Archive for February, 2011

jQuery Attribute Selector

Use following selector to cooperate controls generated from

Attribute Contains Selector [name*=”value”]
Attribute Starts With Selector [name^=”value”]
Attribute Ends With Selector [name$=”value”]

No Comments

List uses IEquatable<(Of <(T>)>) interface

In order to use List.Contains(object) to check if the object is added in the list, the object have to use IEquatable interface.

For Example, if you want to do the following logic,

List<Car> myCars = new List<Car>();

You have to define the object Car as below,

public class Car : IEquatable<Car>
    public string Name;

    public Car(string name)
        this.Name = name;

    public bool Equals(Car other)
        if (other == null) return false;
        return (this.Name.Equals(other.Name));

No Comments

Using Log4net in


Log4net is an Open Source utility used for log/report statements to various kinds of output targets (text file, email, database, event viewer etc.): It can be a very handy utility for application instrumentation purposes.

Configuring Log4net

Step 1: Add a reference of Log4net.dll to the project.

Step 2: Add Global.asax to the project, if not already added. In the “Application_Start” event of global.asax, add the following code:


Step 3: In the web.config file, under Configuration->Configsections, add the following section:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

Step 4: In web.config, add a new section “”. This section will contain all the settings related to the Log4net configuration.

Step 5: In web.config, under “log4net” section, add the required appenders (output target) configuration sections in the following way:

File appender configuration, used for log statements in a text file

<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
  <param name="File" value="Logs\\Log4Net.log"/>
  <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>

Step 6: In the web.config file, under “log4net” section, for each appender, add loggers in the following way:

<logger name="File">
<level value="All" />
<appender-ref ref="LogFileAppender" />
<logger name="EmailLog">
<level value="All" />
<appender-ref ref="SmtpAppender" />

Step 7: Now, whenever we want to log any information/error/warning, call the appropriate method in the following manner:

//for logging to file
log4net.ILog logger = log4net.LogManager.GetLogger("File");

logger.Info("Starting page load");

Copied from :

No Comments

Caching Web Services in

The caching is by parameter. Therefore different parameter is entered, different result will be cached.

public string GetCacheEntryTime(string Name)
	StringBuilder sb = new StringBuilder("Hi ");
	sb.Append(", the Cache entry was made at ");

No Comments

Bulk Upload Projects to Team Foundation Server

1. Place all projects in one folder
2. In Visual Studio > “Team Explorer” > Create a “New Team Project”
3. In the newly created team project, double click “Source Control”
4. In “Source Control”, right click the newly created team project, press “Add Items to Folder”
5. Add all projects, and choose “Check In Pending Changes” again…

No Comments

Killing Excel Process when Using Excel Object Model in .net

1. Following is the method you need to included in the class.

private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

/// <summary> Tries to find and kill process by hWnd to the main window of the process.</summary>
/// <param name="hWnd">Handle to the main window of the process.</param>
/// <returns>True if process was found and killed. False if process was not found by hWnd or if it could not be killed.</returns>
public static bool TryKillProcessByMainWindowHwnd(int hWnd)
	uint processID;
	GetWindowThreadProcessId((IntPtr)hWnd, out processID);
	if (processID == 0) return false;
	catch (ArgumentException)
		return false;
	catch (Win32Exception)
		return false;
	catch (NotSupportedException)
		return false;
	catch (InvalidOperationException)
		return false;
	return true;

/// <summary> Finds and kills process by hWnd to the main window of the process.</summary>
/// <param name="hWnd">Handle to the main window of the process.</param>
/// <exception cref="ArgumentException">
/// Thrown when process is not found by the hWnd parameter (the process is not running). 
/// The identifier of the process might be expired.
/// </exception>
/// <exception cref="Win32Exception">See Process.Kill() exceptions documentation.</exception>
/// <exception cref="NotSupportedException">See Process.Kill() exceptions documentation.</exception>
/// <exception cref="InvalidOperationException">See Process.Kill() exceptions documentation.</exception>
public static void KillProcessByMainWindowHwnd(int hWnd)
	uint processID;
	GetWindowThreadProcessId((IntPtr)hWnd, out processID);
	if (processID == 0)
		throw new ArgumentException("Process has not been found by the given main window handle.", "hWnd");

