Saturday, October 6, 2012

Editable wpf control

Recently I've involved myself in a fun project which is basically a plugin for outlook that can automatically tag my mails based on some regular expression. During the time I noticed that I might need a control that can switch between different mode from view to edit and vice-versa. The control should also be able to display a list of possible tags for the particular mail item. I searched and searched for this kind of free control and could not find any. So I decided to build my own, which is in a way fun too. Rather than building this in winform, I decided to stick with wpf. If you are wondering why then you surely are missing something. I'd not even think of building such control, if wpf wasn't there. Styling and adding behavior in wpf controls are so much easier than doing the same in winform. I remember back then when I had to build a custom grid control with group header in winform. After that I never thought of custom building anything in winform.

So this is just a basic control with the functionality as described earlier above. It is derived from textbox control and modified the template itself. So coollll.... Just few lines of code to switch back and forth between textblock and the textbox content presenter itself and my basic model is almost ready. The control can also behave like autocomplete like I said earlier and for that, after scratching my head for a day or two I decided to make it MVVM friendly. The user can provide the autocomplete list data provider which is basically a class that implements IAutoCompleteDataCollector. 


public interface IAutoCompleteDataCollector
    {
        void GatherData(AutoCompleteDataArgs arg);
    }


On top of it you can also switch the datatemplate of the autocomplete listbox. 

I suggest you to check out the source code and extend it on your own. Please remember that this is still in it's infancy. I might or might not take interest in further extending this control. And also note that some of the things have been borrowed from different sources such as the cross button, you can see in the listbox control in a sample mainwindow form. 


Please do not forget to send me a link to such wpf controls if you have any.


Friday, July 20, 2012

Fun with Asp.net MVC 3 Custom Json Model Binder


If you have been using Asp.net MVC for quite a while then your are probably familiar with the concept of model binding and more specifically Json Model Binding. Starting from MVC3, Asp.net MVC is elegantly capable of binding json string passed from client into a full blown model. Asp.net MVC provides a new JsonValueProviderFactory that is capable of supplying model values from the json string. To be able to use this feature your client code(javascript) needs to change the content header to application/json and that’s it, your model parameter in the action is automatically set with required/passed values.
Before digging more into Custom Json Model Binder I’d like to show you how this so called JsonValueProviderFactory works. (I hope nobody would sue me for pasting this code here.)

private static object GetDeserializedObject(ControllerContext controllerContext) {
           if (!controllerContext.HttpContext.Request.ContentType.StartsWith(
"application/json", StringComparison.OrdinalIgnoreCase)) {
               // not JSON request
               return null;
           }

           
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
           string bodyText = reader.ReadToEnd();
           if (
String.IsNullOrEmpty(bodyText)) {
               // no JSON data
               return null;
           }

           JavaScriptSerializer serializer = new JavaScriptSerializer();
           object jsonData = serializer.DeserializeObject(bodyText);
           return jsonData;
       }


The code is quite neat and clean and it’s clear that you don’t need any magic or complex code to handle the json string. Like I said earlier to use the JsonValueProviderFactory your request header should have content-type specified as application/json and to add to it the whole request stream should be a json string. JsonValueProviderFactory then reads this whole input stream and deserializes this string into an object.


Let me take a moment to state that my intention here is not to question the existing Json binding capability of Asp.net MVC or JsonValueProviderFactory. They are self-sufficient and works pretty well in many scenarios. The purpose of my post here is to explain how to create a Custom Model Binder, how to plug them into MVC framework, overcome a scenario when your whole request stream may not be the json string and show how extensible Asp.net MVC is and how easy it really is.  Allow me to further clarify this topic.


Asp.net MVC has pretty neat request pipeline, starting from the UrlRouteModule that intercepts every request, finds the most suitable route, hand over the request to the MvcHandler in the particular route, request the controller from the controller factory, hand over the request then to the controller, load tempdata,  find the action name, hand over the execution of action to action invoker, Action Invoker then finds the action method, detects the action filters applicable to the action method, run authorization filter if any, validate request for XSS attack, build parameter values by finding the appropriate model binder and value providers(model binders request value from value provider), model binder in the course performs validation, execute the action method by supplying the required parameter values then boooom, your action method gets called. There’s a whole lot of thing going on between the browser’s request and your controller’s action method. But the architecture is fairly simple and far more extensible that Asp.net webform. At any point in the request pipeline you can plug in your own implementation from your own MvcHandler to your own value provider. If you want more details on this I suggest you do some googling or binging and of course check out the Asp.net MVC source code itself. It’s open source. It's one of the reason why I love it.

