lock Statement (C# Reference)

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. This statement takes the following form:

Object thisLock = new Object();
lock (thisLock)
{
// Critical code section.
}


The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The section Threading (C# and Visual Basic) discusses threading.

The lock keyword calls Enter at the start of the block and Exit at the end of the block.

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this), lock (typeof (MyType)), and lock ("myLock") violate this guideline:

lock (this) is a problem if the instance can be accessed publicly.

lock (typeof (MyType)) is a problem if MyType is publicly accessible.

lock("myLock") is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

    
using System.Threading;

    class ThreadTest
    {
        public void RunMe()
        {
            Console.WriteLine("RunMe called");
        }

        static void Main()
        {
            ThreadTest b = new ThreadTest();
            Thread t = new Thread(b.RunMe);
            t.Start();
        }
    }
    // Output: RunMe called





The following sample uses threads and lock. As long as the lock statement is present, the statement block is a critical section and balance will never become a negative number.



    using System.Threading;

    class Account
    {
        private Object thisLock = new Object();
        int balance;

        Random r = new Random();

        public Account(int initial)
        {
            balance = initial;
        }

        int Withdraw(int amount)
        {

            // This condition will never be true unless the lock statement
            // is commented out:
            if (balance < 0)
            {
                throw new Exception("Negative Balance");
            }

            // Comment out the next line to see the effect of leaving out 
            // the lock keyword:
            lock (thisLock)
            {
                if (balance >= amount)
                {
                    Console.WriteLine("Balance before Withdrawal :  " + balance);
                    Console.WriteLine("Amount to Withdraw        : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Balance after Withdrawal  :  " + balance);
                    return amount;
                }
                else
                {
                    return 0; // transaction rejected
                }
            }
        }

        public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
            {
                Withdraw(r.Next(1, 100));
            }
        }
    }

    class Test
    {
        static void Main()
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
        }
    }


Virtual Methods

Declaring a class member as *virtual* allows inheriting classes to override the base class behavior.
This is one of the pillars of OOP known as polymorphism.

Declaring a method as *sealed* breaks this inheritance chain., preventing inheriting classes from overriding base class methods.


class BaseClass
{
public virtual void Method_01()
{
Console.WriteLine("BaseClass.Method_01");
}
public virtual void Method_02()
{
Console.WriteLine("BaseClass.Method_02");
}
}
class DerivedClass : BaseClass
{
public override void Method_01()
{
Console.WriteLine("DerivedClass.Method_01");
}
public override sealed void Method_02()
{
Console.WriteLine("DerivedClass.Method_02");
}
}
class Consumer : DerivedClass
{
public override void Method_01()
{
Console.WriteLine("Consumer.Method_01");
}
public new void Method_02()
{
Console.WriteLine("Consumer.Method_02");
}
}



static void Main(string[] args)
{
BaseClass bc;
bc = new DerivedClass();
bc.Method_01();
bc.Method_02();
Console.ReadLine();
bc = new Consumer();
bc.Method_01();
bc.Method_02();
Console.ReadLine();
}

Customize default folder of Windows Explorer

If you have noticed when you click on the Windows Explorer icon default folder in task bar in Win 7, it would go to libraries folder. You can customize this behavior. Let’s say we need to set the default behavior to open My Computer.



Here are steps to change it from libraries to my computer:


1. Close all the windows explorer windows.

2. Press Shift key and right click on the explorer icon



3. Click Properties menu item and Click Properties menu item and Go to Shortcut tab.

4. Change the Target to : %SystemRoot%\explorer.exe /E,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}







5. Click Apply and Ok button.


So next time you open the windows explorer it would open my computer folder.

Windows 7 Tips

Minimize Everything except the current window

Many times we have a lot of applications open on the screen and if we have to minimize or hide other windows that are open in the background.
Then this tip can be handy.
Press the Windows Key + Home Key.
This would minimize all the background windows.

Box Selection and Multi-Line Editing with VS 2010

Technology:
Visual Studio 2010

