http://weblogs.asp.net/adilakhter/archive/2008/05/04/more-on-unit-testing-testcontext.aspx

What is TestContext?

TestContext is a abstract class of Microsoft.VisualStudio.TestTools.UnitTesting namespace that provides various information about the current test run. Purposes that has been served by TestContext Class -

1.  To store information and provide information to the unit tests during Unit Test Run.

2.  Provide a mechanism to measure performance of your code being tested by the Unit Test.

3.  In Testing the web service it stores the additional information, like server's URL.

4.  In Asp.Net unit tests, it get holds of the Page object.

5.  For Data Driven Unit Tests , it provides access to the data rows.



 
Categories: Agile | C# | UnitTest | VS 2008

To retrieve the version number from the assembly in your code, you use can do this:

String strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); 

To retrieve the version number from the assembly that is calling your assembly, you can use this:

String strVersion = System.Reflection.Assembly.GetCallingAssembly().GetName().Version.ToString()


 
Categories: C#

April 19, 2010
@ 09:45 AM
Last week someone asked me about "yield" that he saw in my blog. It is very embarrassed me, I totally forget what it is.
I can't keep the "yield" in my mind because it is not something like "what you see is what it is". it even didn't has "return" in the code scope, that make code not easy to read.  that new feature of c#3.0 need me more time to familiar with.


But the new feature "Default Parameter" in c# 4.0 give me some different feeling ,
This is something very nature and  very easy to use.

private void TestFunction(string username,bool isAdmin=false)
{
    //do something..
}

/// since have Default Parameter, this overLoad function is no more need
//private void TestFunction(string username)
//{
//    TestFunction(username,false);
//}
public void Test()
{
     TestFunction("user");
     TestFunction("user1",true)

 
}


This will make you code cleaner and easier to read in many cases.


 
Categories: C#

I don't like to using Struct just for Performance reason. Because it made it easier to has bug in your application.
And it is worse in Team environment.  If an application has a stuct employeeDTO, because this DTO only hold Employee values and qualify to be a value type .
In one place the code got an EmployeeDTO and stored it to a collection(for example, session or ArrayList).

See code like this
ArrayList EmpList=new ArrayList();
EmpList.add(aEmpDto);

....

EmployeeDTO empDto=(EmpleoyeeDTO)EmpList[0];
empDto.email="newemail@test.com"

or
EmployeeDTO empDto=(EmpleoyeeDTO)Session["MyEmpDTO"];
empDto.email="newemail@test.com"

UnBox happen here. Many people will forget that the employeeDTO is value type and treat it as reference type. They change the value and didn't save it back to session.


if in another page, he want to display this updated email address.
Response.write(((EmpleoyeeDTO)session["myEmployeeDto"]).email)
It will still print the old email address.

you may say a good programmer with good programming habit will not cause that bug. But you can't relay on all the members in your team will never make mistake like this.
So I always avoid to create new value type in my code. I may lost some performance, but prevent some potential bugs.


 
Categories: C#

Here is a example of using yield:

public static IEnumerable<int> Unique(IEnumerable<int> nums)
{
Dictionary<int, int> uniqueVals = new
Dictionary<int, int>();
foreach (int num in nums)
{
if (!uniqueVals.ContainsKey(num))
{
uniqueVals.Add(num, num);
yield return num;
}
}
}


Dompare the typical way and the "yield" to get IEnumerable

# IList<string> FindBobs(IEnumerable<string> names)  
# {
# var bobs = new List<string>();
#
# foreach(var currName in names)
# {
# if(currName == "Bob")
# bobs.Add(currName);
# }
#
# return bobs;
# }
# IEnumerable<string> FindBobs(IEnumerable<string> names)  
# {
# foreach(var currName in names)
# {
# if(currName == "Bob")
# yield return currName;
# }
# }



 
Categories: C# | LINQ and C# 3.0


I found those piece of code in my old project. I forget where to get it. Just post here in case I lost it.


