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));VB6 Function for AlphaNumeric Checking
Public Function IsAlphaBetical(TestString As String) As Boolean
Dim sTemp As String
Dim iLen As Integer
Dim iCtr As Integer
Dim sChar As String
'returns true if all characters in a string are alphabetical
'returns false otherwise or for empty string
sTemp = TestString
iLen = Len(sTemp)
If iLen > 0 Then
For iCtr = 1 To iLen
sChar = Mid(sTemp, iCtr, 1)
If Not sChar Like "[A-Za-z]" Then Exit Function
Next
IsAlphaBetical = True
End If
End Function
Public Function IsAlphaNumeric(TestString As String) As Boolean
Dim sTemp As String
Dim iLen As Integer
Dim iCtr As Integer
Dim sChar As String
'returns true if all characters in a string are alphabetical
' or numeric
'returns false otherwise or for empty string
sTemp = TestString
iLen = Len(sTemp)
If iLen > 0 Then
For iCtr = 1 To iLen
sChar = Mid(sTemp, iCtr, 1)
If Not sChar Like "[0-9A-Za-z]" Then Exit Function
Next
IsAlphaNumeric = True
End If
End Function
Public Function IsNumericOnly(TestString As String) As Boolean
Dim sTemp As String
Dim iLen As Integer
Dim iCtr As Integer
Dim sChar As String
'returns true if all characters in string are numeric
'returns false otherwise or for empty string
'this is different than VB's isNumeric
'isNumeric returns true for something like 90.09
'This function will return false
sTemp = TestString
iLen = Len(sTemp)
If iLen > 0 Then
For iCtr = 1 To iLen
sChar = Mid(sTemp, iCtr, 1)
If Not sChar Like "[0-9]" Then Exit Function
Next
IsNumericOnly = True
End If
End Function
How To: Reading and Writing Text Files
Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy. The following sequence outlines the basic steps necessary to work with text files:
1. Open the file
2. Read/Write to the file
3. Close the file
It's that simple. Listing 1 shows how to write text data to a file.
Writing to a Text File
Listing 1: Writing Text Data to a File: TextFileWriter.cs
using System;
using System.IO;
namespace csharp_station.howto
{
class TextFileWriter
{
static void Main(string[] args)
{
// create a writer and open the file
TextWriter tw = new StreamWriter("date.txt");
// write a line of text to the file
tw.WriteLine(DateTime.Now);
// close the stream
tw.Close();
}
}
}
This program creates a text file when it runs. In the directory where the executable program is located, you'll find a file named date.txt. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran:
2/15/2002 8:54:51 PM
The first task in Listing 1 is to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, the StreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding. Here's the line that opens the date.txt file:
TextWriter tw = new StreamWriter("date.txt");
Using the TextWriter instance, tw, you can write text info to the file. The example writes the text for the current date and time, using the static Now property of the DateTime class. Here's the line from the code:
tw.WriteLine(DateTime.Now);
When you're done writing to the file, be sure to close it as follows:
tw.Close();
Reading From a Text File
Listing 2: Reading Text Data from a File: TextFileReader.cs
using System;
using System.IO;
namespace csharp_station.howto
{
class TextFileReader
{
static void Main(string[] args)
{
// create reader & open file
Textreader tr = new StreamReader("date.txt");
// read a line of text
Console.WriteLine(tr.ReadLine());
// close the stream
tr.Close();
}
}
}
In Listing 2, the text file is opened in a manner similar to the method used in Listing 1, except it uses a StreamReader class constructor to create an instance of a Textreader. The StreamReader class includes additional overloads that allow you to specify the file in different ways, text format encoding, and buffer info. This program opens the date.txt file, which should be in the same directory as the executable file:
Textreader tr = new StreamReader("date.txt");
Within a Console.WriteLine statement, the program reads a line of text from the file, using the ReadLine() method of the Textreader instance. The Textreader class also includes methods that allow you to invoke the Read() method to read one or more character or use the Peek() method to see what the next character is without pulling it from the stream. Here's the code that reads an entire line from the text file:
Console.WriteLine(tr.ReadLine());
When done reading, you should close the file as follows:
tr.Close();
Summary
This article showed how to write text to a file and read it back out. For more details on additional methods, consult the .NET Frameworks reference on the StreamWriter, StreamReader, TextWriter, and Textreader classes.
How to format a value using T-SQL: pad left
CREATE FUNCTION [dbo].[PadString]
(@Seq varchar(16),
@PadWith char(1),
@PadLength int
)
RETURNS varchar(16) AS
BEGIN
declare @curSeq varchar(16)
SELECT @curSeq = ISNULL(REPLICATE(@PadWith, @PadLength - len(ISNULL(@Seq ,0))), '') + @Seq
RETURN @curSeq
END
Testing the function:
SELECT dbo.PadString ('8', '0', 5)
SELECT dbo.PadString ('abc', '*', 12)
SELECT dbo.PadString ('abc', '0', 7)
Here are the results:
----------------
00008
(1 row(s) affected)
----------------
*********abc
(1 row(s) affected)
----------------
0000abc
(1 row(s) affected)
"Extention Methods" are new feature in C# 3.0 and above. We could define them as static methods that extend existing classes.
If we wanted to do something like that in the past we had to derive from the selected class and extend it with whatever we wanted. But what if that class is a sealed class? Extention methods come in just for that.
Lets say we need to reverse a string. Before we had extention methods we would probably have something like this:
public class StringOperations
{
public static string ReverseString(string str)
{
string i = string.Empty;
foreach (char c in str)
{
i = i.Insert(0, c.ToString());
}
return i;
}
}
And we would use it like this:
static void Main(string[] args)
{
string g = StringOperations.ReverseString("abcd");
}
Well now we don’t have to. We can actually attach the ReversString method to the string object! Here’s how:
namespace System
{
public static class Extentions
{
//notice that we use this as the parameter.
public static string Reverse(this string str)
{
string i = string.Empty;
foreach (char c in str)
{
i = i.Insert(0, c.ToString());
}
return i;
}
}
}
We have just extended the System namespace with a method called Reverse.
Now we can reverse a string like this:
string gg = ("abcd").Reverse();
Great!!!
Thursday, September 3, 2009
How to sort array in Javascript
Just call array.sort() method without any parameter.
//Sort alphabetically and ascending:
var myarray=["Steven", "Jeff", "Michael"]
myarray.sort() //Array now becomes ["Jeff", "Michael", "Steven"]
To sort in descending order, call array.reverse() method.
myarray.reverse() //Array now becomes ["Steven", "Michael", "Jeff"]
Session State Issue in ASP.NET
Maximum no of worker processess value should be set to 1
The session value in the InProc mode session state will NOT be persisted if the application is deployed in a application pool with the Maximum no of worker processess value greater than 1.
To retrieve RowCount Quickly
If you're using SQL 2005 or 2008 querying sysindexes will still work but Microsoft advises that sysindexes may be removed in a future version of SQL Server so as a good practice you should use the DMVs instead, like so:
-- Shows all user tables and row counts for the current database -- Remove is_ms_shipped = 0 check to include system objects -- i.index_id <>SELECT o.name,ddps.row_count FROM sys.indexes AS i INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_IDINNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_IDAND i.index_id = ddps.index_id WHERE i.index_id <> AND o.is_ms_shipped = 0 ORDER BY o.NAME