Title:
Box Selection and Multi-Line Editing with VS 2010

Description:
Box selection is a feature that has been in Visual Studio for a while. It allows you to select a rectangular region of text within the code editor by holding down the Alt key while selecting the text region with the mouse.

With VS 2008 you could then copy or delete the selected text.

VS 2010 now enables several more capabilities with box selection including:
• Text Insertion: Typing with box selection now allows you to insert new text into every selected line

• Paste/Replace: You can now paste the contents of one box selection into another and have the content flow correctly

• Zero-Length Boxes: You can now make a vertical selection zero characters wide to create a multi-line insert point for new or copied text

These capabilities can be very useful in a variety of scenarios.

Some example scenarios: change access modifiers (private->public), adding comments to multiple lines, setting fields, grouping multiple statements together, restructuring HTML.

Running Batch Script from C#

Here is another example code to run batch script from C#


public void RunBatchScript(string batchPath, string arguments)
{
Process process = new Process();
process.StartInfo.FileName = batchPath;
process.StartInfo.Arguments = arguments;

process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;


process.OutputDataReceived += new DataReceivedEventHandler(writeStdOutStreamInfo);
process.ErrorDataReceived += new DataReceivedEventHandler(writeStdErrStreamInfo);

process.Start();

process.BeginErrorReadLine();
process.BeginOutputReadLine();

// Wait for the process to end
while (!process.HasExited)
{
Thread.Sleep(500); // sleep
}
Console.ReadKey();
}
public void writeStdOutStreamInfo(object sender,DataReceivedEventArgs e)
{
string s = e.Data;
Console.WriteLine(s);
}
public void writeStdErrStreamInfo(object sender, DataReceivedEventArgs e)
{
string s = e.Data;
Console.WriteLine(s);
}

Using there event handlers we will get the standardoutput and standarderror asynchronously in the command prompt

LinQ to XML

Using LinQ to XML its very easy to query the Xml files and traverse through the nodes and elements.
Here is one simple exaple to read the configuration XML file

bellow is my simple XML configuration file



CPADCE008
CPADCE008VM1
CPADCE044
CPADCE044VM4
20100504



Then here is the simple class to load the XML file

class ConfigElements
{
public string ServerMain { get; set; }
public string ServerVM { get; set; }
public string ClientMain { get; set; }
public string ClientVM { get; set; }
public string LatestBuild { get; set; }

public ConfigElements(XElement xElement)
{
ServerMain = xElement.Element("ServerMain").Value;
ServerVM = xElement.Element("ServerVM").Value;
ClientMain = xElement.Element("ClientMain").Value;
ClientVM = xElement.Element("ClientVM").Value;
LatestBuild = xElement.Element("LatestBuild").Value;
}

public ConfigElements(string ID)
{
XDocument doc = XDocument.Load("XMLFile2.xml");

var query = from xElem in doc.Descendants("Automation")
where xElem.Attribute("ID").Value ==ID
select new ConfigElements(xElem);

}
}


By creating the object of this class we will get all the reqired nodes

ConfigElements objConfigElements = new ConfigElements("1");
//pass here the Id of the requied values
string s= objConfigElements.ServerMain;
string t = objConfigElements.ServerVM;
string u = objConfigElements.ClientMain;
string v = objConfigElements.ClientVM;
string w = objConfigElements.LatestBuild;

Lamda Expression usage in LinQ

int[] marks = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100 };


int firstClassCount = marks.Where(n => n > 60).Count();

int[] distMarks = marks.Where(n => n > 80).ToArray();

Response.Write("Total first classes : "+firstClassCount.ToString() + "</br>");

foreach (int mark in distMarks)

{

Response.Write("Above Distinction : " + mark.ToString() + "</br>");

}

Lambda Expressions C# 3.0 & Anonymous Methods

Lambda expressions provide a concise syntax for writing anonymous
methods. The C# 3.0 specification describes lambda expressions as a
super set of anonymous methods.