In this post I’m just going to focus myself and you in plugging in our custom model binder. Please note that you probably won’t need to create your own model binder unless you have your own custom model binding functionality to be implemented for specific scenario or type. Asp.net MVC 3 already has 3 custom model binders for System.Web.HttpPostedFileBase, Byte array and System.Data.Linq.Binary and a default model binder which is capable of binding a single value type parameter to any complex type. In our case we do have a specific requrement, that is, we do not want to send the whole request as json string and we may not always send the content type as json, which is what Asp.net MVC 3 doesn’t want to handle. But it’s cool, coz’ it’s not that hard anyway.

Any model binder that you create needs to implement IModelBinder and implement BindModel() function.

public interface IModelBinder {
       object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);
   }


If your custom model binder is unable to bind the model, then simply return null, MVC will do the rest.

Now lets create a tiny sample MVC project to see how and where can we plug in this custom model binder so that MVC framework can call this binder to build our model class and more over, so that you can understand why did we create this model binder in first place when MVC 3 already has a JsonValueProviderFactory which does pretty much what we did and a powerful default model binder.

I do not want to go into detail how to creating MVC project. This is something I assume that you already know of, otherwise there’s no point in learning how to create a custom model binder.

But before doing our thing let me demonstrate how we can leverage the exising JsonValueProviderFactory to bind our models automatically, let’s create a GuestBookController

public class GuestBookController : Controller
   {
       //
       // GET: /GuestBook/

       public
ActionResult Index()
       {
           return View();
       }


       public
JsonResult Save(string key,GuestBook guest)
       {
           if (guest==null )
           {
               return Json(false);
           }

           return Json(true);

       }

   }


The application we are going to create is quite simple. We have a simple Guest Book data entry form with three fields-GuestName, GuestAddress, GuestAge. When a user clicks on Save Button we will post the data to Save Action using jquery ajax. The Save Action method takes two parameters- “key” of type string(which doesn’t have any significance, but is here to demonstrate how multiple parameters in action can be supplied as json string) and our model “guest” of type GuestBook. The Save Action simply checks to see if guest is null or not and returns json value true or false accordingly.

Now lets see how does our GuestBook model looks like.

public class GuestBook
   {
       public string GuestName { get; set; }
       public string GuestAddress { get; set; }
       public int GuestAge { get; set; }

   }


Now let’s create our Data entry view(index.cshtml)

@{
   ViewBag.Title =
"Index";
}

<br/>
@using(Html.BeginForm(
"Save", "GuestBook", FormMethod.Post, new { @class = "form-horizontal" })){

 <fieldset>
   <legend>Add Guest Entry</legend>
     <div class="control-group">
         <label class="control-label" for="guestName">Guest Name</label>
         <div class="controls">
             <input type="text" class="input-xlarge" id="guestName">
             
         </div>
     </div>
     <div class="control-group">
         <label class="control-label" for="guestAddress">Address</label>
         <div class="controls">
             <input type="text" class="input-xlarge" id="guestAddress">
             
         </div>
     </div>
     <div class="control-group">
         <label class="control-label" for="guestAge">Age</label>
         <div class="controls">
             <input type="text" class="input-xlarge" id="guestAge">
             
         </div>
     </div>
     <div class="form-actions">
           <button type="submit" id="save" class="btn btn-primary">Save changes</button>
           <button class="btn" id="cancel">Cancel</button>
         </div>
 </fieldset>


}


<script type="text/javascript">

   $(document).ready(function () {
       $("#save").click(function (e) {
           var act = {};
           var guestBook = {};
           guestBook.GuestName = $('#guestName').val();
           guestBook.GuestAddress = $('#guestAddress').val();
           guestBook.GuestAge = $('#guestAge').val();
           act.guest = guestBook;
           act.key= "my key" ;

           var guestBookString = JSON.stringify(act);

           $.ajax({
               url: '@Url.Action(
"Save")',
               dataType: 'json',
               contentType: 'application/json',
               type: 'POST',
               data: guestBookString,
               success: function (result) {
                   alert(result);
               },
               error: function (xhr) {
                   alert(xhr.responseText);
               }
           });

           return false;
       });

       $('#cancel').click(function (e) {
           return false;
       })
   });
</script>


Which looks something like this.


Please note that I’ve used Twitter bootstrap to customize the look. It’s a cool project with a lot of goodness in it. You can download it yourself from here. If you don’t want to use it then it’s ok, just have three input text fields, three labels, and two buttons. I’ve also used jquery 1.7.2 for ajax call.

