The simplest way to get hash password is as follows.
FormsAuthentication.HashPasswordForStoringInConfigFile("value of string", FormsAuthPasswordFormat.MD5.ToString());
Remember to import the following namespaces.
using System.Web.Security;
using System.Web.Configuration;
Sunday, April 4, 2010
Get MD5 hash password to store in config file
Saturday, September 12, 2009
Retrieve total Number of elements in jQuery
$('table').size();
Replace string in jQuery
var objElement = $('#id');
objElement.html(objElement.html().replace(/word/ig, ""));
How to disable browser right-click using jQuery
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
Friday, September 11, 2009
Simple and easy paging with LINQ !!!
Before LINQ, if we want to implement custom paging (i.e. only extract those data pages that is displayed in GridView. If there is 10 rows per page, only extract 10 rows from database) , we have to write additional codes in our SQL stored procedure to return those data rows needed to display on a particular GridView page.
Take a look at the following codes !!! Have fun!
Design View LINQTest1.aspx

Code Behind file LINQTest1.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace LINQTest
{
public partial class LINQTest1 : System.Web.UI.Page
{
private int pageSize = 10;
public int CurrentPageIndex
{
get
{
return Convert.ToInt32(ViewState["CurrentPageIndex"]);
}
set
{
ViewState["CurrentPageIndex"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CurrentPageIndex = 0;
LoadContact(0);
}
//using System.Data.Linq; Add Reference ...
/* Simple ...
DataContext context = new DataContext(@"Initial Catalog=AdventureWorks;Data Source=.\SQLEXPRESS;Integrated Security=sspi");
Table
var query =
from c in contact
where c.FirstName.StartsWith("S")
&& c.LastName.StartsWith("K")
orderby c.LastName
select c;
String strNames = String.Empty;
foreach (var item in query)
strNames += item.FirstName + " " + item.LastName + " " +
item.EmailAddress + "
";
Response.Write(strNames);
*/
}
private int GetTotalPages()
{
DataContext context = new DataContext(@"Initial Catalog=AdventureWorks;Data Source=.\SQLEXPRESS;Integrated Security=sspi");
Table
var query =
(from c in contact
where c.FirstName.StartsWith("S")
&& c.LastName.StartsWith("K")
orderby c.LastName
select new { c.ContactID, c.FirstName, c.LastName, c.EmailAddress }).Count();
int nPages = query / 10;
if (query % 10 != 0)
{
nPages++;
}
return nPages;
}
private void LoadContact(int startRowindex)
{
DataContext context = new DataContext(@"Initial Catalog=AdventureWorks;Data Source=.\SQLEXPRESS;Integrated Security=sspi");
Table
var query =
(from c in contact
where c.FirstName.StartsWith("S")
&& c.LastName.StartsWith("K")
orderby c.LastName
select new { c.ContactID, c.FirstName, c.LastName, c.EmailAddress }).Skip(startRowindex).Take(pageSize).ToList();
gvContact.DataSource = query;
gvContact.DataBind();
}
protected void gvContact_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
txtConactID.ReadOnly = true;
txtConactID.Attributes.Add("style", "background-Color:#FFFF80");
int nResult = 0;
AdventureWorks context = new AdventureWorks(@"Initial Catalog=AdventureWorks;Data Source=.\SQLEXPRESS;Integrated Security=sspi");
var result = context.ContactsByID(Convert.ToInt32(e.CommandArgument.ToString()), ref nResult);
foreach (GetContactsByID obj in result)
{
txtConactID.Text = obj.ContactID.ToString();
txtFirstName.Text = obj.FirstName;
txtLastName.Text = obj.LastName;
txtEmailAddress.Text = obj.EmailAddress;
}
int count = 0;
result = context.GetContacts("A", ref nResult);
foreach (GetContactsByID obj in result)
{
txtConactID.Text = obj.ContactID.ToString();
txtFirstName.Text = obj.FirstName;
txtLastName.Text = obj.LastName;
txtEmailAddress.Text = obj.EmailAddress;
count++;
}
Response.Write("Count : " + count.ToString());
}
}
protected void gvContact_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void gvContact_PageIndexChanged(object sender, EventArgs e)
{
}
protected void gvContact_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
LoadContact(e.NewPageIndex * pageSize);
}
protected void BtnPrev_Click(object sender, EventArgs e)
{
if (CurrentPageIndex - 1 < currentpageindex =" CurrentPageIndex">= GetTotalPages())
return;
LoadContact((CurrentPageIndex + 1) * pageSize);
CurrentPageIndex = CurrentPageIndex + 1;
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
DataContext context = new DataContext(@"Initial Catalog=AdventureWorks;Data Source=.\SQLEXPRESS;Integrated Security=sspi");
Table
Contact objContact = contact.Single(c => c.ContactID == Convert.ToInt32(txtConactID.Text));
objContact.FirstName = txtFirstName.Text.Trim();
objContact.LastName = txtLastName.Text.Trim();
objContact.EmailAddress = txtEmailAddress.Text.Trim();
context.SubmitChanges();
LoadContact(0);
}
}
}
There is additional coding for DataAccess part.
AdventureWorks.cs
using System;
using System.Data;
using System.Data.Linq;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//Add Reference to Microsoft.SqlServer.Smo, Microsoft.SqlServer.ConnectionInfo
using Microsoft.SqlServer.Management.Smo;
using System.Collections;
using System.Reflection;
using System.Data.Linq.Mapping;
public class AdventureWorks : DataContext
{
public AdventureWorks(string connection) : base(connection) { }
[Function(Name = "GetContactsByID")]
public ISingleResult
([Parameter(Name = "ContactID", DbType = "int")] int contactID, [Parameter(Name = "Result", DbType = "int")] ref int nResult)
{
var result = this.ExecuteMethodCall
(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())),
contactID, nResult);
nResult = (int)result.GetParameterValue(1);
return (ISingleResult
}
[Function(Name = "GetContacts")]
public ISingleResult
([Parameter(Name = "FirstName", DbType = "nvarchar")] string firstName, [Parameter(Name = "Result", DbType = "int")] ref int nResult)
{
var result = this.ExecuteMethodCall
(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())),
firstName, nResult);
nResult = (int)result.GetParameterValue(1);
return (ISingleResult
}
}
[Table(Name = "ContactTable")]
public partial class GetContactsByID
{
[Column(DbType = "int", IsPrimaryKey = true, IsDbGenerated = true)]
public int ContactID;
[Column(DbType = "nvarchar(8) not null")]
public string Title;
[Column(DbType = "nvarchar(50) not null")]
public string FirstName;
[Column(DbType = "nvarchar(50) not null")]
public string MiddleName;
[Column(DbType = "nvarchar(50) not null")]
public string LastName;
[Column(DbType = "nvarchar(50) not null")]
public string EmailAddress;
}
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
//Add Ref to Microsoft.SqlServer.Smo, Microsoft.SqlServer.ConnectionInfo
using Microsoft.SqlServer.Management.Smo;
using System.Collections;
[Table(Name = "Person.Contact")]
public class Contact
{
[Column(DbType = "int", IsPrimaryKey = true, IsDbGenerated = true)]
public int ContactID;
[Column(DbType = "nvarchar(8) not null")]
public string Title;
[Column(DbType = "nvarchar(50) not null")]
public string FirstName;
[Column(DbType = "nvarchar(50) not null")]
public string MiddleName;
[Column(DbType = "nvarchar(50) not null")]
public string LastName;
[Column(DbType = "nvarchar(50) not null")]
public string EmailAddress;
[Column(DbType = "int")]
public int EmailPromotion;
}
Friday, September 4, 2009
C# Threading
We are going to take a look at how to use C#'s ThreadPool - which is probably the simplest way to make a multi-threaded C# app.
A thread pool takes away all the need to manage your threads - all you have to do is essentially say "hey! someone should go do this work!", and a thread in the process' thread pool will pick up the task and go execute it. And that is all there is to it. Granted, you still have to keep threads from stepping on each other's toes, and you probably care about when these 'work items' are completed - but it is at least a really easy way to queue up a work item.
In fact, working with the ThreadPool is so easy, I'm going to throw all the code at you at once. Below is a pretty simple test app that gives 5 (or NumThreads) work items to the ThreadPool, waits for them all to complete, and then prints out all the answers. I will walk through the code step by step below:
using System.Threading;
namespace ThreadPoolTest
{
class Program
{
private const int NumThreads = 5;
private static int[] inputArray;
private static double[] resultArray;
private static ManualResetEvent[] resetEvents;
private static void Main(string[] args)
{
inputArray = new int[NumThreads];
resultArray = new double[NumThreads];
resetEvents = new ManualResetEvent[NumThreads];
Random rand = new Random();
for (int s = 0; s < NumThreads; s++)
{
inputArray[s] = rand.Next(1,5000000);
resetEvents[s] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(n
}
Console.WriteLine("Waiting..."
WaitHandle.WaitAll(resetEvents
Console.WriteLine("And the answers are: ");
for (int i = 0; i < NumThreads; i++)
Console.WriteLine(inputArray[i
}
private static void DoWork(object o)
{
int index = (int)o;
for (int i = 1; i < inputArray[index]; i++)
resultArray[index] += 1.0 / (i * (i + 1));
resetEvents[index].Set();
}
}
}
We have three arrays at the top of the program: one for input to the work items (inputArray), one for the results (resultArray), and one for the ManualResetEvents (resetEvents). The first two are self explanatory, but what is a ManualResetEvent? Well, it is an object that allows one thread to signal another thread when something happens. In the case of this code, we use these events to signal the main thread that a work item has been completed.
So we initialize these arrays, and then we get to a for loop, which is where we will be pushing out these work items. First, we make a random value for the initial input (cause random stuff is always more fun!), then we create a ManualResetEvent with its signaled state initially set to false, and then we queue the work item. Thats right, all you have to do to push a work item out for the ThreadPool to do is call ThreadPool.QueueUserWorkItem.
So what are we queuing here? Well, we are saying that a thread in the thread pool should run the method DoWork, with the argument s. Any method that you want to queue up for the thread pool to run needs to take one argument, an object, and return void. The argument will end up being whatever you passed in as the second argument to the QueueUserWorkItem call - and in this case is the 'index' of this work item (the index in the various arrays that it needs to work with). And it makes sense that the method would have to return void - because it isn't actually returning 'to' anything, it is running out there all on its own as a separate thread.
So what are we doing in this DoWork function? Not that much in this case, just a simple summation. The important part is the very last call of the function, which is hit when all the work for this work item is done - resetEvents[index].Set(). This triggers the ManualResetEvent for this work item - signaling the main thread that the work is all done here.
Back up in main thread land, after it has pushed all these work items onto the ThreadPool queue, we hit the very important call WaitHandle.WaitAll(. This causes the main thread to block here until all the ManualResetEvent objects in the resetEvents array signal. When all of them have signaled, that means that all the work units have been completed, and so we continue on and print out all the results. The results change because we are seeding with random values, but here is one example output:
And the answers are:
3780591 -> 0.991001809831479
3555614 -> 0.991163782231558
2072717 -> 0.989816715560308
2264396 -> 0.989982111762391
544144 -> 0.99066981542858
There are a couple things to note, though. The default thread pool size for a process is 25 threads, and while you can change this number, this resource is not infinite. If all of the threads in the pool are currently occupied with other tasks, new work items will be queued up, but they won't get worked on until one of the occupied threads finishes its current task. This generally isn't a problem unless you are giving the pool very large quantities of work. And really, you should never assume that a task is executed immediately after you queue it, because there is no guarantee of that at all.
That's it for this intro to thread pools in C#. If there are any questions, leave them below - especially if they push on the more advanced aspects of threads and thread pools (cause then I'll have an excuse to write some more threading tutorials!.
C# delegate
Basically it is similar like the old "C" age function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions. C# delegate is the smarter version of function pointer which helps software architects a lot, specially while utilizing design patterns.
At first, a delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function. The function will then can be called via the delegate object.
Let's see how it works!
1. Defining the delegate
public delegate int Calculate (int value1, int value2); 2. Creating methods which will be assigned to delegate object
//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate
public int add(int value1, int value2)
{
return value1 + value2;
}
//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate
public int sub( int value1, int value2)
{
return value1 - value2;
}
3. Creating the delegate object and assigning methods to those delegate objects
//creating the class which contains the methods
//that will be assigned to delegate objects
MyClass mc = new MyClass();
//creating delegate objects and assigning appropriate methods
//having the EXACT signature of the delegate
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);
4. Calling the methods via delegate objects
//using the delegate objects to call the assigned methods
Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));