In C# 2.0, you can write a delegate using an anonymous method, as
shown in this example:

public delegate int MyDelegate(int n);

class MyClass
{
    static void Main()
    {
        // Anonymous method that returns the argument multiplied by 5:
        MyDelegate delegObject1 = new MyDelegate(
        delegate(int n) { return n * 5; }
        );
        // Display the result:
        Console.WriteLine("The value is: {0}", delegObject1(5));
    }
}

This program outputs the value 25.

Using a lambda expression you can use a simpler syntax to achieve the
same goal:

MyDelegate delegObject2 = (int n) => n * 5;

using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;

namespace Lambda
{
    public delegate int MyDelegate(int n);
    class MyClass
    {
        static void Main()
        {
            MyDelegate delegObject1 = new MyDelegate(
            delegate(int n) { return n * 5; }
            );

            Console.WriteLine("The value using an anonymous method is: {0}",
            delegObject1(5));

            MyDelegate delegObject2 = (int n) => n * 5;
            
            Console.WriteLine("The value using a lambda expression is: {0}",
            delegObject2(5));

            Console.ReadLine();
        }
    }
}

Output:
The value using an anonymous method is: 25
The value using a lambda expression is: 25


A lambda expression can use two arguments, especially when you are
using the Standard Query Operators. Let us start by declaring the following
delegate that uses two arguments:

public delegate int MyDelegate(int m, int n);

You can instantiate the delegate by using a lambda expression like this:

MyDelegate myDelegate = (x, y) => x * y;

You can then invoke the delegate and display the result as follows:

Console.WriteLine("The product is: {0}", myDelegate(5, 4));
// output: 20

Different types of Object Initializers

Consider the bellow Point class

 class Point
    {
        int x, y;
        public int X
        {
            get { return x; }
            set { x = value; }
        }
        public int Y
        {
            get { return y; }
            set { y = value; }
        }
    }


Then consider the main Program

class Program
    {
        static void Main(string[] args)
        {
            Point c1=new Point();
            c1.X=10;
            c1.Y=100;
            Console.WriteLine(c1.X);
            Console.WriteLine(c1.Y);

            Point c2=new Point {X=20,Y=200};    // See the new type of Initializing

            Console.WriteLine(c2.X);
            Console.WriteLine(c2.Y);

            var p = new Point { X = 30, Y = 300 };    // See the new type of Initializing using "var" keyword

            Console.WriteLine(p.X);
            Console.WriteLine(p.Y);

            Console.ReadLine();
        }
    }

With complex fields, such as a square or a rectangle whose corners are
located at the points p1 and p2, you can create the Rectangle class as
follows:

    public class Rectangle
    {
        Point p1; Point p2;
        public Point ULcorner { get { return p1; } set { p1 = value; } }
        public Point LRcorner { get { return p2; } set { p2 = value; } }      
    }
You can create and initialize the Rectangle object like this:

         var rectangle = new Rectangle
        {
            ULcorner = new Point { X = 0, Y = 0 },
            LRcorner = new Point { X = 10, Y = 20 }
        };

Note that the semicolon at the end of the object initializer block.

Find current URL of an IE instance from a C# application

We all know that to get the current URL of the browser for an Web Application can be find by

HttpContext.Current.Request.Url.AbsolutePath

But to find out the current URL of IE from a C# application following scripts can be useful

            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();

            foreach (SHDocVw.WebBrowser ies in shellWindows)
            {
                Console.WriteLine(ies.LocationURL);
            }


Windows PowerShell 2.0 Best Practices (Best Practices (Microsoft))

Open an Internet Explorer from C# Application

First of all add reference the SHDocVw.dll to the apllication.

             object o = null;
            SHDocVw.InternetExplorer ie = new  SHDocVw.InternetExplorerClass();
            IWebBrowserApp wb = (IWebBrowserApp)ie;
            wb.Visible = true;

            //Do anything else with the window here that you wish
            wb.Navigate("http://google.com", ref o, ref o, ref o, ref o);