The code is pretty straight forward. When the save button is clicked you build a guest object with properties similar to your c# GuestBook model. Then create an object named act with guest and key property, which are the parameter names in your Save action. The code then serializes the act object as string and ajax calls the Save action method, by supplying necessary parameters to $.ajax() function. There are two things you should notice. First is the data option which is the json string and second is the contentType, which is set as “application/json”. You are required to set the contentType to “application/json” so that JsonValueProviderFactory to come into play(Please check the source code that I’ve posted at the top of this post). This is all you need to leverage the existing capability of Asp.net MVC 3 to bind the json string. Now run the application, input the desired values and click on save button. Before that don’t forget to place breakpoint somewhere in Save action method to check if the guest parameter of type Guest has been properly bound with proper values. And I’m pretty sure it does, if everything is in place.

This is how you can bind json string in Asp.net MVC 3. Now let’s dig into our problem. Let me rephrase it again, as JsonValueProvider factory expects we are not going to change the contentType to “application/json” and our whole request stream(data) won’t be json string. Only the guest parameter will be supplied as json string. Now keeping everything as they are, let’s change your javascript function as.

<script type="text/javascript">

   $(document).ready(function () {
       $("#save").click(function (e) {
           //var act = {};
           var guestBook = {};
           guestBook.GuestName = $('#guestName').val();
           guestBook.GuestAddress = $('#guestAddress').val();
           guestBook.GuestAge = $('#guestAge').val();
           //act.guest = guestBook;
           //act.key= "my key" ;

           var guestBookString = JSON.stringify(guestBook);

           $.ajax({
               url: '@Url.Action(
"Save")',
               dataType: 'json',
               //contentType: 'application/json',
               type: 'POST',
               data: {key:"my key",guest:guestBookString},
               success: function (result) {
                   alert(result);
               },
               error: function (xhr) {
                   alert(xhr.responseText);
               }
           });

           return false;
       });

       $('#cancel').click(function (e) {
           return false;
       })
   });
</script>


Here I’ve commented the contentType parameter in $.ajax call and now the data parameter is not the json string anymore. It’s the key value pair of “key” and “guest” as params(which is similar to the parameter names in our Save action method) and their corresponding values. Now start debugging your application and check to see if the guest parameter in the action has been bound with proper values. You will probably notice that the guest parameter will be null. Shame on us. We just acted like a 4 year old stubborn child and didn’t do what somebody else expected us to do. Now if we want things to work properly then let’s add few more things.

Now let’s add our custom json binder into our project. The JsonBinder looks something like this.

public class JsonBinder : IModelBinder
   {
       public object BindModel(
ControllerContext controllerContext, ModelBindingContext bindingContext)
       {
           //return base.BindModel(controllerContext, bindingContext);
           if (controllerContext == null)
           {
               throw new
ArgumentNullException("controllerContext");
           }

           if (bindingContext == null)
           {
               throw new
ArgumentNullException("bindingContext");
           }

           var prefix = bindingContext.ModelName;
           string jsonString = controllerContext.RequestContext.HttpContext.Request.Params[prefix];
           if (jsonString != null)
           {
               var serializer = new
JavaScriptSerializer();
               var result = serializer.Deserialize(jsonString, bindingContext.ModelType);
               return result;

           }
           else
           {
               return null;
           }


       }
   }



The code is self explanatory and more or less similar to what JsonValueProviderFactory does- get the prefix or parameter name, try to find the request value for that prefix and deserialize the string into an object using JavaScriptSerializer. That’s all you need to do. For complex model binding logic you can use the controllerContext and bindingContext parameters to find out more on the request parameters and model metadata.

Adding JsonBinder class is not just enough. MVC let’s you add a model binder for a specific type. This is usually done in Global.asax.cs file. Let’s register our custom model binder JsonBinder for GuestBook type. My Application_Start() in Global.asax.cs file looks something like this.

protected void Application_Start()
       {
           
AreaRegistration.RegisterAllAreas();

           RegisterGlobalFilters(
GlobalFilters.Filters);
           RegisterRoutes(
RouteTable.Routes);
           
ModelBinders.Binders.Add(typeof(GuestBook),new JsonBinder()); //register
           
       }


