Monday, August 30, 2010

Changing constant value at runtime

In C#, you are allowed to set the value for a constant. This can be done by using the "readonly" keyword.

Normally, when we want to declare a constant that is not updateable through out the application by doing the following:

   public const int MAX_DAYS = 30;


In case, your application would like to allow the system administrator changing the MAX_DAYS value to accommodate their business environment, you need a way to do it. This can be done by replacing the "const" keyword with "readonly":

public class MyConstants
(
public readonly int MAX_DAYS;

public MyConstants()
{
MAX_DAYS = {read the value from database OR config file};
}

)

Monday, August 9, 2010

String Comparison Optimization

String myString = String.Intern("VERY LONG STRING #2");

if (Object.ReferenceEquals(myString, "VERY LONG STRING #1"))
{
...
}

else if (Object.ReferenceEquals(myString, "VERY LONG STRING #2"))
{
...
}

else if (Object.ReferenceEquals(myString, "VERY LONG STRING #3"))
{
...
}

...

else

{

...

}

Reference:
http://dotnetfacts.blogspot.com/2008/03/how-to-optimize-strings-comparison.html
http://msdn.microsoft.com/en-us/library/system.string.intern%28vs.71%29.aspx

Wednesday, August 4, 2010

Adding DLL reference automatically

It's quite sad when you are trying to add new reference by using the Add Reference provided in the Visual Studio because it is very slow. To speed up the process, you may have to add the following Macro and run it manually. It will add all your Dll references in one click:

    '4-8-10,lhw
'-add the commonly used dll to the selected project.
' No need to go through the Add Reference screen in VS.
Sub AddGeneralReferences()
Dim proj As EnvDTE.Project
Dim arr As Array = DTE.ActiveSolutionProjects

If Not arr Is Nothing Then
If arr.Length > 0 Then
proj = arr(0)

If Not proj Is Nothing Then
Dim v As VSLangProj.VSProject = proj.Object
Dim r As VSLangProj.References = v.References

If Not r Is Nothing Then
r.Add("System.configuration")
r.Add("System.Drawing")

'not sure why must include the
'full reference to system.web dll.
'Otherwise, COM error will occur.
r.Add("C:\WINDOWS\Microsoft.NET" & _
"\Framework\v2.0.50727\System.Web.dll")

r.Add("System.Web.Services")
End If
End If
End If
End If
End Sub