2. When create the excel application, the process ID (Hwnd) is captured. Which is used to kill the process afterwards.

Excel.Application excel = new Excel.Application();
int hWnd = excel.Hwnd;
Excel.Workbook wb = excel.Workbooks.Open(fi.FullName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Excel.Worksheet mainSheet = (Excel.Worksheet)wb.ActiveSheet;

string name = ((Excel.Range)mainSheet.Cells[7, 4]).Value2.ToString();
string staffNo = ((Excel.Range)mainSheet.Cells[9, 4]).Value2.ToString();
string mobileNo = ((Excel.Range)mainSheet.Cells[11, 4]).Value2.ToString();
int NoOfPpl = Convert.ToInt16(((Excel.Range)mainSheet.Cells[13, 4]).Value2.ToString());
string selectedDate = "";



No Comments

Numeric Only Validator

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Please Enter Only Numbers" ValidationExpression="^\d+$" ValidationGroup="check" />

No Comments

Create Custom Validator in

1. Add Custom Validator in page

Custom text:<br />
<asp:TextBox runat="server" id="txtCustom" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" ClientValidationFunction="validateStaffNoOrStaffNameNotEmpty" />

2. Create Custom Validator Event

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
if(e.Value.Length == 10)
e.IsValid = true;
e.IsValid = false;

3. Add java script client side validation (this help the performance by should not be trusted!!!)

<script type="text/javascript">
     function validateStaffNoOrStaffNameNotEmpty(source, args){
       var sStaffNo = document.getElementById("<%= StaffNumberTextBox.ClientID %>").value;
       var sStaffName = document.getElementById("<%= StaffNameTextBox.ClientID %>").value;
       if (sStaffNo == "" && sStaffName == "")
          args.IsValid = false;
          args.IsValid = true;

No Comments

Implementing Role-Based Security for Site Map in

1. While the XSD for .sitemap files (from which the IntelliSense is derived) includes “securityTrimmingEnabled” attribute, it’s incorrect. It’s the result of an old VS 2005 bug that’s still around. That value should be set in web.config; we’ll take care of that next.

2. Define the siteMap in web.config, and add securityTrimmingEnabled=”true” as below,

<siteMap enabled="true">
    <add siteMapFile="Web.sitemap" name="AspNetXmlSiteMapProvider" type="System.Web.XmlSiteMapProvider" securityTrimmingEnabled="true"/>

No Comments

Loading JSON Result to Javascript Array, and use jQuery autocomplete

	url: "/Services/GetMasterData.asmx/GetLocations",
	data: "{ 'prefixText': '' }",
	dataType: "json",
	type: "POST",
	contentType: "application/json; charset=utf-8",
	dataFilter: function (data) { return data; },
	success: function (data) {
		availableTags = eval("(" + data.d + ")");

			source: availableTags,
			minLength: 1
	error: function (XMLHttpRequest, textStatus, errorThrown) {
  • availableTags = eval(“(” + data.d + “)”); <- The JSON returned by : JavaScriptSerializer().Serialize(result.ToArray()) is missing ‘(‘, therefore add it back and use eval here
  • Start $(‘[id$=LocationTextBox]’).autocomplete ONLY after the .ajax success since the variable availableTags will be cached and cannot be updated afterwards
  • data: “{ ‘prefixText’: ” }”, <- is the data input to the web services, the “prefixText” should be the variable name of the parameter

Below is the CSharp code to create the web services

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetLocations(string prefixText)
	List<string> result = new List<string>();

	using (DatabaseHelper myDbHelper = DbUtility.getDBConnection())
		string query = "SELECT column from table";
		myDbHelper.AddParameter("@prefixText", prefixText);

		DbDataReader myDataReader = myDbHelper.ExecuteReader(query);
		if (myDataReader.HasRows)
			while (myDataReader.Read())

	return new JavaScriptSerializer().Serialize(result.ToArray());;



No Comments