You just noticed that I’ve added a new JsonBinder for type GuestBook into Binders collection. When time comes for model binders to bind the parameter in action, MVC checks to see if there’s any custom binder that has been registered for the type of the parameter it’s trying to bind. And in our case we did for GuestBook. Now let’s rebuild and start debugging our application and see if the guest parameter in the Save action has proper values or not. The guest parameter should be properly bound with values supplied from the browser. If not you probably missed something somewhere. Double check your javascript, and Global.asax.cs to see you did exactly what I explained above.
You just learnt one approach of binding your model using custom model binder. But the problem with this approach is that whenever MVC finds any action with a parameter of GuestBook type then it always calls and expects  JsonBinder to bind the model. Let’s assume you are not doing ajax call and simply letting the form to submit. In this case the values being submitted by the browsers are not json string but rather key value pair, which in our case is better handled by DefaultModelBinder. JsonBinder won’t be able to handle this as the request stream is no more a json string. There are few work arounds for this problem. One way is, you can add a constructor in JsonBinder to take the parameter name to bind to and try to deserialize only when the current prefix to bind is equal to the key name with which the binder was registered for a specific type. And if the key and prefix doesn’t match then that means the binding is better handled by DefaultModelBinder. So create an instance of DefaultModelBinder and call the BindModel function by supplying the required parameters and return the returned value.

So instead of registering our model binder globally for specific type let’s do it in a different way. Asp.net MVC 3 also checks to see if the parameter in our Action method has been decorated with an attribute derived from CustomModelBinderAttribute . CustomModelBinderAttribute is an Abstract attribute class which looks something like this.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
   public abstract class
CustomModelBinderAttribute : Attribute
   {
       public abstract IModelBinder GetBinder();
   }



If Mvc finds that the action parameter is decorated with any attribute derived from CustomModelBinderAttribute then it calls the GetBinder function of the attribute, which is supposed to return a custom binder type which implements IModelBinder. Mvc then calls the BindModel function of the binder returned by the Custom Model Binder Attribute.

Rather than trying to explain this theoretically, let’s dive into the code. Now let’s create our JsonModelBinderAttribute which is derived from CustomModelBinderAttribute and return our previous JsonBinder. Our JsonModelBinderAttribute looks something like this.

public class JsonModelBinderAttribute : CustomModelBinderAttribute
   {
       public override
IModelBinder GetBinder()
       {
           return new
JsonBinder();
       }
   }



Now let’s remove the code from Application_Start() function in Global.asax.cs file that we added earlier, i.e

ModelBinders.Binders.Add(typeof(GuestBook),new JsonBinder());
We don’t need this any more.
Now let’s change your action method Save and decorate the guest parameter with JsonModelBinder attribute. Your Save Action method must look something like this.

public JsonResult Save(string key,[JsonModelBinder]GuestBook guest)
       {
           if (guest==null )
           {
               return Json(false);
           }

           return Json(true);

       }



And that’s it. Compile your application. Run in debug mode and check to see if the guest parameter is properly built with proper values. If things are right then your guest object should have all the properties set with proper values sent from browser


Phewwww!!!!!!!!!!!..... I hope that’s enough for this post and really really hope that I got everything right and everything on your side worked perfectly as expected. Please forgive me for not going in depth on everything, which doesn’t seem possible in one blog post.

Please find the final source code here.


Monday, July 16, 2012

Good to know in .net


  1. Char in c# provides some useful static functions to do some common checking functions such as
Console.WriteLine(char.IsUpper('U')); //returns true
      
Console.WriteLine(char.IsNumber('1'));//returns true
      
Console.WriteLine(char.IsDigit('1'));//returns true
      
Console.WriteLine(char.IsLower('u'));//returns true
      
Console.WriteLine(char.IsLetterOrDigit('A'));//returns true
      
Console.WriteLine(char.IsLetterOrDigit('1'));//returns true
      
Console.WriteLine(char.IsWhiteSpace(' '));//returns true

  1. If you have created a function before which takes out and ref parameters then you probably already know this.
    1. Function that takes out parameters needs to assign a value to the parameter before leaving the control. While it is not the case with ref.
    2. When you pass a variable to a function that takes ref parameter you explicitly need to assign a value before passing it to the function. While it is not the case with out.
  2. Enum
    1. By default the underlying storage type for the values in enum are int. You can change this type to any of the type(byte, sbyte, short, ushort, int, uint, long, or ulong). This can be particularly helpful in saving some extra space by deriving from byte instead of int.

public enum MyEnum:byte
   {
       EnumType1=100,
       EnumType2=255 //maximum limit for the byte.
   }