Internet Explorer 8, Illustrated Essentials

Serialisation and Deserialisation Class

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.IO;
using System.Xml.Serialization;

/// <summary>
/// Summary description for Serialization
/// </summary>
public class Serialization
{
    public static string StringSerialize(object instance)
    {
        MemoryStream m = new MemoryStream();
        XmlSerializer x = new XmlSerializer(instance.GetType());
        x.Serialize(m, instance);
        byte[] b = m.ToArray();
        string s = System.Text.ASCIIEncoding.ASCII.GetString(b);
        return s;
    }
    public static byte[] ByteSerialize(object instance)
    {
        MemoryStream m = new MemoryStream();
        XmlSerializer x = new XmlSerializer(instance.GetType());
        x.Serialize(m, instance);
        byte[] b = m.ToArray();
        return b;
    }
    public static object DeSerialize(string Text, Type type)
    {
        byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(Text);
        MemoryStream m = new MemoryStream(b);
        XmlSerializer x = new XmlSerializer(type);
        object o = x.Deserialize(m);
        return o;
    }
    public static object DeSerialize(byte[] b, Type type)
    {
        MemoryStream m = new MemoryStream(b);
        XmlSerializer x = new XmlSerializer(type);
        object o = x.Deserialize(m);
        return o;
    }
}

Ajax, Update Panel, Script Manager, Update Controls Outside Update Panel With Out Postback

Here my first post is regarding Ajax.
So here I am going to give you a simple example how to update the controls outside the update panel without postback

Code behind file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class scriptMgr : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Label1 upadte" + DateTime.Now.ToString();
Label2.Text = "Label2 updated" + DateTime.Now.ToString();
if (ScriptManager1.IsInAsyncPostBack)
{

ScriptManager1.RegisterDataItem(Label3, DateTime.Now.ToString());
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "Label1 " + DateTime.Now.ToString();
Label2.Text = "Label2 " + DateTime.Now.ToString();
if (ScriptManager1.IsInAsyncPostBack)
{
ScriptManager1.RegisterDataItem(Label3, "Label3 "+DateTime.Now.ToString());
}
}
}



Aspx page

 <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <script type="text/javascript" language="javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(PageLoadingHandler);
        function PageLoadingHandler(sender, args) {
            var dataItems = args.get_dataItems();
            if ($get('Label3') != null)
                $get('Label3').innerHTML = dataItems['Label3'];
         
        }
    </script>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
            <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
            <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br />
        </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>
       
        <asp:Label ID="Label3" runat="server" Text="krwelkr"></asp:Label>
        <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
    </div>
  

You can find Ajax Books

Professional ASP.NET 3.5 AJAX (Wrox Programmer to Programmer)
Microsoft ASP.NET and AJAX: Architecting Web Applications (PRO-Developer)

Very Simple Linq Usage Sample

Here I will give one very simple linq sample code.

A query that will return each of the items in the people List collection by aliasing the people collection with a variable p and then selecting p (p is of type string remember as the people List is a collection of immutable string objects).

You may notice that query is of type IEnumerable - this is because we know that query will hold an enumeration of type string. When we foreach through the query the GetEnumerator of query is invoked.


protected void Page_Load(object sender, EventArgs e)
{
List people = new List(){
"Sen", "Paulose", "Thomas", "Raju",
"Anil", "Shyam", "Saidwin"
};

IEnumerable query = from p in people select p;
foreach (string person in query)
{
Response.Write(person);
}
}

Creating HTML Table Dynamically of Desired Rows and Columns

string table = "tableTag"; //html table tag
string tr = "trTag"; //html tr tag
string td = string.Empty;

int count = 0;
for (int i = 1; i <=10; i++)
{
string Name = "Sen";
td += "tdTag" + Name + i + "tdCloseTag";
count++;
if (count == 3)
{
td = td + "trCloseTag" + "trTag";
count = 0;
}
}
tr += td + "trCloseTag";
table += tr + "tableCloseTag";

Response.Write(table);

ASP.NET C# Programmer Kerala: Advanced Filtering with Relationships

ASP.NET C# Programmer Kerala: Advanced Filtering with Relationships

DataView Advanced Filtering with Relationships in C# And ASP.NET

The DataView allows for some surprisingly complex filter expressions. One of its little-known features is the ability to filter rows based on relationships. For example, you could display categories that contain more than 20 products, or you could display customers who have made a certain
number of total purchases. In both of these examples, you need to filter one table based on the
information in a related table.

To create this sort of filter string, you need to combine two ingredients:

• A table relationship that links two tables.
• An aggregate function such as AVG(), MAX(), MIN(), or COUNT(). This function acts on the
data in the related records.

For example, suppose you’ve filled a DataSet with the Categories and Products tables and
defined this relationship:

// Define the relationship between Categories and Products.
DataRelation relat = new DataRelation("CatProds",
ds.Tables["Categories"].Columns["CategoryID"],
ds.Tables["Products"].Columns["CategoryID"]);
// Add the relationship to the DataSet.
ds.Relations.Add(relat);

You can now filter the display of the Categories table using a filter expression based on the
Products table. For example, imagine you want to show only category records that have at least one
product worth more than $50. To accomplish this, you use the COUNT() function, along with the
name of the table relationships (CatProds).
Here’s the filter string you need:

MAX(Child(CatProds).UnitPrice) > 50

And here’s the code that applies this filter string to the DataView:

DataView view1 = new DataView(ds.Tables["Categories"]);
view1.RowFilter = "MAX(Child(CatProds).UnitPrice) > 50";
GridView1.DataSource = view1;

The end result is that the GridView shows only the categories that have a product worth more
than $50.

Filtering with a DataView

You can a DataView to apply custom filtering so that only certain rows are included in the
display. To accomplish this feat, you use the RowFilter property. The RowFilter property acts like a WHERE clause in a SQL query. Using it, you can limit results using logical operators (such as <, >, and =) and a wide range of criteria. Bellow the most common filter operators.

Filter Operators

Operator Description
<, >, <=, and >= Performs comparison of more than one value. These comparisons can be
numeric (with number data types) or alphabetic dictionary comparisons
(with string data types).
<> and = Performs equality testing.
NOT Reverses an expression. Can be used in conjunction with any other clause.
BETWEEN Specifies an inclusive range. For example, “Units BETWEEN 5 AND 15”
selects rows that have a value in the Units column from 5 to 15.
IS NULL Tests the column for a null value.
IN(a,b,c) A short form for using an OR clause with the same field. Tests for equality
between a column and the specified values (a, b, and c).
LIKE Performs pattern matching with string data types.
+ Adds two numeric values or concatenates a string.
- Subtracts one numeric value from another.
* Multiplies two numeric values.
/ Divides one numeric value by another.
% Finds the modulus (the remainder after one number is divided by another).
AND Combines more than one clause. Records must match all criteria to be
displayed.
OR Combines more than one clause. Records must match at least one of the
filter expressions to be displayed.
The following example page includes three GridView controls. Each one is bound to the same
DataTable but with different filter settings.

string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "SELECT ProductID, ProductName, UnitsInStock, UnitsOnOrder, " +
Discontinued FROM Products";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds, "Products");
// Filter for the Chocolade product.
DataView view1 = new DataView(ds.Tables["Products"]);
view1.RowFilter = "ProductName = 'Chocolade'";
GridView1.DataSource = view1;

// Filter for products that aren't on order or in stock.
DataView view2 = new DataView(ds.Tables["Products"]);
view2.RowFilter = "UnitsInStock = 0 AND UnitsOnOrder = 0";
GridView2.DataSource = view2;
// Filter for products starting with the letter P.
DataView view3 = new DataView(ds.Tables[“Products”]);
view3.RowFilter = "ProductName LIKE 'P%'";
GridView3.DataSource = view3;
this.DataBind();