using
System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Security.Cryptography; using System.Text; /// <summary> /// Summary description for Cryptography /// </summary> public static class Cryptography { /// <summary> /// Encrypt a string using dual encryption method. Return a encrypted cipher Text /// </summary> /// <param name="toEncrypt">string to be encrypted</param> /// <param name="useHashing">use hashing? send to for extra secirity</param> /// <returns></returns> public static string Encrypt(string toEncrypt, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); // Get the key from config file string key = (string)settingsReader.GetValue("SecurityKey", typeof(String)); //System.Windows.Forms.MessageBox.Show(key); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string /// </summary> /// <param name="cipherString">encrypted string</param> /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param> /// <returns></returns> public static string Decrypt(string cipherString, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(cipherString); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); //Get your key from config file to open the lock! string key; try { key = (string)settingsReader.GetValue("SecurityKey", typeof(String)); }catch { key = "broadview networks"; } if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return UTF8Encoding.UTF8.GetString(resultArray); } }


 
Categories: C#

Sometime I need resort the ArrayList or List<T> in my code. I am too lazy to write a piece of code to implement IComparer. When I search through google, I found there is a very elegant way to do the sorting:
[code]
peopleList.Sort(
delegate(Person p1, Person p2)
{
return p1.name.CompareTo(p2.name);
}
);

peopleList.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

[/code]
I have used code like this many times, but actually I didn't really understand why code can be wrote like this.
Those are some different way to sorting in different version of .net frameworks,
and those articles helping me to understand the sorting code better.

Thanks to happy九拍
如果不用匿名方法,我们1.1里就的这么写

代码:
static int Compare(Person p1, Person p2)
{
return p1.name.CompareTo(p2.name);
}
然后
代码:
people.Sort(new Comparison<Preson>(Compare));
你的问题解决了,在C#3.0里,我们不再需要匿名方法了,直接lambda咯
代码:
people.Sort((p1, p2) => p1.name.CompareTo(p2.name));

Thanks to Shadal:
2.0可以这样写
static int Compare(Person p1, Person p2)
{
return p1.name.CompareTo(p2.name);
}

people.Sort(Compare);





An userful article:

Variable Scoping in Anonymous Delegates in C#


public void AddScript(ScriptItem script)
{
    ScriptItem match = null;
 
    // *** Grab just the path
    if (!string.IsNullOrEmpty(script.Src))
    {
        script.FileId = Path.GetFileName(script.Src).ToLower();
 
        match = this.InternalScripts.Find(
            delegate(ScriptItem item)
            {
               ScriptRenderModes mode = this.RenderMode;  // demonstrate this pointer
               return (item.FileId == script.FileId);
            });
    }
 
    if (match == null)                
        this.InternalScripts.Add(script);
    else
        match = script;
} 


 
Categories: C# | LINQ and C# 3.0

step 1, Preparing Object Datasource:

UserDs.cs

public class UserDS
{
public ArrayList GetUsers(object login_user)
{
if user is admin return all users, otherwise return login_user in Arralist
return DBControl.GetDashboardUsers((User)login_user);
}
public void SaveUser(string username, string password, string group)
{
DBControl.UpdateUser(username, password, group);
}
public void InsertUser(string username, string password, string group)
{
//if username exsit, then throw excepton..
DBControl.InsertUser(username, password, group);
}

public void Deleteuser(string username)
{
DBControl.DeleteUser(username);
}
}

step 2, Create Object Datasource In Asp page:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Deleteuser"
SelectMethod="GetUsers" TypeName="UserDS" UpdateMethod="SaveUser">
<DeleteParameters>
<asp:Parameter Name="UserName" Type="String" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="UserName" Type="String" />
<asp:Parameter Name="Password" Type="String" />
<asp:Parameter Name="Group" Type="String" />
</UpdateParameters>
<SelectParameters>
<asp:SessionParameter Name="login_user" SessionField="Login_User" Type="Object" />
</SelectParameters>

</asp:ObjectDataSource>

step 3, GridView:

<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="ObjectDataSource1"
GridLines="Horizontal" AutoGenerateColumns=False DataKeyNames="UserName">
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly=true />
<asp:BoundField DataField="Password" AccessibleHeaderText="Password" HeaderText="Password" />
<asp:BoundField DataField="Group" HeaderText="Group" />
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingRowStyle BackColor="#F7F7F7" />
</asp:GridView>


 
Categories: Asp.net | C#