Plus you definitely need to take care of the limit imposed by the type when you are deriving from the type.
  1. To find out the underlying storage type of the enum you can use the Enum.GetUnderlyingType() function.

var ee = MyEnum.EnumType1;Console.WriteLine(Enum.GetUnderlyingType(ee.GetType()));


  1. The number of members that can be declared in an enum type is really dependent on the underlying storage type of the enum. So in above case the MyEnum can have 256 members, but if the underlying type wasn’t changed then it would have been 2^32(the default type is int whose size is 4 byte).

  1. default keyword in c# can be used to return default value of a generic parameter type. Default in a sense, it returns null for reference type and 0 for numeric type. This can be particulary useful when creating a generic function and need to initialize a new variable with the default value of the generic parameter type, coz a generic function may not necessarily know the type of parameter type being passed.
public static T GenericFunction<T>()
       {
           return default(T);
       }


  1. Under the hood c# properties are compiled into hidden methods with get_ and set_ prefixes appended. Your getter property will be appended with get_ and setter property will be appended with set_ prefixes.
  2. Same is the case with events. Events are prefixed with add_ and remove_ prefixes.
  3. Struct cannot inherit. They are always sealed.
  4. Type Conversion:

  • Implicit conversion automatically happens when you try to assign a smaller/derived data type into a larger/base data type which can accommodate without any loss of data.
For e.g
int i=100;
long j=i;//implicit conversion

  • Explicit conversion happens when you cast from one data type to other using cast operators explicitly. When you want to store the larger/base data type to smaller/derived data type you need to explicitly casting.
For e.g
long j=100;
int i=(int)j;

  • Inheritance model of c# automatically allows you to implicitely cast derived class to base class, however you can only explicitely cast base class to derived class using cast operator. But it is converted to derived class only when the base class has been assigned the same derived class previously.
For eg.
public class TCBase
    {
        public string Param1 { get; set; }
       
    }

    public class  
TCDerived:TCBase
    {
        public string Param2 { get; set; }

    }

   public class
TCDerived2 : TCBase
   {
       public string Param2 { get; set; }

   }

//this is valid
           
TCDerived derived=new TCDerived();
           
TCBase base1 = derived;
           
TCDerived derived2 = base1 as TCDerived;
//this is valid but won't cast
           
           
TCBase base2 = new TCBase();
           
TCDerived derived3 = base2 as TCDerived;


  • To be able to cast one type to other you can either provide implicit operator or explicit. If you have provided implicit operator then explicit casting works automatically.
For e.g
public class  TCDerived:TCBase
    {
        public string Param2 { get; set; }

        public static explicit operator
TCDerived(TCDerived2 d2)
        {
            return new
TCDerived() { Param2 = d2.Param2, Param1 = d2.Param1 };
        }
    }

    //this is valid
           
TCDerived2 d2 =new TCDerived2();
           
TCDerived d = d2;

           //this is not valid since we haven't provided implicit or explicit conversion operator
           
TCDerived dd = new TCDerived();
           
TCDerived2 dd2 = dd;



  1. Partial Method.
Partial class has been around since c# 2.0 but partial method has been available from c#3.0. This feature is not something that many know or use quite often. Even microsoft doesn't seem to brag about this feature, that's why many of us are still unaware about it. Let’s check out a small sample.
public partial class PartialMethodClass
   {

       public void Test()
       {
           
Console.WriteLine("from test method");
           PartialMethod();
           //some other stuff
       }

       partial void PartialMethod();

   }

If you compile your assembly without implementing this PartialMethod() then c# compiler completely strips out the call to this method. In above case the the line calling PartialMethod() method in Test() method will be stripped out by the compiler in compiled assembly.
You can implement this method in another part of the partial class as
public partial class PartialMethodClass
   {
       partial void PartialMethod()
       {
           
Console.WriteLine("from partial method");
       }
   }

Some important things to remember about partial method.

  • Partial methods can only be defined within a partial class.
  • Partial methods must return void.
  • Partial methods can be static or instance level.
  • Partial methods can have arguments (including parameters modified by this, ref, or params—but not with the out modifier).
  • Partial methods are always implicitly private.


  1. Anonymous Type.

  • .net compiler always creates anonymous class for anonymous types.
  • When you test the equality of two classes the “==” operator always checks for their references. Similarly the equals method, by default does the same unless you override the method and provide your own logic. However the equals method of anonymous type compares each property rather than their references.
  • If two anonymous types have same class signature .net compiler creates only 1 anonymous class for both of them.
  • You don’t control the name of the anonymous type.
  • Anonymous types always extend System.Object.
  • The fields and properties of an anonymous type are always read-only.
  • Anonymous types cannot support events, custom methods, custom operators, or custom overrides.
  • Anonymous types are always implicitly sealed.
  • Anonymous types are always created using the default constructor


  1. Linq
    1. The Linq methods such as where,skip,select,reverse are all extension methods defined for generic IEnumerable<> type. So all container/collection types derived from this interface automatically gets linq enabled.
    2. Other container types such as ArrayList which derives from non-generic IEnumerable interface doesn’t get linq extension methods. However .net provides another generic extension method called OfType<> defined in Enumerable class for non-generic IEnumerable interface which converts the source to generic IEnumerable<> of type supplied in type parameter. For e.g
