Monday, August 30, 2010

Use Button CommandName, CommandArgument Property to dynamically Call Button Command Events

Button Server Control has two types: submit and command. By default a button is a submit button which doesn't have commandname, commandArguments, and it has button.Click events as the default event. We can create command button using the following steps.

Create a Web Application, in the designer drag 4 buttons:

Set the CommandName Property to be: btn1Command, btn2Command, btn3Command, btn4Command. And CommandArgument to be: Asc, Desc, Upper, Lower.

The Source is like:

< body>
< id="form1" runat="server" method="post" action="Default.aspx">
  < id="Button1" runat="server" commandname="btn1Command" text="NAsc" commandargument="Asc">
   < id="Button2" runat="server" commandname="btn2Command" text="NDesc" commandargument="Desc">
   < id="Button3" runat="server" commandname="btn3Command" text="LUpper" commandargument="Upper">
   < id="Button4" runat="server" commandname="btn4Command" text="LLower" commandargument="Lower">
  < /form>
< /body>

In the Events window, set these 4 buttons Command to be: Button_Command, double click, and write in the Button_Command Event the following code:

protected void Button_Command(object sender, CommandEventArgs e)
{
 switch (e.CommandName)
 {
   case "btn1Command":
   ShowNumbers(e.CommandArgument);
   break;
   case "btn2Command":
   ShowNumbers(e.CommandArgument);
   break;
   case "btn3Command":
   ShowLetters(e.CommandArgument);
   break;
   case "btn4Command":
   ShowLetters(e.CommandArgument);
   break;
  }
}

And Write the ShowNumbers, ShowLetters Methods:

private void ShowNumbers(object commandArgument)
{
  if (commandArgument.ToString() == "Asc")
  {
   Response.Write("123");
  }
  else if (commandArgument.ToString() == "Desc")
  {
   Response.Write("321");
  }
}

private void ShowLetters(object commandArgument)
{
  if (commandArgument.ToString() == "Upper")
  {
   Response.Write("AAA");
  }
  else if (commandArgument.ToString() == "Lower")
  {
   Response.Write("aaa");
  }
}

Build the web application to test the button commands. The sample code is at:

http://groups.google.com/group/jiezhu0815myfiles/web/ButtonCommandSample.rar

Wednesday, August 25, 2010

Array.Find(), Array.FindLast() and Array.FindAll()

static void Main(string[] args)
{
string[] arr = new string[5] { "tests", "Google", "good","yes","grey" };

Console.WriteLine(Array.Find(arr, StartwithG));
Console.WriteLine(Array.FindLast(arr, StartwithG));

string[] arrstartwithg = Array.FindAll(arr, StartwithG);
foreach (string str in arrstartwithg)
{
Console.WriteLine(str);
}

}

static bool StartwithG(string str)
{
if (str.ToLower().StartsWith("g"))
return true;
else return false;
}

Compare Array has equalent element

string[] arr1=new string[3]{"a","b","c"}
string[] arr2=new string[3]{"a","b","c"}

arr1==arr2 //false
arr1.Equals(arr2) //false
arr1.SequenceEqual(arr2) //true

Tuesday, August 24, 2010

Recall the Use of Delegate

1.Define delegate use function signature:

ex.

delegate string MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate d=myFunc;
Console.WriteLine(d(5));
}
static string MyFunc(int a)
{
return a.ToString();
}

2. Use delegate to call back a function,
change the code MyDelegate d=myFunc to MyDelegate d=new MyDelegate(myFunc);

The code will be:

delegate string MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate d=new MyDelegate(myFunc);
Console.WriteLine(d(5));
}
static string MyFunc(int a)
{
return a.ToString();
}

3. Multicast delegate:

delegate void MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate d=(MyDelegate)myFunc1+(MyDelegate)myFunc2-(MyDelegate)myFunc1;
d(5);
}
static void MyFunc1(int a)
{
Console.WriteLine(a.ToString());
}
static string MyFunc2(int a)
{
Console.WriteLine("second function:"+a.ToString());
}

4. Delegate Chain:

delegate void MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate[] ds= new MyDelegate[]{(MyDelegate)myFunc1,(MyDelegate)myFunc2};
MyDelegate d=(MyDelegate)Delegate.Combine(ds);
d(5);
}
static void MyFunc1(int a)
{
Console.WriteLine(a.ToString());
}
static string MyFunc2(int a)
{
Console.WriteLine("second function:"+a.ToString());
}

5. delegate call anonymous method:

delegate void MyDelegate(int myint);

static void Main(args[])
{
MyDelegate d=delegate(int i){Console.WriteLine(i.ToString());}
d(5);
}

delegate to call anonymous method can be represented as lambda expression, so we can also write the above code as:

delegate void MyDelegate(int myint);

static void Main(args[])
{
MyDelegate d=(int i)=>{Console.WriteLine(i.ToString());};
d(5);
}

Func< T,Tresult> , Action< T> and Predicate< T>

There are many Pre-defined delegates in C#, such as eventhandler, Predicate.

Func and Action two pre-defined delegate:

The syntax for Funcion is:

public delegate TResult Func(
T arg
)

The syntax for Action is:

public delegate void Action< in T>(
T obj
)

So Func and Action are essentially a special delegate:

We can use: Func myfunc=delegate(T para){ //Some method return Tout;}
//delegate calling an anonymous method;
Action myAction=delegate(T para){ //somemethod return void;}
//delegate calling an anonymous method;

As well, lambda expression can be considered as a special delegate calling an anonymous method: on the "=>" left side is the parameters to input, on the "=>" right side is the method, if the method return void, the delegate is void and if the method returns some type, the delegate returns some type.

So we can write:
Fun myFunc=(T para)=>(//Some method returns Tout);
Action myAct=(T para)=>(//Some method return void);

Here is some examples:

Func myFunc= delegate(string s)
{
return s.ToUpper();
};

We can write as: Func myFunct= (string s)=>s.ToUpper();

Console.WriteLine(myFunct("This is a test for Func delegate"));

As well for Action:

Action myAction=delegate(string s)
{
Console.WriteLine(s);
}

We can also write as Action myAction=(string s)=>{Console.WriteLine(s)};

Test the above code:

myAction("This is a test for Action delegate");

Predicate is the same thing, except the function called return boolean, it can also be written lambda expression.

Wednesday, August 18, 2010

Some of the Testing Tools

*****TestDriven.Net
--Open source, see www.testdriven.net

****AutoRunner
--For automatic testing

***BorlandSilkTest

***Fit/Fitnesse For .net

***IBM Rational Functional Tester

**Compuware TestPartner

Use Query String to pass values between pages

Example: http://...../form.aspx?param1=career¶m2=ride

First Page, Rediret page from text input:

private void ButtonSubmit_Click(object sender, eventArgs e)
{
Response.Redirect("form.aspx?param1="+this.Form.Text1.Text +"¶m2="
+this.Form.Text);
}

Second Read value from query string:

private void Page_Load(object sender, eventArgs e)
{
Text1.Text=Request.QueryString["Param1"];
Text2.Text=Request.QueryString["Param2"];
}

ADO.net Connection Pool (1)

In ADO.net, if every time we perform a query, we create a new connection. Like the following:

//connection1
Sqlconnection sqlcon=new Sqlconnction();
sqlcon.ConnectionString = constring + "database = DB1;Integrated Security=true";
sqlcon.Open();
sqlcon.Close();


//connetion2
Sqlconnection sqlcon=new Sqlconnction();
sqlcon.ConnectionString = constring + "database = DB2;Integrated Security=true";
sqlcon.Open();
sqlcon.Close();

//connection1
Sqlconnection sqlcon=new Sqlconnction();
sqlcon.ConnectionString = constring + "database = DB1;Integrated Security=true";
sqlcon.Open();
sqlcon.Close();

//connection1
Sqlconnection sqlcon=new Sqlconnction();
sqlcon.ConnectionString = constring + "database = DB1;Uid=sa ;Pwd=password";
sqlcon.Open();
sqlcon.Close();

//connection2
Sqlconnection sqlcon=new Sqlconnction();
sqlcon.ConnectionString = constring + "database = DB2;Integrated Security=true";
sqlcon.Open();
sqlcon.Close();

If for every query or transation there create a new connection, this will waste the resources, as create new connection will take time, which will cause the query slow for users.

ADO.net has the connection pool mechanism. For the created connections, they are placed in the connection pool, the connection object can be used from the pool in stead of initialize a new connection object. After a specific of time period, if a connection is not used, it can be disposed.

The connection pool can be created by the sqlconnection string, pretty much like:
SqlConnection mySqlConnection =
new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;" +
"max pool size=10;min pool size=5"
);

Monday, August 16, 2010

C# 4.0 Feature (1) Concurrent Collections

Before C# 4.0 comming out, there is no concurrent collections. So there is thread safety issue about the collections if mutiple thread access these collections.

Traditional way we do is lock the collection's syncroot property.

For example:

Hashtable ht=new Hashtable();
lock (ht.SyncRoot)
{
...//do somthing
}

Notice that the lock of "this" (lock(this)). or lock of an object instance is not a thread safe method. And Syncronized method is not thread safe for collections as well.

After C# 4.0 comming out, there is a new data structure: Concurrent Collection, and this data type makes thread safe.

We write an sample code below to use Concurrent Collection:

using System;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Concurrent;

class Program
{
static void Main(string[] args)
{
var links = new ConcurrentQueue();
links.Enqueue("http://....aa.jpg");
links.Enqueue("http://....bb.jpg");
links.Enqueue("http://....cc.jpg");


Parallel.For(0, links.Count, delegate(int i)
{
string url;
string filename = "Product"+i + "test.jpg";
if (links.TryDequeue(out url))
{

DownLoad(url, filename);
}
});
}

private static void DownLoad(string url,string filename)
{
using (WebClient wc = new WebClient())
{
wc.DownloadFile(url, filename);
}
}
}

For the other Concurrent Data Type, such as ConcurrentBag, ConcurrentStack, ConcurrentList, please check msdn for use.

Wednesday, August 11, 2010

Integrate Microsoft BizTalk/TIBCO with Sharepoint

BizTalk or TIBCO as the midware is currently very hot. And the instant message system can make our job live. For my current work, we have ticket system, but those are pretty static and not instant communicate with client. BizTalk or TIBCO as a hot midware use Service Oriented Architecture, and seems a hot tool to improve our job. For example we can have the instant request from the client and we can have the instant message in the company use as well.

During my work on Sharepoint, to my feeling, Sharepoint is like a "container", it can host workflow, sql server reporting service, silverlight controls et al. But to costomize some of the forms/web parts is very annoying. After watching Microsoft introduction (http://www.microsoft.com/biztalk/en/us/click-through-demo/hol.htm),we can find combine sharepoint with BizTalk or TIBCO is more than just a "fancy" technique but very useful here.

But currently the tutorial on intergrate BizTalk/TIBCO is very few. In the near future in my spare time, I would do some research on this field and may keep posting some series on what I figure out.