<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Coding N Design</title>
	<atom:link href="http://codingndesign.com/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://codingndesign.com/blog</link>
	<description>Design and Coding Beautiful Software</description>
	<lastBuildDate>Sat, 21 Aug 2010 11:38:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>C# Monitor,Busy Wait,True Wait &amp; SpinLock</title>
		<link>http://codingndesign.com/blog/?p=171</link>
		<comments>http://codingndesign.com/blog/?p=171#comments</comments>
		<pubDate>Sat, 21 Aug 2010 11:32:57 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Programming & Languages]]></category>
		<category><![CDATA[Monitor]]></category>
		<category><![CDATA[SpinLock]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=171</guid>
		<description><![CDATA[In my last two posts I had discussed about thread synchronization,critical sections and System.Threading.Monitor class.What we have seen is, a critical section in the code where thread synchronization is required is protected by a lock.When a thread encounters a critical section it tries to acquire the lock,if successful it executes the code or else waits [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D171"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D171&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my last two <a href="http://codingndesign.com/blog/?tag=monitor" target="_blank">posts</a> I had discussed about thread synchronization,critical sections and <font color="#0000ff">System.Threading.Monitor</font> class.What we have seen is, a critical section in the code where thread synchronization is required is protected by a lock.When a thread encounters a critical section it tries to acquire the lock,if successful it executes the code or else waits to acquire the lock.Now when we say wait, what exactly happens?.There are two possible ways this can be done.</p>
<p><span id="more-171"></span> </p>
<p>Managed threads, spawned via .NET are actually threads in Windows OS.So they can use the Windows Kernel Synchronization objects(Mutex,Semaphores,..etc.).These synchronization objects can have two states: <em>signaled and non-signaled</em>.When a thread gets reference to a synchronization object which is in non-signaled state there is an immediate context switch i.e. it is taken down from the processor and put into a wait/sleep mode.Later when the synchronization object is signaled the thread is put back to the runnable queue and is ready for execution.In this kind of waiting there is no wastage of CPU cycles in wait state but there is a context switch.So if the waiting period is long enough this can be useful but for shorter duration the overhead of context switch may prove to be costly.We are referring to this as <strong>true wait</strong>.</p>
<p>There is another way.The thread waits and checks for the lock to be released in some kind of a loop.This is known as <strong>spin or busy wait</strong>.Here if the waiting period is short this can be useful but for longer duration this will lead to wastage of CPU cycles.</p>
<p>The C# Monitor class implements a mix of the two.First it spins for few cycles and if the lock is still not acquired by that time it then get&#8217;s into a true wait using kernel synchronization objects.</p>
<p>From .NET 3.5 the <font color="#0000ff">System.Threading.SpinLock</font> structure is introduced to implement busy or spin wait based locks.The methods are quite similar to that of Monitor.The two most important methods are:</p>
<ul>
<li><font color="#004000"><em>public void Enter(ref bool lockTaken)</em></font> &#8211; To acquire the lock
<li><em><font color="#004000">public void Exit()</font></em> &#8211; To release the lock</li>
</ul>
<p>The following code shows the use of this methods to acquire and release locks:</p>
<pre class="brush: csharp;">
public class Foo
{
     SpinLock spLock = new SpinLock();
     public void M1()
     {
         bool lockTaken = false;
         try
         {
             spLock.Enter(ref lockTaken);
             Thread.Sleep(1000);
             Console.WriteLine(&quot;M1::&quot;);
         }
         finally
         {
             if(lockTaken)spLock.Exit();
         }
     }
}
</pre>
<p>However one difference with Monitor is, this lock is non reentrant in nature.In the following code the pne thread is trying to acquire the same SpinLock twice.</p>
<pre class="brush: csharp;">
public class Foo
{
     SpinLock spLock = new SpinLock();
     public void M1()
     {
         bool lockTaken = false;
         try
         {
             spLock.Enter(ref lockTaken);
             Thread.Sleep(1000);
             M2();
             Console.WriteLine(&quot;M1::&quot;);
         }
         finally
         {
             if(lockTaken)spLock.Exit();
         }
     }
     public void M2()
     {
         bool lockTaken = false;
         try
         {
             spLock.Enter(ref lockTaken);
             Console.WriteLine(&quot;M2::&quot;);
         }
         finally
         {
             if (lockTaken) spLock.Exit();
         }
     }
}
</pre>
<p>The execution of the method M1 will throw a <font color="#0000ff">LockRecursionException</font> exception:</p>
<p><font color="#ff0000">{&#8220;The calling thread already holds the lock.&#8221;}</font></p>
<p>However we can avoid this by checking whether lock is held by same thread or not using the <font color="#0000ff">SpinLock.IsHeldByCurrentThread</font> property</p>
<pre class="brush: csharp;">
public void M2()
{
    bool lockTaken = false;
    try
    {
        if(!spLock.IsHeldByCurrentThread)spLock.Enter(ref lockTaken);
        Console.WriteLine(&quot;M2::&quot;);
    }
    finally
    {
        if (lockTaken) spLock.Exit();
    }
}
</pre>
<p>In the next series we will explore the other thread synchronization mechanisms available in .NET Framework. </p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=171</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ServiceLocator in ASP.NET MVC 3 &#8211; Part 2</title>
		<link>http://codingndesign.com/blog/?p=168</link>
		<comments>http://codingndesign.com/blog/?p=168#comments</comments>
		<pubDate>Sat, 21 Aug 2010 06:42:04 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Web Apps]]></category>
		<category><![CDATA[ASP.NET MVC 3.0]]></category>
		<category><![CDATA[StructureMap]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=168</guid>
		<description><![CDATA[In my earlier post I had discussed about the Common Service Locator framework (IServiceLocator interface)and how we can implement an adapter for the StructureMap container.In this post we will take look into how the new ASP.NET MVC provides support to plug in this ServiceLocator. The new framework supports an interface System.Web.Mvc.IMvcServiceLocator which is defined as: [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D168"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D168&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my earlier <a href="http://codingndesign.com/blog/?p=164" target="_blank">post</a> I had discussed about the Common Service Locator framework (IServiceLocator interface)and how we can implement an adapter for the <a href="http://structuremap.github.com/structuremap/index.html" target="_blank">StructureMap</a> container.In this post we will take look into how the new ASP.NET MVC provides support to plug in this ServiceLocator.</p>
<p><span id="more-168"></span></p>
<p>The new framework supports an interface <font color="#0000ff">System.Web.Mvc.IMvcServiceLocator</font> which is defined as:</p>
<pre class="brush: csharp;">
public interface IMvcServiceLocator : IServiceLocator {
      void Release(object instance);
  }
</pre>
<p>We also have a default implementation of this interface <font color="#0000ff">System.Web.Mvc.MvcServiceLocator.</font> This class exposes a method <em><font color="#004000">public static void SetCurrent(IServiceLocator locator)</font></em> to plug in custom service locator implementation.</p>
<p>If there is no custom service locator set, then it uses a default implementation provided by the class <font color="#0000ff">DefaultMvcServiceLocator</font>.This class uses <font color="#004000"><em>Activator.CreateInstance</em></font> to instantiate the objects.</p>
<p>Right now there is support for service locator to manage instances of Controller,Views and Filters.Let&#8217;s take a look into how we can manage controller instances using the service locator.</p>
<p>The instantiation of controllers are managed through the factory classes implementing the <font color="#0000ff">IControllerFactory</font> interface.We can implement our own controller factory or can use the <font color="#0000ff">DefaultControllerFactory</font> class provided by the framework itself.</p>
<p>DefaultControllerFactory gets the reference to a IServiceLocator instance in the following way:</p>
<pre class="brush: csharp;">
protected internal DefaultControllerFactory(IServiceLocator locator) {
    if (locator == null)
        _serviceLocatorThunk = () =&gt; MvcServiceLocator.Current;
    else
        _serviceLocatorThunk = () =&gt; locator;
}
</pre>
<p>While creating the instance it first checks with the service locator.If the container is not able to create the instance it then uses <font color="#004000"><em>Activator.CreateInstance</em></font> as shown below:  </p>
<pre class="brush: csharp;">
// Try the container first...
try {
    return (IController)_serviceLocatorThunk().GetInstance(controllerType);
}
catch (ActivationException) {
} 

// ...failing that, fall back to MVC 2 behavior
try {
    return (IController)Activator.CreateInstance(controllerType);
}
catch (Exception ex) {
    throw new InvalidOperationException(
        String.Format(
            CultureInfo.CurrentCulture,
            MvcResources.DefaultControllerFactory_ErrorCreatingController,
            controllerType),
        ex);
}
</pre>
<p>To use our StructureMap based service locator we have to configure the StructureMap container,register the controller type and set the custom service locator in <em><font color="#004000">Application_Start</font></em> event of <font color="#0000ff">global.asax.cs</font> as shown below: </p>
<pre class="brush: csharp;">
Container container = new Container(
    x =&gt;
    {
        x.ForRequestedType&lt;IController&gt;().
                AddInstances
                (
                    y =&gt;
                        {
                            y.
                               OfConcreteType
                               (
                                typeof(DepartmentController)
                               ).
                                    WithName(&quot;Department&quot;);
                        }
                );
    }
    ); 

StructureMapServiceLocator serviceLocator =
    new StructureMapServiceLocator(container); 

MvcServiceLocator.SetCurrent(serviceLocator);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=168</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ServiceLocator in ASP.NET MVC 3 Preview 3 &#8211; Part 1</title>
		<link>http://codingndesign.com/blog/?p=164</link>
		<comments>http://codingndesign.com/blog/?p=164#comments</comments>
		<pubDate>Sun, 08 Aug 2010 11:31:26 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Web Apps]]></category>
		<category><![CDATA[ASP.NET MVC 3.0]]></category>
		<category><![CDATA[Service Locator]]></category>
		<category><![CDATA[StructureMap]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=164</guid>
		<description><![CDATA[For past couple of days I was checking out features of the new ASP.NET MVC Preview 3.There are couple of interesting new additions like integration with the new Razor viewengine,improvements in Model Validation,AJAX support and Dependency Injection.In this post we will discuss on, how ASP.NET MVC 3 has streamlined the ability to register/retrieve objects/services in [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D164"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D164&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>For past couple of days I was checking out features of the new <span style="color: #804040;">ASP.NET MVC Preview 3</span>.There are couple of interesting new additions like integration with the new <span style="color: #804040;">Razor</span> viewengine,improvements in Model Validation,AJAX support and Dependency Injection.In this post we will discuss on, how ASP.NET MVC 3 has streamlined the ability to register/retrieve objects/services in a loosely coupled manner by incorporating support for the <span style="color: #804040;">Common Service Locator</span> framework.<br />
<span id="more-164"></span><br />
What is Common Service Locator?Today we have many <a href="http://martinfowler.com/articles/injection.html#InversionOfControl" target="_blank">Inversion of Control/Dependency Injection</a> Containers like NInject,StructureMap,Unity,.. etc in the .NET world.Most of these vary quite widely in terms of configuration and initialization/registration of the instances.But they provide more or less similar interface while <em>resolving the dependencies and returning object instances</em>.Common Service Locator framework extracts these commonalities out and provides an <em>abstraction on top of these IoC/DI containers</em>.This is now part of the <a href="http://msdn.microsoft.com/en-us/library/ff664535(PandP.50).aspx" target="_blank">Enterprise Library 5.0</a> and used in the Enterprise Library code to create/retrieve objects.Common Service Locator provides an interface <span style="color: #0000ff;">IServiceLocator</span></p>
<pre class="brush: csharp;">
public interface IServiceLocator : IServiceProvider
{
    IEnumerable&lt;TService&gt; GetAllInstances&lt;TService&gt;();
    IEnumerable&lt;object&gt; GetAllInstances(Type serviceType);
    TService GetInstance&lt;TService&gt;();
    TService GetInstance&lt;TService&gt;(string key);
    object GetInstance(Type serviceType);
    object GetInstance(Type serviceType, string key);
}
</pre>
<p>It is quite evident from the method signatures that these are only related to retrieval of right object instances with proper resolution of the dependencies based upon different parameters.</p>
<p>Another important class related to the Common Service Locator is the <span style="color: #0000ff;">ActivationException</span> which needs to be thrown whenever there is exception in instantiating the objects /resolving the dependencies.</p>
<p>I was planning to use StructureMap as the DI Container and a <a href="http://commonservicelocator.codeplex.com/wikipage?title=StructureMap%20Adapter&amp;referringTitle=Home" target="_blank">StructureMap Adapter for Service Locator</a> was available in Codeplex but that seemed far from complete.</p>
<p>So I went ahead to write few lines of code and develop a service locator which will use <a href="http://structuremap.github.com/structuremap/index.html" target="_blank">StructureMap</a> as the DI container as shown below:</p>
<pre class="brush: csharp;">
  public class StructureMapServiceLocator : IServiceLocator
  { 

      private IContainer container;
      public StructureMapServiceLocator(IContainer container)
      {
          this.container = container;
      }
    //........
  }
</pre>
<p>This class accepts an instance of the <span style="color: #0000ff;">StructureMap.Container</span> in the constructor and uses it to resolve dependencies and instantiate objects.In the implementation of the IServiceLocator methods we have to just map them suitably to <span style="color: #0000ff;">StructureMap.Container.GetAllInstances</span> and <span style="color: #0000ff;">StructureMap.Container.GetInstance</span> methods (and their overloads).The code which depends on IServiceLocator will perform exception handling based on ActivationException class whereas StructureMap raises <span style="color: #0000ff;">StructureMap.StructureMapException</span> in most of the cases.So we need to catch StructureMapException in this class and throw a ActivationException.The complete code is given below:</p>
<pre class="brush: csharp;">
namespace MVC.Sample.ServiceLocator
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using StructureMap;

    /// &lt;summary&gt;
    /// Structure Map Based Service Locator
    /// &lt;/summary&gt;
    public class StructureMapServiceLocator : IServiceLocator
    {
        /// &lt;summary&gt;
        /// Strycture Map Container Reference
        /// &lt;/summary&gt;
        private IContainer container;
        /// &lt;summary&gt;
        /// Constructor
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;container&quot;&gt;Instance of the Structure Map Container&lt;/param&gt;
        public StructureMapServiceLocator(IContainer container)
        {
            this.container = container;
        }
        #region IServiceLocator Members

        /// &lt;summary&gt;
        ///  Gets all registered instances for a particular type
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;serviceType&quot;&gt;Type of the requested instance&lt;/param&gt;
        /// &lt;returns&gt;IEnumerable of Service Instances&lt;/returns&gt;

        public IEnumerable&lt;object&gt; GetAllInstances(Type serviceType)
        {
            IList list = null;
            try
            {
                list = container.GetAllInstances(serviceType);
            }
            catch (StructureMapException smex)
            {
                throw new ActivationException(message: smex.Message);
            }
            foreach (var o in list)
            {
                yield return o;
            }
        }
        /// &lt;summary&gt;
        /// Gets all registered instances for a particular type
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TService&quot;&gt;Type of the requested instance&lt;/typeparam&gt;
        /// &lt;returns&gt;IEnumerable of Service Instances&lt;/returns&gt;
        public IEnumerable&lt;TService&gt; GetAllInstances&lt;TService&gt;()
        {
            IList&lt;TService&gt; list = null;
            try
            {
                list = container.GetAllInstances&lt;TService&gt;();
            }
            catch (StructureMapException smex)
            {
                throw new ActivationException(message: smex.Message);
            }
            foreach (var o in list)
            {
                yield return o;
            }
        }
        /// &lt;summary&gt;
        /// Gets registered instance for a particular type and key
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;serviceType&quot;&gt;Type of the requested instance&lt;/param&gt;
        /// &lt;param name=&quot;key&quot;&gt;Key/Name of the requested instance &lt;/param&gt;
        /// &lt;returns&gt;requested object instance&lt;/returns&gt;
        public object GetInstance(Type serviceType, string key)
        {
            object o = null;
            try
            {
                o = container.GetInstance(serviceType, key);
            }
            catch (StructureMapException smex)
            {
                throw new ActivationException(message: smex.Message);
            }
            return o;
        }
        /// &lt;summary&gt;
        /// Gets registered instance for a particular type
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;serviceType&quot;&gt;Type of the requested instance&lt;/param&gt;
        /// &lt;returns&gt;requested object instance&lt;/returns&gt;
        public object GetInstance(Type serviceType)
        {
            object o = null;
            try
            {
                o = container.GetInstance(serviceType);
            }
            catch (StructureMapException smex)
            {
                throw new ActivationException(message: smex.Message);
            }
            return o;
        }
        /// &lt;summary&gt;
        /// Gets registered instance for a particular type and key
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TService&quot;&gt;Type of the requested instance&lt;/typeparam&gt;
        /// &lt;param name=&quot;key&quot;&gt;Key/Name of the requested instance&lt;/param&gt;
        /// &lt;returns&gt;requested object instance&lt;/returns&gt;
        public TService GetInstance&lt;TService&gt;(string key)
        {
            TService t;
            try
            {
                t = container.GetInstance&lt;TService&gt;(key);
            }
            catch (StructureMapException smex)
            {
                throw new ActivationException(message: smex.Message);
            }
            return t;
        }

        /// &lt;summary&gt;
        /// Gets registered instance for a particular type
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TService&quot;&gt;Type of the requested instance&lt;/typeparam&gt;
        /// &lt;returns&gt;requested object instance&lt;/returns&gt;
        public TService GetInstance&lt;TService&gt;()
        {
            TService t;
            try
            {
                t = container.GetInstance&lt;TService&gt;();
            }
            catch (StructureMapException smex)
            {
                throw new ActivationException(message: smex.Message);
            }
            return t;

        }

        #endregion

        #region IServiceProvider Members
        /// &lt;summary&gt;
        /// Gets registered instance for a particular type
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;serviceType&quot;&gt;Type of the requested instance&lt;/param&gt;
        /// &lt;returns&gt;requested object instance&lt;/returns&gt;
        public object GetService(Type serviceType)
        {
            object o = null;
            try
            {
                o = GetInstance(serviceType);
            }
            catch (StructureMapException smex)
            {
                throw new ActivationException(message: smex.Message);
            }
            return o;
        }

        #endregion
    }
}
</pre>
<p>So we have our Service Locator class ready.In next part of the post we will see how we can plug this into the ASP.NET MVC 3.0 Framework.</p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=164</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>July 2010 Community Tech Days Presentation</title>
		<link>http://codingndesign.com/blog/?p=161</link>
		<comments>http://codingndesign.com/blog/?p=161#comments</comments>
		<pubDate>Sun, 01 Aug 2010 12:35:33 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[In Focus]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=161</guid>
		<description><![CDATA[Here goes my presentation for July 2010 Microsoft KolkataNET Community Tech Days Parallel Programming in .NET View more presentations from SANKARSAN BOSE.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D161"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D161&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://codingndesign.com/blog/wp-content/uploads/2010/08/ctdj.png"><img class="alignnone size-full wp-image-162" title="ctdj" src="http://codingndesign.com/blog/wp-content/uploads/2010/08/ctdj.png" alt="" width="320" height="245" /></a></p>
<p>Here goes my presentation for July 2010 Microsoft KolkataNET Community Tech Days</p>
<div id="__ss_4739938" style="width: 425px;"><strong style="margin: 12px 0px 4px; display: block;"><a title="Parallel Programming in .NET" href="http://www.slideshare.net/sankarsan78/parallel-programming-in-net">Parallel Programming in .NET</a></strong><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="name" value="__sse4739938" /><param name="src" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=ctd-parallelprogramming-100712232218-phpapp01&amp;rel=0&amp;stripped_title=parallel-programming-in-net" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=ctd-parallelprogramming-100712232218-phpapp01&amp;rel=0&amp;stripped_title=parallel-programming-in-net" allowfullscreen="true" name="__sse4739938"></embed></object></p>
<div style="padding-bottom: 12px; padding-left: 0px; padding-right: 0px; padding-top: 5px;">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/sankarsan78">SANKARSAN BOSE</a>.</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=161</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C# Monitor &#8211; Some Important Points</title>
		<link>http://codingndesign.com/blog/?p=158</link>
		<comments>http://codingndesign.com/blog/?p=158#comments</comments>
		<pubDate>Sun, 01 Aug 2010 12:10:18 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Programming & Languages]]></category>
		<category><![CDATA[Lock]]></category>
		<category><![CDATA[Monitor]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=158</guid>
		<description><![CDATA[In my last post I started the discussion on race conditions and thread synchronization technique using Monitor/lock in C#.In this post also, we will continue with the same and discuss some important points related to the Monitor class. Value Types The lock statement or the Monitor.Enter method expects a parameter of type object on which [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D158"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D158&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my last <a href="http://codingndesign.com/blog/?p=154" target="_blank">post</a> I started the discussion on race conditions and thread synchronization technique using Monitor/lock in C#.In this post also, we will continue with the same and discuss some important points related to the <font color="#0000ff">Monitor</font> class.</p>
<p><span id="more-158"></span></p>
<p><u>Value Types</u></p>
<p>The <font color="#0000ff">lock</font> statement or the <font color="#0000ff">Monitor.Enter</font> method expects a parameter of type object on which the lock is held.So what happens if we pass value type as parameter?</p>
<pre class="brush: csharp;">
private int i;

public void M2()
{
    lock (i)
    {
        Console.WriteLine(&quot;Method::M2::Entered Critical Section&quot;);
    }
} 
</pre>
<p>This will throw a compilation error <font color="#ff0000"><em>CS0185: &#8216;int&#8217; is not a reference type as required by the lock statement</em></font>.</p>
<p>So the natural question is why C# compiler is not allowing us to pass a value type as parameter? This is because when we pass a value type it will be boxed to a reference type i.e. <font color="#0000ff">object</font> in this case.So every time the <font color="#0000ff">lock</font> statement is executed, boxing happens and we get a completely new and separate object instance.So all the executing threads will be able to acquire the lock as the object itself will be a different one.</p>
<p><u>Re-entrancy</u></p>
<p>The locking provided by <font color="#0000ff">Monitor/lock</font> statement are reentrant in nature i.e. the same thread can acquire the lock on same object multiple times.</p>
<pre class="brush: csharp;">
public class A
{
    private object objLock = new object();
    private int i;
    public void M1()
    {
        lock (objLock)
        {
            Console.WriteLine(&quot;Method::M1::Entered Critical Section&quot;);
            M2();
        }
    }
    public void M2()
    {
        lock (objLock)
        {
            Console.WriteLine(&quot;Method::M2::Entered Critical Section&quot;);
        }
    }
}
</pre>
<p>This code will produce the output as:</p>
<p><font color="#004000">Method::M1::Entered Critical Section<br />Method::M2::Entered Critical Section</font>
<p>This is because lock statement allows the same thread to acquire lock on objLock multiple times once within method M1 and then within M2.</p>
<p><u>Lock On Public Types/Objects</u></p>
<p>As per <a href="http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx" target="_blank">MSDN</a> </p>
<blockquote><p><em>In general, avoid locking on a public type, or instances beyond your code&#8217;s control. The common constructs lock (this), lock (typeof (MyType)), and lock (&#8220;myLock&#8221;) violate this guideline: </em>
<ul>
<li><em>lock (this) is a problem if the instance can be accessed publicly. </em>
<li><em>lock (typeof (MyType)) is a problem if MyType is publicly accessible. </em>
<li><em>lock(“myLock”) is a problem since any other code in the process using the same string, will share the same lock.</em></li>
</ul>
</blockquote>
<p>This is very valid guideline I will just try to explain the possible hazards that might arise on using lock on publicly accessible properties/types.Consider the following simple class:</p>
<pre class="brush: csharp;">
public class Foo
{
    public void Bar()
    {
        lock (this)
        {
            Console.WriteLine(&quot;Class:Foo:Method:Bar&quot;);
        }
    }
}
</pre>
<p>Here we are using a lock on the object instance itself.Let&#8217;s assume that this code is part of some library/API where the client code is not supposed to be aware of internal implementation.The client code makes a call to <font color="#400000">Foo/Bar</font> in the following way:</p>
<pre class="brush: csharp;">
public class MyClient
{
    public void Test()
    {
        Foo f = new Foo();
        lock (f)
        {
            ThreadStart ts = new ThreadStart(f.Bar);
            Thread t = new Thread(ts);
            t.Start();
            t.Join();
        }
    }
}
</pre>
<p>This program will simply hang because the main thread acquires a lock on instance of <font color="#400000">Foo</font> and then invokes the method <font color="#400000">Bar</font> on the same instance <font color="#400000">f</font> but on a different thread.The method <font color="#400000">Bar</font> also tries to acquire a lock on this i.e instance of <font color="#400000">Foo</font> (same as <font color="#400000">f</font>) and waits forever.</p>
<p>So to be on the safe side and write bug free code we should always avoid locking on publicly exposed types and properties.In the earlier post we have seen that we can use the <font color="#0000ff">System.Runtime.CompilerServices.MethodImplAttribute</font> to synchronize a method.But this will lead to a lock on the object instance (<font color="#0000ff">this</font>) or the <font color="#0000ff">Type</font> instance of the class(in case of static methods).So it&#8217;s better to avoid this.</p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=158</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Race Condition &amp; Synchronization in C#</title>
		<link>http://codingndesign.com/blog/?p=154</link>
		<comments>http://codingndesign.com/blog/?p=154#comments</comments>
		<pubDate>Sun, 18 Jul 2010 12:36:41 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Programming & Languages]]></category>
		<category><![CDATA[Monitor]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=154</guid>
		<description><![CDATA[We have heard about the term race condition in relation to threads.This is basically a scenario where two or more threads are competing(racing) to read/write from a shared memory location leading to the possibilities of leaving the program in an inconsistent state. Consider the program shown below: public class A { public int x = [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D154"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D154&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>We have heard about the term <font color="#004000">race condition</font> in relation to threads.This is basically a scenario where two or more threads are competing(<font color="#004000">racing</font>) to read/write from a shared memory location leading to the possibilities of leaving the program in an inconsistent state.</p>
<p><span id="more-154"></span></p>
<p>Consider the program shown below:</p>
<pre class="brush: csharp;">
public class A
{
     public int x = 0;
     public int y = 0; 

     public void M1()
     {

             if (y == 0)
             {
                 x = y + 1;
             }
             else x = 5;
     }
     public void M2()
     {
             if (x == 0)
             {
                 y = x + 1;
             }
             else y = 5;
     }
}
</pre>
<p>This a very simple program where the methods M1 and M2 tries to read/write from/to two shared variables x and y.If M1 and M2 are executed using two threads started one after the other we should get an output x=1 and y=5 or x=5 and y=1 depending upon who is scheduled to execute first.</p>
<pre class="brush: csharp;">
A a = new A(); 

ThreadStart ts1 = new ThreadStart(a.M1);
ThreadStart ts2 = new ThreadStart(a.M2); 

Thread t1 = new Thread(ts1); 

Thread t2 = new Thread(ts2); 

t1.Start(); 

t2.Start(); 

t1.Join();
t2.Join();
Console.WriteLine(&quot;x:{0},y:{1}&quot;, a.x, a.y);
</pre>
<p>But when we run it several times we sometimes might see an output where x=1 and y=2 and vice versa.So here what is possibly happening is</p>
<ul>
<li>Thread t1 checks if y==0 and gets true
<li>Thread t2 checks x==0 and gets true
<li>Thread t2 sets x= y+1 = 0 + 1 = 1
<li>Thread t1 sets y=x+1 = 1+1 =2</li>
</ul>
<p>So to ensure a consistent program output we need to ensure that sections of the code where we read/write from x &amp; y will be executed by one thread at a time.These sections of the code are referred to as <font color="#004000">critical sections</font> and the mechanisms to protect the critical sections are known as synchronization techniques.</p>
<p>.NET has a provision of doing so using the methods of the <font color="#0000ff">System.Threading.Monitor</font> class.The two most commonly used methods are:</p>
<ul>
<li><em><font color="#0000ff">public static void Enter(Object obj)</font></em> &#8211; This method is called before entering the critical sections and it grants an exclusive lock on the object passed as parameter.
<li><font color="#0000ff"><em>public static void Exit(Object obj)</em></font> &#8211; This method is called before leaving the critical sections and it releases the&nbsp; exclusive lock on the object passed as parameter.</li>
</ul>
<p>So our modified code&nbsp; now looks like:</p>
<pre class="brush: csharp;">
public class A
{
     public int x = 0;
     public int y = 0;
     private object lockObject = new object();
     public void M1()
     {
         Monitor.Enter(lockObject);
         if (y == 0)
         {
             x = y + 1;
         }
         else
         {
             x = 5;
         }
         Monitor.Exit(lockObject); 

     }
     public void M2()
     {
             Monitor.Enter(lockObject);
             if (x == 0)
             {
                 y = x + 1;
             }
             else
             {
                 y = 5;
             }
             Monitor.Exit(lockObject); 

     }

}
</pre>
<p>When any one of the threads call <font color="#0000ff">Monitor.Enter(lockObject)</font> it gets an exclusive lock on the instance of the object.So the second thread has to wait till that lock is released by <font color="#0000ff">Monitor.Exit(lockObject)</font>.</p>
<p>But from programming perspective this is a bit cumbersome and error prone.What happens if <font color="#0000ff">Monitor.Enter</font> is called but not <font color="#0000ff">Exit</font> particularly in case of exception situations.So it is a good programming practice to implement Monitor as shown below:</p>
<pre class="brush: csharp;">
public void M2()
{

    try
    {
        Monitor.Enter(lockObject);
        if (x == 0)
        {
            y = x + 1;
        }
        else
        {
            y = 5;
        }
    }
    finally
    {
        Monitor.Exit(lockObject);
    }
}
</pre>
<p>C# provides a keyword called <font color="#0000ff"><strong>lock</strong></font> which helps to implement critical section protection in a much simpler and error free way.</p>
<pre class="brush: csharp;">
public void M2()
 {
     lock (lockObject)
     {
         if (x == 0)
         {
             y = x + 1;
         }
         else
         {
             y = 5;
         }
     }
 }
</pre>
<p>The C# compiler will generate the IL code with appropriate calls to <font color="#0000ff">Monitor.Enter/Monitor.Exit</font> and <font color="#0000ff">try{}finally{}</font> blocks as shown below:</p>
<p>&nbsp;</p>
<p><font color="#800000"><em>.method public hidebysig instance void&nbsp; M2() cil managed<br />{<br />&nbsp;&nbsp; &#8230;&#8230;&#8230;&#8230;&#8230;.</em></font></p>
<p><em><font color="#800000">&nbsp;<strong> .try<br />&nbsp; {<br /></strong>&nbsp;&nbsp;&nbsp; IL_0003:&nbsp; ldarg.0<br />&nbsp;&nbsp;&nbsp; IL_0004:&nbsp; dup<br />&nbsp;&nbsp;&nbsp; IL_0005:&nbsp; stloc.1<br />&nbsp;&nbsp;&nbsp; IL_0006:&nbsp; ldloca.s&nbsp;&nbsp; &#8216;&lt;&gt;s__LockTaken0&#8242;<br />&nbsp; </font><font color="#800000"><strong>&nbsp; IL_0008:&nbsp; call&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void [mscorlib]System.Threading.Monitor::Enter(object,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bool&amp;)<br /></strong>&nbsp;&nbsp;&nbsp; &#8230;&#8230;&#8230;&#8230;&#8230;.<br />&nbsp;&nbsp;&nbsp; &#8230;&#8230;&#8230;&#8230;&#8230;. </font></em></p>
<p><font color="#800000"><em>&nbsp;<strong> }&nbsp; // end .try<br />&nbsp; finally<br />&nbsp; {<br /></strong>&nbsp;&nbsp;&nbsp; IL_003d:&nbsp; ldloc.0<br />&nbsp;&nbsp;&nbsp; IL_003e:&nbsp; ldc.i4.0<br />&nbsp;&nbsp;&nbsp; IL_003f:&nbsp; ceq<br />&nbsp;&nbsp;&nbsp; IL_0041:&nbsp; stloc.2<br />&nbsp;&nbsp;&nbsp; IL_0042:&nbsp; ldloc.2<br />&nbsp;&nbsp;&nbsp; IL_0043:&nbsp; brtrue.s&nbsp;&nbsp; IL_004c<br />&nbsp;&nbsp;&nbsp; IL_0045:&nbsp; ldloc.1<br />&nbsp;&nbsp;&nbsp; IL_0046:&nbsp; call&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void [mscorlib]System.Threading.Monitor::Exit(object)<br />&nbsp;&nbsp;&nbsp; IL_004b:&nbsp; nop<br />&nbsp;&nbsp;&nbsp; IL_004c:&nbsp; endfinally<br /><strong>&nbsp; }&nbsp; // end handler</strong><br />&nbsp; IL_004d:&nbsp; nop<br />&nbsp; IL_004e:&nbsp; ret<br />} // end of method A::M2</em></font>
<p>In the above examples the entire code in M1 and M2 are protected as critical sections.We can say these methods itself are synchronized such that one thread can execute them at a time.We can also implement this using the MethodImpl attribute as shown below: </p>
<pre class="brush: csharp;">
[System.Runtime.CompilerServices.MethodImpl
(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public void M2()
{

        if (x == 0)
        {
            y = x + 1;
        }
        else
        {
            y = 5;
        }
}
</pre>
<p>In the IL compiler will add the synchronized keyword as shown below:
<p><em><font color="#800000">.method public hidebysig instance void&nbsp; M2() cil managed <strong>synchronized</strong><br />{</font></em>
<p><em><font color="#800000">&#8230;&#8230;&#8230;&#8230;.</font></em></p>
<p><em><font color="#800000">}</font></em></p>
<p>This implementation flag called <strong><font color="#0000ff">synchronized</font></strong> tells the JIT compiler to insert code to acquire lock on entry of the method and release the lock on exit of the method.For instance methods this lock is placed on object instance i.e. this parameter and for static methods this lock is placed on <font color="#0000ff">System.Type</font>. </p>
<p>So in this post we have discussed about the various ways to implement locking of critical sections.In the next post we will some other mechanisms&nbsp; of locking which is conceptually little bit different from internal implementation standpoint.</p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=154</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Single Assignment &amp; readonly Fields in C#</title>
		<link>http://codingndesign.com/blog/?p=150</link>
		<comments>http://codingndesign.com/blog/?p=150#comments</comments>
		<pubDate>Sun, 27 Jun 2010 16:40:41 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Programming & Languages]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=150</guid>
		<description><![CDATA[We have all heard about immutable objects, the objects whose field values cannot be altered throughout it&#8217;s lifetime.Immutable objects are simpler to deal with in case concurrent programs where they can be shared between multiple threads.The single assignment variables variables which is once assigned a value cannot be reassigned again.These are inherently immutable in nature.In [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D150"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D150&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>We have all heard about immutable objects, the objects whose field values cannot be altered throughout it&#8217;s lifetime.<font color="#0000ff">Immutable</font> objects are simpler to deal with in case concurrent programs where they can be shared between multiple threads.The <font color="#0000ff">single assignment</font> variables variables which is once assigned a value cannot be reassigned again.These are inherently immutable in nature.In languages like <font color="#004000">Haskell,Erlang,F#</font> etc. variables are by default single assignment variables.</p>
<p><span id="more-150"></span></p>
<p>The following code shows how <font color="#004000">F#</font> throws error when you try to reassign a variable:</p>
<p>&#160;</p>
<p><a href="http://codingndesign.com/blog/wp-content/uploads/2010/06/fssav.png"><img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" border="0" alt="fssav" src="http://codingndesign.com/blog/wp-content/uploads/2010/06/fssav_thumb.png" width="314" height="154" /></a> </p>
<p>As <font color="#004000">F#</font> is not a pure functional language and some imperative styles are also allowed.So we can have <font color="#0000ff">mutable</font> variables as well:</p>
<p><a href="http://codingndesign.com/blog/wp-content/uploads/2010/06/fssav1.png"><img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" border="0" alt="fssav1" src="http://codingndesign.com/blog/wp-content/uploads/2010/06/fssav1_thumb.png" width="190" height="127" /></a> </p>
<p>But how does <font color="#0000ff">C#</font>, the <em>lingua franca</em> of .NET Framework handle this.C# provides the <em><font color="#0000ff">readonly</font></em> modifier for similar purposes.A variable marked with this modified can only be initialized while declaration or from within the constructor.Consider the code below:</p>
<pre class="brush: csharp;">
class Program
{
    static void Main(string[] args)
    {
        C c = new C();
        c.i = 10;
        Console.Read();
    }
}
public class C
{
    public readonly int ; 

}
</pre>
<p>This will lead to a compile error <em><font color="#ff0000">&quot;error CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer)&quot;</font></em></p>
<p>However the following code runs fine:</p>
<pre class="brush: csharp;">
class Program
{
    static void Main(string[] args)
    {
        C c = new C();
        Console.Read();
    }
}
public class C
{
    public readonly int i =0; 

    public C()
    {
        i = 5;
        i = 7;
    }
}
</pre>
<p>This is not allowing to assign value apart from the initialization process but it is not pure single assignment.<em><strong>As it is very clear that I can assign the variable multiple times in the constructor.</strong></em></p>
<p>But, what happens if we pass the field i as a <font color="#0000ff">ref</font> parameter in some method which alters it&#8217;s value.</p>
<pre class="brush: csharp;">
class Program
{
    static void Main(string[] args)
    {
        C c = new C();
        D d = new D();
        d.M1(ref c.i);
        Console.Read();
    }
}
public class C
{
    public readonly int i =0; 

    public C()
    {
        i = 5;
        i = 7;
    }
}
public class D
{
    public void M1(ref int i)
    { 

        i++;
    }
}
</pre>
<p>This will not compile and throw compilation error <em><font color="#ff0000">&quot;error CS0192: A readonly field cannot be passed ref or out (except in a constructor)&quot;.</font></em></p>
<p>As a readonly variable can be assigned multiple times, it might lead to problems where the instance of the object is shared before the entire constructor executes as shown below:</p>
<pre class="brush: csharp;">
class Program
{
     static void Main(string[] args)
     {
         C c = new C();
         Console.WriteLine(&quot;Value of i={0}&quot;, c.i);
         Console.Read();
     }
}
public class C
{
     public readonly int i =5; 

     public C()
     {
         Console.WriteLine(&quot;Class C::Constructor::Start&quot;);

         E e = new E();
         WaitCallback w = (o) =&gt;
         {
             e.M1(this);
         }; 

         ThreadPool.QueueUserWorkItem(w);
         //Do Something.
         Thread.Sleep(100);
         i = 7; 

         Console.WriteLine(&quot;Class C::Constructor::End&quot;);
     }
}
public class E
{
     public void M1(C c)
     {
         Console.WriteLine(&quot;Class D::Method M1::Start&quot;);
         if (c.i == 5)
         {
             Console.WriteLine(&quot;Somethings.......&quot;);
         }
         Console.WriteLine(&quot;Class D::Method M1::End&quot;);
     }
}
</pre>
<p>Here the output will be:</p>
<p>Class C::Constructor::Start    <br />Class D::Method M1::Start     <br />Somethings&#8230;&#8230;.     <br />Class D::Method M1::End     <br />Class C::Constructor::End     <br />Value of i=7</p>
<p>&#160;</p>
<p>In this the final value of the readonly variable i is 7 but the method M1 gets a value of 5 and performs something which is not correct.</p>
<p>Anyway&#8217;s sharing an object instance before the constructor executes is not a recommended programming practice.But this also reveals a potential weakness of readonly keyword in terms of concurrency.</p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=150</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Caching in HTTP &#8211; Part 1</title>
		<link>http://codingndesign.com/blog/?p=141</link>
		<comments>http://codingndesign.com/blog/?p=141#comments</comments>
		<pubDate>Sun, 30 May 2010 07:35:38 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Web Apps]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[HTTP]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=141</guid>
		<description><![CDATA[A Web Cache stores copies of web resources(html/images etc.) returned by the requests that pass through it and next time onwards returns the stored copy to the client instead of forwarding the same request to the server.This helps to improve the speed of content delivery, reduce bandwidth usage and processing load on the servers.Caching as [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D141"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D141&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>A <span style="color: #0000ff;">Web Cache</span> stores copies of web resources(html/images etc.) returned by the requests that pass through it and next time onwards returns the stored copy to the client instead of forwarding the same request to the server.This helps to <em><span style="color: #004000;">improve the speed of content delivery, reduce bandwidth usage and processing load on the servers</span></em>.Caching as a concept is nothing new and can be seen in many other areas of software and hardware technologies as well.In this post we will discuss about what all options HTTP as a protocol provides to control and manipulate the caching of web resources.<br />
<span id="more-141"></span><br />
Before getting into the HTTP specific details let&#8217;s take a quick look into some of the common caching related terminologies:</p>
<ul>
<li><span style="color: #0000ff;">Cache Hit</span> &#8211; When a request arrives at the cache it can serve the local copy.</li>
<li><span style="color: #0000ff;">Cache Miss</span> &#8211; When a request arrives at the cache it does not have the response available in the cache and has to get it from the server.</li>
<li><span style="color: #0000ff;">Revalidation</span> &#8211; From time to time the cache needs to check whether the cached documents are up-to-date with the server or not.This is known as the <span style="color: #0000ff;">Freshness Check or Revalidation</span>.</li>
</ul>
<p>The conditions based on which this freshness check or revalidation is triggered will be discussed later.We will first see what provisions HTTP has to perform such a check.This is done using <em><span style="color: #0000ff;">If-Modified-Since</span></em> HTTP Header field.This header is passed in the HTTP Request as:</p>
<p><span style="color: #004000;"><strong>If-Modified-Since: &lt;Date Time&gt;</strong></span></p>
<p>If the document is modified since the date mentioned in If-Modified-Since header then the server will return the latest document as response with <span style="color: #0000ff;">HTTP Status Code 200</span> other wise it will send the <span style="color: #0000ff;">HTTP Status 304: Not Modified</span> with empty response body.</p>
<p>To test the same I have written simple Http Client in C# and tried to fetch a wikipedia page as shown below:</p>
<pre class="brush: csharp;">
HttpWebRequest wr = null;
HttpWebResponse response = null;
try
{
    wr = HttpWebRequest.Create(&quot;http://en.wikipedia.org/wiki/Lady_Gaga&quot;) as HttpWebRequest;
    wr.IfModifiedSince = DateTime.Parse(&quot;06/30/1910&quot;);
    response = wr.GetResponse() as HttpWebResponse;
    Console.WriteLine((response as HttpWebResponse).StatusCode);
}
catch (Exception ex)
{
    Console.WriteLine(&quot;Error:&quot; + ex.Message);
}
finally
{
    if(response!=null) response.Close();
} 

Console.Read();
</pre>
<p>Here I have passed a date in 1910 in the If-Modified-Since header field and got a status code 200 since the page was obviously modified since such a old date.</p>
<p>If I change the date something to future I will get the following output:</p>
<p><em><span style="color: #ff0000;">Error:The remote server returned an error: (304) Not Modified.</span></em></p>
<p>This is because the page was not modified since such a future date.</p>
<p>Now we will examine the response headers a little bit more closely adding following lines of code in the program:</p>
<pre class="brush: csharp;">
for(int i=0;i&lt;response.Headers.Count;i++)
{
    Console.WriteLine(&quot;Response Header:: {0} - {1}&quot;,response.Headers.Keys[i] , response.Headers[i].ToString());
}
</pre>
<p>The output is shown below:</p>
<p><span style="color: #004000;">Response Header:: Content-Language &#8211; en<br />
Response Header:: Vary &#8211; Accept-Encoding,Cookie<br />
</span><span style="color: #004000;"><strong>Response Header:: Age &#8211; 1761<br />
Response Header:: X-Cache &#8211; HIT from sq61.wikimedia.org,MISS from sq65.wikimedia<br />
.org<br />
Response Header:: X-Cache-Lookup &#8211; HIT from sq61.wikimedia.org:3128,MISS from sq<br />
65.wikimedia.org:80<br />
</strong>Response Header:: Connection &#8211; keep-alive<br />
Response Header:: Content-Length &#8211; 215691<br />
</span><span style="color: #004000;"><strong>Response Header:: Cache-Control &#8211; private, s-maxage=0, max-age=0, must-revalidate<br />
</strong>Response Header:: Content-Type &#8211; text/html; charset=UTF-8<br />
Response Header:: Date &#8211; Sun, 30 May 2010 06:32:28 GMT<br />
Response Header:: Last-Modified &#8211; Sun, 30 May 2010 04:22:41 GMT<br />
Response Header:: Server &#8211; Apache</span></p>
<p>The response header <span style="color: #0000ff;">Age</span> tells us the amount of time elapsed since the document was sent from (or revalidated ) from the server.The value is in seconds.This is  one of the factors in computing the criteria for freshness checks of the cached documents.</p>
<p>X headers are non standard or extension HTTP headers.The <span style="color: #0000ff;">X-Cache and X-Cache-Lookup</span> is used by the Squid Proxy Server which is used by wikipedia for caching.The values indicate multiple levels of cache where there is MISS from sq65.wikimedia.org and HIT from sq61.wikimedia.org.</p>
<p>Another header Cache-Control, the most important HTTP header in terms of caching needs a detailed discussion which we will take up in the next part of the series.</p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=141</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Flex with WCF Service Over Https &#8211; Part 1</title>
		<link>http://codingndesign.com/blog/?p=133</link>
		<comments>http://codingndesign.com/blog/?p=133#comments</comments>
		<pubDate>Sun, 11 Apr 2010 12:52:33 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Web Apps]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=133</guid>
		<description><![CDATA[For the past week I am trying to play around with Flex and find out how it works with different back end service endpoints.In this post I will discuss about how Flex works with a simple WCF Service over HTTPS and also the issues I encountered while doing so. Okay, so let&#8217;s get started with [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D133"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D133&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>For the past week I am trying to play around with Flex and find out how it works with different back end service endpoints.In this post I will discuss about how Flex works with a simple WCF Service over HTTPS and also the issues I encountered while doing so.</p>
<p><span id="more-133"></span></p>
<p>Okay, so let&#8217;s get started with the WCF service first.I have a POCO named Contact which is decorated as a <span style="color: #0000ff;">DataContract</span> as shown below:</p>
<pre class="brush: csharp;">
[DataContract]
public class Contact
{
     [DataMember ]
     public string Name { get; set; }
     [DataMember]
     public string Email { get; set; }
     [DataMember]
     public string ContactType { get; set; }
}
</pre>
<p>The <span style="color: #0000ff;">ServiceContract</span> and it&#8217;s implementation is shown below:</p>
<pre class="brush: csharp;">
[ServiceContract]
public interface IContact
{
    [OperationContract]
    Contact[] GetContactList();

}

public class ContactService : IContact
  {

      #region IContact Members

      public Contact[] GetContactList()
      {
          return new Contact[]
                     {
                      new Contact()
                          {
                              ContactType =&quot;Friend&quot;,Name=&quot;John Doe&quot;,
                              Email=&quot;John.Doe@xyz.com&quot;
                          },
                      new Contact()
                          {
                              ContactType =&quot;Friend&quot;,Name=&quot;Robin Crusoe&quot;,
                              Email=&quot;Robin.Crusoe@xyz.com&quot;
                          },
                      new Contact()
                          {
                              ContactType =&quot;Friend&quot;,Name=&quot;VanValkenburg&quot;,
                              Email=&quot;Valkenburg@xyz.com&quot;
                          },
                       new Contact()
                          {
                              ContactType =&quot;Relative&quot;,Name=&quot;Anthony Price&quot;,
                              Email=&quot;Anthony.Price@xyz.com&quot;
                          },
                     };
      }

      #endregion
  }
</pre>
<p>So it&#8217;s all very simple.. demo.. demo.. with no demons of complexity.One more thing, I have made the endpoint secure with Transport level security.</p>
<pre class="brush: xml;">
&lt;system.serviceModel&gt;
  &lt;bindings&gt;
   &lt;basicHttpBinding&gt;
    &lt;binding name=&quot;custombasicHttpBinding&quot;&gt;
      &lt;security mode=&quot;Transport&quot; &gt;
      &lt;/security&gt;
    &lt;/binding&gt;
   &lt;/basicHttpBinding&gt;
  &lt;/bindings&gt;
  &lt;services&gt;
   &lt;service behaviorConfiguration=&quot;DemoServiceApp.ContactService&quot;
    name=&quot;DemoServiceApp.ContactService&quot;&gt;
    &lt;endpoint address=&quot;https://localhost/DemoServiceApp/ContactService.svc&quot;
     binding=&quot;basicHttpBinding&quot; bindingConfiguration=&quot;custombasicHttpBinding&quot;
     contract=&quot;DemoServiceApp.IContact&quot;&gt;
     &lt;identity&gt;
      &lt;dns value=&quot;localhost&quot; /&gt;
     &lt;/identity&gt;
    &lt;/endpoint&gt;
    &lt;endpoint address=&quot;mex&quot; binding=&quot;mexHttpsBinding&quot; bindingConfiguration=&quot;&quot;
     contract=&quot;IMetadataExchange&quot; /&gt;
   &lt;/service&gt;
  &lt;/services&gt;
        &lt;behaviors&gt;
   &lt;serviceBehaviors&gt;
    &lt;behavior name=&quot;DemoServiceApp.ContactService&quot;&gt;
     &lt;serviceMetadata httpGetEnabled=&quot;false&quot; httpsGetEnabled=&quot;true&quot;
      httpsGetUrl=&quot;https://localhost/DemoServiceApp/ContactService.svc/wsdl&quot; /&gt;
     &lt;serviceDebug includeExceptionDetailInFaults=&quot;false&quot; /&gt;
    &lt;/behavior&gt;
   &lt;/serviceBehaviors&gt;
  &lt;/behaviors&gt;
    &lt;/system.serviceModel&gt;
</pre>
<p>In my Flex application I want to call this service and display the data in a datagrid.To do so I followed the steps mentioned below (using Flexbuilder)</p>
<ul>
<li><strong><span style="text-decoration: underline;">Create the ActionScript Proxy Classes</span></strong> &#8211; I used the Flexbuilder option <strong>Data -&gt; Import Web Service (WSDL)</strong>.But I got the following error:</li>
</ul>
<p><a href="http://codingndesign.com/blog/wp-content/uploads/2010/04/wsdlflex.png"><img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" src="http://codingndesign.com/blog/wp-content/uploads/2010/04/wsdlflex_thumb.png" border="0" alt="wsdlflex" width="308" height="128" /></a></p>
<p>So what&#8217;s happening? I have given the URI correct then why is not FlexBuilder able to connect?After checking the log at <span style="color: #004000;">C:\Documents and Settings\Administrator\My Documents\Flex Builder 3\.metadata</span> I found the following error:</p>
<p><em><span style="color: #ff0000;">javax.wsdl.WSDLException: WSDLException: faultCode=OTHER_ERROR: Unable to resolve imported document at &#8216;https://localhost/DemoServiceApp/ContactService.svc?wsdl&#8217;.: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target</span></em></p>
<p>So it&#8217;s clear that the SSL handshake is failing and FlexBuilder is not able to locate the certificate.FlexBuilder is based on Eclipse platform which runs on a JVM.For this we need to add the certificate in the certificate store used by JVM under which Flexbuilder is running.The certificate store is the <span style="color: #0000ff;">cacerts</span> file present under <span style="color: #004000;">D:\Program Files\Adobe\Flex Builder 3\jre\lib\security</span>.This is done with <span style="color: #0000ff;"><strong><a href="http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html" target="_blank">keytool</a></strong></span> command line tool coming with JRE.</p>
<p>So after adding the certificate everything was set, but alas again there was an error <span style="color: #ff0000;"><em>Provider com.bea.xml.stream.MXParserFactory not found</em></span>. After searching about this error message in google I found that it&#8217;s a known bug in FlexBuilder</p>
<p><a title="http://bugs.adobe.com/jira/browse/FB-13542?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel" href="http://bugs.adobe.com/jira/browse/FB-13542?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel">http://bugs.adobe.com/jira/browse/FB-13542?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel</a></p>
<p>I could not locate the fix and used the hack provided in the site <a title="http://poradowski.com/fb/" href="http://poradowski.com/fb/">http://poradowski.com/fb/</a>. The root cause seems to be</p>
<p><em>&#8220;<span style="color: #804040;">bug with resolving multiple, recursive &lt;xsd:import&gt; declarations in WSDL that import type schemas</span>&#8220;</em></p>
<p>So now after copying the file <a title="https://ovh.poradowski.net/com.adobe.flexbuilder.axis2_3.0.214193.jar" href="https://ovh.poradowski.net/com.adobe.flexbuilder.axis2_3.0.214193.jar">https://ovh.poradowski.net/com.adobe.flexbuilder.axis2_3.0.214193.jar</a> to <span style="color: #004000;">D:\Program Files\Adobe\Flex Builder 3\plugins</span> folder everything went fine and set of ActionScript classes got generated.</p>
<p>In the next part of the post we will see what these classes are and how to make the service call.</p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=133</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>BerkleyDB &amp; C# &#8211; Part 1</title>
		<link>http://codingndesign.com/blog/?p=127</link>
		<comments>http://codingndesign.com/blog/?p=127#comments</comments>
		<pubDate>Sun, 31 Jan 2010 01:04:15 +0000</pubDate>
		<dc:creator>sankarsan</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[BerkleyDB]]></category>

		<guid isPermaLink="false">http://codingndesign.com/blog/?p=127</guid>
		<description><![CDATA[In my last post I have discussed about the BerkleyDB product family.In this post we will discuss about using BerkleyDB with it’s C# API set.Before getting into the details we will take a quick look into the different access methods provided by Berkley DB. BTree – Here the data is stored in a balanced tree [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D127"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fcodingndesign.com%2Fblog%2F%3Fp%3D127&amp;source=sankarsan&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my last <a href="http://codingndesign.com/blog/?p=122" target="_blank">post</a> I have discussed about the BerkleyDB product family.In this post we will discuss about using BerkleyDB with it’s C# API set.Before getting into the details we will take a quick look into the different access methods provided by Berkley DB.</p>
<ul>
<li><span style="color: #0000ff;">BTree</span> – Here the data is stored in a balanced tree structure.We can put complex as well as simple types as key/values in the database.Duplicate key values also can be stored.</li>
<li><span style="color: #0000ff;">Hash</span> – Here the data is stored in a hash table structure, both simple &amp; complex types can be stored as key/values in the database, database can be configured to store duplicate key values as well.</li>
<li><span style="color: #0000ff;">Queue</span> – Here data is stored as fixed length records, logical record number is used as the key.This is specially designed for fast inserts at the tail of the queue and retrieval/deletion from the head of the queue.</li>
<li><span style="color: #0000ff;">Recno</span>– Like Queue here also the logical record number is used as the key store fixed/variable length records.</li>
</ul>
<p>BTree database is very suitable when there is some locality reference i.e. query for a given key will be followed by query for one of it’s neighbours.</p>
<p>Hash database is suitable for large dataset.This is because internal information stored by the database in case of BTree is larger than that of Hash.So when the application data grows there will be very little space left in the cache for actual application data in case of BTree databases.</p>
<p>Queue &amp; Recno databases are suitable for cases where we want to use the logical record number as the key.Queue only supports fixed length records whereas Recno support both fixed and variable length records.</p>
<p>The access methods needs to be selected right at the beginning before opening the databases.In the C# API the following classes provides an abstraction of the databases with different access methods:</p>
<ul>
<li><span style="color: #0000ff;">BTreeDatabase</span></li>
<li><span style="color: #0000ff;">HashDatabase</span></li>
<li><span style="color: #0000ff;">QueueDatabase</span></li>
<li><span style="color: #0000ff;">RecnoDatabase</span></li>
</ul>
<p>Each of these databases classes have a corresponding configuration class which is used to hold the configuration information for those databases e.g. BTreeDatabase as an accompanying class called <span style="color: #0000ff;">BTreeDatabaseConfig</span>.</p>
<p>The code sample below shows how to open a BerkleyDB BTreeDatabase.</p>
<pre class="brush: csharp;">
BTreeDatabase btdb = null;
BTreeDatabaseConfig btcfg = new BTreeDatabaseConfig();
btcfg.Duplicates = DuplicatesPolicy.SORTED;
btcfg.Creation = CreatePolicy.IF_NEEDED;

try
{
btdb = BTreeDatabase.Open(@&quot;C:\\BTreeSample.db&quot;, btcfg);
Console.WriteLine(&quot;Database Opened..&quot;);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (btdb != null) btdb.Close();
}
Console.ReadLine();
</pre>
<p>Here we have first setup the BTreeDatabaseConfig and then opened the database by passing the filename and config.</p>
<p>The BTreeDatabaseConfig exposes two important properties:</p>
<ul>
<li><span style="color: #0000ff;">Duplicates</span> – This property is of type <span style="color: #0000ff;">DuplicatePolicy</span> enumeration.This enumeration supports three values
<ul>
<li><span style="color: #0000ff;">NONE</span> – This means duplicate keys will not be allowed.</li>
<li><span style="color: #0000ff;">SORTED</span> – This means duplicate keys will be stored in a sorted fashion</li>
<li><span style="color: #0000ff;">UNSORTED</span> – This means duplicate keys will be stored in an unsorted fashion</li>
</ul>
</li>
<li><span style="color: #0000ff;">Creation</span> – This property is of type <span style="color: #0000ff;">CreatePolicy</span> enumeration.This enumeration supports three values
<ul>
<li><span style="color: #0000ff;">NEVER</span> –It will never create the database.Only existing DB will be opened</li>
<li><span style="color: #0000ff;">ALWAYS</span> – It will always try to create the database and throw exception if database already exists. <em><span style="color: #800000;"><strong>BerkeleyDB.DatabaseException: File exists</strong></span></em></li>
<li><span style="color: #0000ff;">IF_NEEDED </span>– This will create the database if it does not exists otherwise will open the existing database.</li>
</ul>
</li>
</ul>
<p>So we have now seen how to configure and open an BerkleyDB database.In the next post we will how insert &amp; retrieve values from it.</p>
]]></content:encoded>
			<wfw:commentRss>http://codingndesign.com/blog/?feed=rss2&amp;p=127</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