ArrayList arlist=new ArrayList();
           //this is not valid.
           //arlist.where();
           //this is valid
           arlist.OfType<string>().Where(m=>m.Equals(
"something"));


  1. A .NET version number is composed of the four parts (<major>.<minor>.<build>.<revision>).
  2. Up to .net 3.5 assemblies in GAC resides under assembly folder of %windir%. From 4.0 assemblies in GAC resides under \Microsoft.NET\assembly\GAC_MSIL of %windir%. Under this new folder, you will find a set of subdirectories, each of which is named identically to the friendly name of a particular code library (for example, System.Windows.Forms, \System.Core, and so on). Beneath a given friendly name folder, you’ll find yet another subdirectory that always takes the following naming convention: v4.0_major.minor.build.revision__publicKeyTokenValue


  1. Probing:
    1. By default when an application loads, the CLR searches for dependent assemblies in the application folder and if not found in case of public/shared assembly, it doesn an extra search in assembly GAC. Probing is a way to tell CLR that the dependent assemblies can be found within the subdirectories of the current directory.
    2. Multiple subdirectories can be assigned by separating the path by colon.
    3. Absolute path cannot be specified.
    4. relative path outside the client’s application directory cannot be specified.
    5. CLR will load the very first assembly it finds during the probing process.
For e.g
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="MyLibrariyFolder"/>
</assemblyBinding>
</runtime>
</configuration>


  1. CodeBase:
<codeBase> is another way of probing dependent assemblies from absolute paths.
If the value assigned to a <codeBase> element is located on a remote machine, the assembly will be downloaded on demand to a specific directory in the GAC termed the download cache
To probe the assemblies without strong name, the dependent assembly needs to be relative to the client’s application directory.

  1. Redirecting shared assembly to different version
One thing to note in .net is, a machine can have the same shared assembly with different versions. So if your application has referenced version 1.0.0.0 of some assembly but if the production environment has higher version of the assembly insted then you will run into problem. Now either you need to change the reference and recompile and re-deploy your application or you can change the binding redirect configuration of your application and direct the CLR to try to load the new version instead.
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="ReferencedLibrary"
publicKeyToken="22ABCD294331EFGHI"
culture=""/>
<bindingRedirect oldVersion= "1.0.0.0" newVersion= "2.0.0.0"/>
</dependentAssembly>

</assemblyBinding>
</runtime>
</configuration>

Now assume you are the developer of “ReferencedLibrary” and after few days of publishing your assembly(version 1.0.0.0) to your clients you discovered few major bugs that need to be fixed but decided to give it a new version number(2.0.0.0). But here is the problem. The server of your client has mulitple applications that reference your library and if you were to follow the above method, the admin might have to open each application’s configuration files and add the above configuration section to redirect the assembly. It’s not something the admin would wanna do. To overcome this issue, you could as a developer of “ReferencedLibrary” create a publisher policy file and supply the publisher assembly along with your new versioned assembly. So when CLR detects the publisher file in GAC it reads the binding redirect configuration and tries to load the new version(2.0.0.0) instead of the older one(1.0.0.0). For more please refer to http://msdn.microsoft.com/en-us/library/dz32563a(v=vs.71).aspx.


  1. Self Executing anonymous function(source: http://blog.dmbcllc.com/self-executing-anonymous-function)
  2. ((Func<int>)(delegate()
    {
       return 0;
    }))();

  3. AppSettingsReader:
This is something I’ve never heard or used it before. AppSettingsReader is a simple yet useful class in System.Configuration that can read the <appSettings> section from application configuration file.
Usage:
AppSettingsReader appSettingsReader=new AppSettingsReader();
      var appkey1Value= appSettingsReader.GetValue(
"appkey1", typeof (string));

If the key is not found it throws InvalidOperationException.



References: