Sunday, February 28, 2010

SQL Server: GETDATE() & GETUTCDATE() & different time zones

Most of us will use GetDate() function for providing default value in SQL server columns. This function Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

This works perfectly if you don’t have to show reports and such stuffs for users from different time zones. In case you want to store time independent of time zones in some universal format; what will do? Well there is GetUtcDate() function for you. This function will return then UTC date based on the setting of the server on which SQL server is installed.

I executed the following function & I got the two different date output values.


SELECT  GETDATE() AS Expr1, GETUTCDATE () AS Expr2

2/28/2010 1:27:17 PM
2/28/2010 7:57:17 AM



SQL Server 2008
SQL Server 2008 has two new DataTypes: date & time

You can use them to retrieve the date & time part from the date time functions like the following

Current Date Value
SELECT CONVERT (date, SYSDATETIME())
    ,CONVERT (date, SYSDATETIMEOFFSET())
    ,CONVERT (date, SYSUTCDATETIME())
    ,CONVERT (date, CURRENT_TIMESTAMP)
    ,CONVERT (date, GETDATE())
    ,CONVERT (date, GETUTCDATE());

Current Time Value
SELECT CONVERT (time, SYSDATETIME())
    ,CONVERT (time, SYSDATETIMEOFFSET())
    ,CONVERT (time, SYSUTCDATETIME())
    ,CONVERT (time, CURRENT_TIMESTAMP)
    ,CONVERT (time, GETDATE())
    ,CONVERT (time, GETUTCDATE());

Saturday, February 27, 2010

ASP.net - Http handlers - Generic Hander

An HTTP Handler is a .NET class that executes whenever you make a request for a file at a certain path. Each type of resource that you can request from an ASP.NET application has a corresponding handler.

When you request an ASP.NET page, the Page class executes. The Page class is actually an HTTP Handler because it implements the IHttpHandler interface. Other examples of HTTP Handlers are the TraceHandler class, which displays applicationlevel trace information when you request the Trace.axd page and the ForbiddenHandler class, which displays an Access Forbidden message when you attempt to request source code files from the browser.

Similarly you can create your own HTTP handlers for acting on any requests received at webserver.

Generic Hander

Add a generic handler by right clicking on the project explorer > Add> new item> select Generic Handler.

A new file with ASHX extension is created.


Here is a sample code which I got from Steven Walthers book. This handler creates image dynamically based on the QueryString value received

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageTextHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            // Get parameters from querystring
            string text = context.Request.QueryString["text"];
            string font = context.Request.QueryString["font"];
            string size = context.Request.QueryString["size"];

            Font fntText = new Font(font, float.Parse(size));

            Bitmap bmp = new Bitmap(10, 10);
            Graphics g = Graphics.FromImage(bmp);

            SizeF bmpsize = g.MeasureString(text, fntText);
            int width =(int) Math.Ceiling(bmpsize.Width);
            int height = (int)Math.Ceiling(bmpSize.Height);
            bmp = new Bitmap(bmp, width, height);
            g.Dispose();

            // Draw the text
            g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            g.DrawString(text, fntText, Brushes.Black, new PointF(0, 0));
            g.Dispose();

            // Save bitmap to output stream
            bmp.Save(context.Response.OutputStream, ImageFormat.Gif);

        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }

ProcessRequest() method is responsible for outputting any content that the handler renders to the browser.


The handler also includes an IsReusable property. The IsReusable property indicates whether the same handler can be reused over multiple requests. You can improve your application’s performance by returning the value True. Because the handler isn’t maintaining any state information, there is nothing wrong with releasing it back into the pool so that it can be used with a future request.


How can I use this generic handler?

You can put the following code in any ASPX file

<img src="ImageTextHandler.ashx?text=Hello World&font=WebDings&size=20" />
<br />
<img src="ImageTextHandler.ashx?text=Hello World&font=Comic Sans MS&size=20" />
<br />
<img src="ImageTextHandler.ashx?text=Hello World&font=Courier New&size=20" />


You will get a browser output like the following
The basic idea here is not to show how to create a image file on the fly but the handling of request by ASHX file


Saturday, February 20, 2010

C# Thread Synchronization


Multithreading enables you to have several threads of execution running at the same time. But in this case there is a risk of one thread trying to access resource when another tread is working on the resource. In short they all compete for the same set of resources, so there must be a mechanism to ensure synchronization and communication among threads.

You can use the following ways to synchronize your threads:
  1. The Interlocked class

    // Summary:
    //     Provides atomic operations for variables that are shared by multiple threads.
    public static class Interlocked
    {
public static int Decrement(ref int location)
public static long Decrement(ref long location);
public static int Increment(ref int location);
        //
        // Summary:
        //     Increments a specified variable and stores the result, as an atomic operation.
        //
        // Parameters:
        //   location:
        //     The variable whose value is to be incremented.
        //
        // Returns:
        //     The incremented value.
        //
        // Exceptions:
        //   System.NullReferenceException:
        //     The address of location is a null pointer.
        public static long Increment(ref long location);
}


use can use the Interlocked class like the foloowing

        static int _inum = 0;
        static void Main(string[] args)
        {
           
        }

        static void Add()
        {
            Interlocked.Increment(ref _inum);
        }
        static void Sub()
        {
            Interlocked.Decrement(ref _inum);
        }

Increment & Decrement are the main two functions of the class. Check out the documentation for other methods

  1. The C# lock keyword

Use this method to keep multiple statements Thread safe; to lock a block of code, give the lock statement an object as argument.

class Program
    {
        static int _inum = 0;
        static object _obj = new object();
        static void Main(string[] args)
        {
            Thread tAdd = new Thread(Add)
            {
                Name = "Add thread"
            };
            tAdd.Start(1);
            Thread tSub = new Thread(new ParameterizedThreadStart(Program.Sub));
            tSub.Start(1);

            //Add(14);
            //Sub(10);
            Console.ReadLine();
           
        }

        static void Add(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                lock (_obj)
                {
                    _inum += val;
                    Console.WriteLine("new value after add= " + _inum);
                    Console.WriteLine("current thread: {0}", Thread.CurrentThread.Name);
                    Console.WriteLine();
                }
            }
        }
        static void Sub(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                lock (_obj)
                {
                    _inum -= val;
                    Console.WriteLine("new value after sub= " + _inum);
                }
            }
        }
    }


  1. The Monitor class

The limitation of the lock statement is that you do not have the capability to release the lock halfway through the critical section. This is important because there are situations in which one thread needs to release the lock so that other threads have a chance to proceed before the first thread can resume its execution.
    //     Provides a mechanism that synchronizes access to objects.
    [ComVisible(true)]
    public static class Monitor
    {
public static void Enter(object obj);
        //
        // Summary:
        //     Releases an exclusive lock on the specified object.
        //
        // Parameters:
        //   obj:
        //     The object on which to release the lock.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The current thread does not own the lock for the specified object.
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        public static void Exit(object obj);
        //
        // Summary:
        //     Notifies a thread in the waiting queue of a change in the locked object's
        //     state.
        //
        // Parameters:
        //   obj:
        //     The object a thread is waiting for.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The calling thread does not own the lock for the specified object.
        public static void Pulse(object obj);
        //
        // Summary:
        //     Notifies all waiting threads of a change in the object's state.
        //
        // Parameters:
        //   obj:
        //     The object that sends the pulse.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The calling thread does not own the lock for the specified object.
        public static void PulseAll(object obj);
}

In the previous example the value of inum can be less than 0 but with lock statement I couldn’t prevent/stop the thread from doing this so but with Monitor class I can set such conditions & check for other similar business conditions.

The Add & Sub methods can be re-written like the following using the Monitor class

static void Add(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                Monitor.Enter(_obj);
                _inum += val;

                if (_inum > 1)
                    Monitor.Pulse(_obj);

                Console.WriteLine("new value after add= " + _inum);
                Console.WriteLine("current thread: {0}", Thread.CurrentThread.Name);
                Console.WriteLine();
                Monitor.Exit(_obj);
            }

        }
        static void Sub(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                Monitor.Enter(_obj);
             
                if (_inum < 1)
                    Monitor.Wait(_obj);

                _inum -= val;
                Console.WriteLine("new value after sub= " + _inum);
                Monitor.Exit(_obj);
            }
        }

The Enter() method of the Monitor class acquires a lock on the specified object, and the Exit()
method releases the lock. The code enclosed by the Enter() and Exit() methods is the critical section.

The Wait() method of the Monitor class releases the lock on the object and enter the object ’ s waiting queue. The next thread that is waiting for the object acquires the lock. If the value is 0, the Sub thread would give up control and let the Add thread have the lock. If this special condition is met, Sub release lock to Add method. Now after add sufficient values to internal variable the Add method should release the lock back. This is done using  the Pulse() method of the Monitor which sends a signal to the waiting thread that the lock is now released and is now going to pass back to it.




C# Thread Synchronization


Multithreading enables you to have several threads of execution running at the same time. But in this case there is a risk of one thread trying to access resource when another tread is working on the resource. In short they all compete for the same set of resources, so there must be a mechanism to ensure synchronization and communication among threads.

You can use the following ways to synchronize your threads:
  1. The Interlocked class

    // Summary:
    //     Provides atomic operations for variables that are shared by multiple threads.
    public static class Interlocked
    {
public static int Decrement(ref int location)
public static long Decrement(ref long location);
public static int Increment(ref int location);
        //
        // Summary:
        //     Increments a specified variable and stores the result, as an atomic operation.
        //
        // Parameters:
        //   location:
        //     The variable whose value is to be incremented.
        //
        // Returns:
        //     The incremented value.
        //
        // Exceptions:
        //   System.NullReferenceException:
        //     The address of location is a null pointer.
        public static long Increment(ref long location);
}


use can use the Interlocked class like the foloowing

        static int _inum = 0;
        static void Main(string[] args)
        {
           
        }

        static void Add()
        {
            Interlocked.Increment(ref _inum);
        }
        static void Sub()
        {
            Interlocked.Decrement(ref _inum);
        }

Increment & Decrement are the main two functions of the class. Check out the documentation for other methods

  1. The C# lock keyword

Use this method to keep multiple statements Thread safe; to lock a block of code, give the lock statement an object as argument.

class Program
    {
        static int _inum = 0;
        static object _obj = new object();
        static void Main(string[] args)
        {
            Thread tAdd = new Thread(Add)
            {
                Name = "Add thread"
            };
            tAdd.Start(1);
            Thread tSub = new Thread(new ParameterizedThreadStart(Program.Sub));
            tSub.Start(1);

            //Add(14);
            //Sub(10);
            Console.ReadLine();
           
        }

        static void Add(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                lock (_obj)
                {
                    _inum += val;
                    Console.WriteLine("new value after add= " + _inum);
                    Console.WriteLine("current thread: {0}", Thread.CurrentThread.Name);
                    Console.WriteLine();
                }
            }
        }
        static void Sub(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                lock (_obj)
                {
                    _inum -= val;
                    Console.WriteLine("new value after sub= " + _inum);
                }
            }
        }
    }




  1. The Monitor class

The limitation of the lock statement is that you do not have the capability to release the lock halfway through the critical section. This is important because there are situations in which one thread needs to release the lock so that other threads have a chance to proceed before the first thread can resume its execution.
    //     Provides a mechanism that synchronizes access to objects.
    [ComVisible(true)]
    public static class Monitor
    {
public static void Enter(object obj);
        //
        // Summary:
        //     Releases an exclusive lock on the specified object.
        //
        // Parameters:
        //   obj:
        //     The object on which to release the lock.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The current thread does not own the lock for the specified object.
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        public static void Exit(object obj);
        //
        // Summary:
        //     Notifies a thread in the waiting queue of a change in the locked object's
        //     state.
        //
        // Parameters:
        //   obj:
        //     The object a thread is waiting for.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The calling thread does not own the lock for the specified object.
        public static void Pulse(object obj);
        //
        // Summary:
        //     Notifies all waiting threads of a change in the object's state.
        //
        // Parameters:
        //   obj:
        //     The object that sends the pulse.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The calling thread does not own the lock for the specified object.
        public static void PulseAll(object obj);
}

In the previous example the value of inum can be less than 0 but with lock statement I couldn’t prevent/stop the thread from doing this so but with Monitor class I can set such conditions & check for other similar business conditions.

The Add & Sub methods can be re-written like the following using the Monitor class

        static void Add(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                Monitor.Enter(_obj);
                _inum += val;
                Console.WriteLine("new value after add= " + _inum);
                Console.WriteLine("current thread: {0}", Thread.CurrentThread.Name);
                Console.WriteLine();
                Monitor.Exit(_obj);
            }

        }
        static void Sub(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                Monitor.Enter(_obj);
                _inum -= val;
                if (_inum < 1)
                    Monitor.Pulse(_obj);
                Console.WriteLine("new value after sub= " + _inum);
                Monitor.Exit(_obj);
            }
        }

The Enter() method of the Monitor class acquires a lock on the specified object, and the Exit()
method releases the lock. The code enclosed by the Enter() and Exit() methods is the critical section. The Pulse() method of the Monitor sends a signal to the waiting thread that the lock is now released and is now going to pass back to it.