Pages

Thursday, March 29, 2012

Folder structure for a .NET application

I usually stick to the same base folder structure for my .NET applications. This one works well for both my open source projects and enterprise projects at work:



  • Branch name (usually ‘trunk’)

  • This root folder contains the solution file.
    • Application
    All the projects of the application goes here. Each project in it’s own subfolder.
    • Build
    I keep all build related stuff here, like:
    • The signing key for the application
    • A C# project holding the main MSBuild script file and any custom MSBuild tasks
    • Common
    Usually not much here, except always a SolutionInfo.cs file.
    • Documentation
    All developer-related documents of the project are kept here. This way a developer can easily get the latest version of a document without leaving Visual Studio.
    If the project contains auto-generated documentation (for instance using Sandcastle), these generator-projects are kept here as well.
    • Installers
    All installer projects are kept here (Setup projects, WIX projects). Each project in it’s own subfolder.
    • Lib
    This folder contains all the external assemblies used by the project.
    All Visual Studio projects reference the needed dll’s directly from this folder.
    • Tests
    Contains all test projects, usually divided in unit tests, integration tests and test helpers. Each project in it’s own subfolder.

    Note that the above is the physical folder structure. I always make sure that the version control has the excact same folder structure. Never try to build this folder structure from within Visual Studio. Instead build it by hand and add it to source control by hand.

    In the main Visual Studio solution file however, I alter the structure slightly by putting the contents of the Application folder directly in the solution root, and mimic the rest of the folders using solution folders:
    • Solution root
      • All projects of the Application folder
      • Build
      • Common
      • Documentation
      • Installers
      • Lib
      • Tests

    Now, with everything being nicely structured, it’s time to do some coding.

    What is volatile keyword in C#

    volatile

    The keyword volatile means that a field can be modified in the program by thinks along the lines of say the operating system, hardware or even a thread executing concurrently. General syntax of volatile is:


    volatile declaration
    
    where:

    declaration is of a field.

    Key Points:

    Whenever a volatile is requested, the system returns the current value at the time of the request. All assignments are written to the object immediately.

    Common usage of the volatile modifier is when a particular field is accessed by many threads without using the lock statement to serialize access. So in essence the volatile modifier guarantees that a thread will retrieve the most recent value written by another thread (even if it was modified by the previous instruction from you call).

    You are not allowed to use volatile on just any time. The following is a list of types you can implement this modifier on:

    • Any reference type.
    • Any pointer type in a unsafe context
    • sbyte, byte, short, ushort, int, uint, char, float, bool.
    • An enum type with an enum base type of the following: byte, sbyte, short, ushort, int, uint.
    Example:

    public volatile int iAge;

    C# How To Encode or Decode a String to Base64 UTF-8

    This example uses the .NET Framework 4 Encoding Class to Base64 Encode and Decode a supplied sting in your C# Application. The example syntax can be used in any ASP.Net or Win32 program.In addition to the UTF-8 example I've supplied below, the framework also supports methods for encoding/decoding ASCIIEncoding, UnicodeEncoding, UTF32Encoding, UTF7Encoding and UTF8Encoding. 

    Assumptions: Your project contains these 3 controls (Label1, TextBox1, Button1)

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = EncodeTo64UTF8(TextBox1.Text.ToString());
    }

    C# Base64 Encoding Method:
    ///
    /// This method creates a Base64 encoded string from an input
    /// parameter string.
    ///

    /// The String containing the characters
    /// to be encoded.
    /// The Base64 encoded string.

    public static string EncodeTo64UTF8(string m_enc)
    {
        byte[] toEncodeAsBytes =
        System.Text.Encoding.UTF8.GetBytes(m_enc);
        string returnValue =
        System.Convert.ToBase64String(toEncodeAsBytes);
        return returnValue;
    }

    C# Base64 Decoding Method:
    ///
    /// This method will Decode a Base64 string.
    ///

    /// The String containing the characters
    /// to be decoded.
    /// A String containing the results of decoding the
    /// specified sequence of bytes.

    public static string DecodeFrom64(string m_enc)
    {
        byte[] encodedDataAsBytes =
        System.Convert.FromBase64String(m_enc);
        string returnValue =
        System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
        return returnValue;
    }
    Reference: http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx

    Friday, March 23, 2012

    What is New in ASP.NET 4.0, Visual Studio 2010 IDE

    Introduction


    This article is an introduction to some of the new features in ASP.NET 4.0 and Visual Studio 2010 IDE.

    Code Snippets


    Code snippets are pre-developed code templates which can save time spent on thinking about the syntax. There are already a lot of built-in code snippets in VS2005 and VS2008. However, those are only available for the code-behind. Code snippets in VS2010 are introduced for JScript, HTML, and ASP.NET markup as well. In the screenshots below, we can see different snippet context menus for JScript and HTML.
    Inside the script tag, it would be

    And inside the HTML:

    New Profiles


    We have seen different development profiles in previous versions of .NET. Like VB, C#, Web Development, and General Development. We select a profile based on our priorities. These are selected after the first installation of Visual Studio or from the Import Export option.

    In VS2010, two more profiles are introduced and both support HTML developers. Those are:
    1. Web Development
    2. Web Development (Code Optimized)

    The Web Development profile hides the client objects and events bar on top in HTML mode.

    In Code Optimized, you will find the HTML editor without code, and the designer tabs. So, it provides a more bigger area on the screen to play with HTML.

    You can choose a profile after installation of Visual Studio on first use. You can also change the existing working profile from the Tools > Import & Export Settings > Reset all settings option. You will have to open and close Visual Studio if it does not show the changes in the IDE.

    Generate From Usage


    In previous versions of ASP.NET, Microsoft introduced code refactoring to generate methods and identifiers from existing code. In ASP.NET 4.0, there is a new concept of Generate From Usage - generates properties, methods, classes, and other types based on existing code.
    Write some code, select it and right click on the left most character, and you will get options to change it to a property or method etc. This option is shown only if you do not define an identifier. For example, in the following example intellisense, it will not show the options to extract a property if you right click on the variable i.

    Multi-Targeting


    In VS2008, it is possible to create a project in version 2.0 or 3.0, rather than developing in default 3.5. Also, there is an option to change a developed project's target framework version.
    The same option is available in VS2010, but with one improvement. In the previous versions, if you create a project in framework 2.0, intellisense will still show you the types and members of 3.5 version as well, so there are more chances of error if you cannot identify the member of the chosen framework. But in VS2010, the intellisense will show you options for the appropriate framework only.

    Multi-Monitor


    Visual Studio 2010 provides us facility to move windows of the IDE outside of the Visual Studio IDE and place them on the desktop area. It also supports having different IDE windows on multiple monitors. If we close Visual Studio and open it again, we will find all the windows on the same places where we finished them last time.

    Code Navigation in Class Files


    Code Navigation

    A new Navigate To option gives us facility to search a term in a file more quickly. It searches the text as you type, but it works for class files only, i.e., it doesn't work for HTML or code-behind files. In the following example, it shows the function name as I type it in the Navigate To window; on selection of any, it will navigate to the function definition.

    View Call Hierarchy

    This featrure helps to see the use of a function and its properties. For example, if you right click on a function name, it will show you the hierarchical list of function usage.

    If you click View Call Hierarchy, it will show you a window with the details of the function calls:

    On selection of the function call in the hierarchy window, it will show the details of the parameters and the location of the function call.

    Code Identifier Highlighting

    On selection of an identifier, the IDE will highlight the places for you where it is utilized. For example, I selected variable i and it highlights the different places it is used.

    Intellisense Improvements


    In VS2008, on selecting properties for an object, intellisense will show you the properties based on the alphabetical order as you type.
    In VS2010, it shows you the properties based on groups. For example, if you type text for a text box, it will show you the members based on the word text, like Text, TextChanged, TextMode. It also supports Pascal case intellisense. For example, if you type TC, it will navigate to the TextChanged member.

    In the picture below, you can see the ClientIDMode property in version 4, and if we change its target version from project properties, it will not show this attribute for the textbox.

    EnablePersistedSelection


    On selecting a row in controls like DataList or GridView, if we move to another page index, it selects the same numbered row on the newly selected page, although we selected it only on the first page.
    To avoid this, ASP.NET 4.0 has introduced a new property for these controls, called EnablePersistedSelection. If you set it to true, it will not select the same numbered row on other pages, and on navigation to the original page, for example, the first page, it will show the initially selected row as selected.

    Web.Config Transformation


    Normally, we set some values in web.config for the development environment, and then we change those values manually at the time of deployment or testing.
    For example, if we have a connection string or any key value combination in the web.config file, and we want to replace those at the time of project publishing or deployment, then we can use the new web.config transformation. It is an automatic way to perform this operation.
    Web.config settings can be overridden by other config files like web.release.config, web.debug.config etc., at the time of debug, release. These values are not overridden in the original web.config but in the published web.config.
    With the help of transformation, we can replace, remove, or delete a node, and for a node itself, we can remove or set attributes. For example:
    1. Create a config file from Configuration Manager > New:
    2. Name it TransformWebConfig. Select Release from the Copy settings from option:
      This will create TransformWebConfig.config.

    3. Right click on web.config and select the Add config transfroms option. Open the web.config and add a test key and the value to be changed.
      <appSettings> 
        <add key="KeyOne" value="A value"/> 
      </appSettings>
    4. Open TransformWebConfig.config and add the following line to it:
      <appSettings> 
        <add key="KeyOne" 
          value="TestOnConfigurationConfig" 
          xdt:Transform="Replace"
          xdt:Locator="Match(key)" /> 
      </appSettings>
      Set the xdt:Transform attribute to Replace.
    5. Right click on the project and select Create Package. VS will get the values from the TransformWebConfig.config file, and it will change the value in the published web.config file for us.
    On successful build, go to the obj folder and check the web.config file under the TransformWebConfig folder; you will see the value TestOnConfigurationConfig for the key KeyOne.

    URL Routing


    Nowadays, we see that website URLs are more SEO specific and do not show any descriptive information. For example, rather than showing a URL like: http://mywebsite.com/userprofiles.aspx?userid=1, developers would prefer to show the URL as: http://mywebsite.com/mydetails.
    URL mapping in ASP.NET 2.0 provides us an option to achieve this functionality up to some extent. We can mention exact URLs to navigate and URLs to show to the user. But in the case of postback, this option starts showing the actual URL in the browser.
    URL routing was introduced in ASP.NET 3.5. Developers had to create different route handler classes depending on the number of URL routings for a website. The postback issue was solved with this URL routing option.
    In ASP.NET 4.0, you do not need to define separate handler classes for each routing. There is a built-in helper function MapPageRoute which helps you to implement routing more quickly. These routes are registered on Application_Start. For example, in this example, in global.asax, the SetRouting method sets routing, the first parameter is the router's friendly name, the second parameter is to check for the URL pattern to match, and the third is the ASPX page where this functionality would be implemented for the users.
    Global.asax would be:
    protected void Application_Start(object sender, EventArgs e) 
    { 
        SetRouting(System.Web.Routing.RouteTable.Routes); 
    } 
    private void SetRouting(System.Web.Routing.RouteCollection routeCollection) 
    { 
        routeCollection.MapPageRoute("RouteFriendlyName", 
            "MyWebsite/RequestParameterName",
            "~/Book.aspx"); 
        // you can add other page routes with different names and combinations here }
    Now, Book.aspx would use the following code to proceed further:
    string Parameter = Page.RouteData.Values["RequestParameterName"].ToString(); 
    
    if (Parameter=="Chemistry"){....} 
    else if (Parameter=="Physics"){....}
    Now, if we navigate to localhost/MyWebsite/Chemistry, it will go to the first if condition.

    Add Reference Dialog


    In previous versions of Visual Studio, on opening the Add Reference dialog box, it will take some time to load .NET assembly files initially till the time it loads all the references from the GAC. In VS2010, on opening Add Reference, it opens the Projects tab by default.

    If you click on the .NET or COM tab by mistake, you still have an option of canceling it before it loads all the assemblies. So, the VS IDE does not freeze like before.

    Compressing Session Values


    ASP.NET session out-of-process state values are saved in a database or on the server. These are saved in a serialized format. Bigger session values consume more resources to be sent to the server. Now, those can be compressed with a new built-in property compressionEnabled. This attribute for the sessionState element can be mentioned in the web.config, like this:
    <sessionState
      mode="SQLServer" 
      stateConnectionString="connectionstring goes here" 
      compressionEnabled="true"/>
    This option would be available for out-of-process sessions.

    Improvements in C# 4.0


    C# in .NET Framework 4.0 has some more things to offer. These are:
    • Dynamic lookup
    • Named
    • Optional parameters

    Dynamic Lookup

    There is a new static type named dynamic. We can use it as object of any type. If there is any error on its usage, we would get it on runtime only. For example:
    dynamic integerValue = 1; 
    dynamic stringValue = " a string"; 
    dynamic Result = integerValue + stringValue;
    Output of this would be: 1 a string.
    But, if you change the last line to:
    dynamic Result = integerValue & stringValue;
    You will not get any compilation error, but the following error on runtime:
    Operator '&' cannot be applied to operands of type 'int' and 'string'

    Optional Parameters

    To implement optional parameters, we used to create overloaded functions before ASP.NET 4, but now, optional parameters are no more a restriction in C#. Like VB, optional parameters must be mentioned last. For example:
    public void FunctionOptionalParam(string Name, int Age, string Country = "") 
    and we can call them without mentioning the value for the optional parameter.
    FunctionOptionalParam("My Full Name",20);

    Named Parameters

    Named parameters allow you to ignore the parameter order and mention parameters with names in a different order. For example:
    public void FunctionNamedParam(int x, int y , int z)
    On function call, it would be:
    FunctionNamedParam(x:1, z:3, y:2);
    Although we are sending a value for the parameter z before its order in the function declaration, but these would be equal to x=1, y=2, z=3.

    Meta Tags


    The HtmlMeta class can be used to add HTML meta tags dynamically. HTMLMeta's Name, Content properties can be used to add any meta tag name and its values dynamically on runtime.
    In ASP.NET 4.0, the Page class has two more properties: MetaDescription and MetaKeywords. These can be used to add meta values in HTML on runtime for the description and keyword elements. These can be mentioned as page attributes in HTML, or in this way:
    Page.MetaDescription = "this is meta description";
    Page.MetaKeywords = "this is a meta keyword";
    If we see the HTML generated for this, it would be:
    <head>
    <meta name="description" content="this is meta description " />
    <meta name="keywords" content="this is a meta keyword" />
    </head>

    Generating Client IDs


    Client IDs for web controls are generated dynamically based on their parent controls. So if we use a textbox inside a web user control in a WebForm, we have to see what ID is generated for it and use it in the client script accordingly.
    Sometimes, these are dynamic, or in the case of changing the user control name, it changes the ID for the child control as well. In ASP.NET 4.0, this problem is solved by the ClientIDMode attribute for the page. It has the following possible values: AutoID, Static, Predictable, and Inherit.
    • AutoID: It is the default setting for a webpage, and works like in the previous versions of ASP.NET.
    • Static: It sets the static IDs for the web control, so we do not have to worry about the parent control ID and so on if we are referencing it in JavaScript. For example, a TextBox inside a user control and one outside it with ClientIDMode set to Static:
      <asp:TextBox ID="textbox1" 
           runat="server" clientIDMode="Static"></asp:TextBox> 
      
      <uc1:WebUserControl ID="WebUserControl1" runat="server" />
      And this user control is the container for TextBox2:
      <asp:TextBox ID="TextBox2" 
         ClientIDMode="Static" runat="server"></asp:TextBox>
      This code will generate the following HTML:
      <input name="ctl00$MainContent$textbox1" 
        type="text" id="textbox1" /> 
      <input name="ctl00$MainContent$WebUserControl1$TextBox2" 
        type="text" id="TextBox2" />
      If we remove the ClientIDMode set to static, the output would be like this:
      <input name="ctl00$MainContent$textbox1" 
        type="text" id="MainContent_textbox1" />
      It will generate the ID for TextBox as it does in previous versions of ASP.NET.
    • Predictable: If we use Predictable as ClientIDMode for web controls inside a GridView or ListView, then it will concatenate the GridView ID with the control ID and the value of the column mentioned in the ClientIDRowSuffiex attribute:
      Gridview ID ="GridView1"
      ClientIDMode="Predictable"
      ClientIDRowSuffix="ItemID"
      If there is a Label in the GridView template column having the ID Label1 and it is bound with the ItemID column, it will generate an ID, GridView1_Label1_200.
      If we use the ClientIDMode value of Predictable for web controls outside databound controls:
      <asp:TextBox ID="TextBox1" runat="server" 
        ClientIDMode="Predictable"></asp:TextBox>
      
      <asp:Panel ID="panel1" runat="server">
      
      <asp:TextBox ID="TextBox2" runat="server" 
        ClientIDMode="Predictable"></asp:TextBox> 
      
      </asp:Panel>
      You can see the output of the web controls in the panel and outside the panel.
      <input name="ctl00$MainContent$TextBox1" 
        type="text" id="MainContent_TextBox1" />
      
      <div id="MainContent_panel1">
      
      <input name="ctl00$MainContent$TextBox1" 
        type="text" id="MainContent_TextBox1" />
      
      </div>
      It will generate the ID for all the web controls concatenated with the ID of the content panel of the child page.
    • Inherit: Web controls, by default, inherit from the parent container ID. Controls can override this attribute of the parent as well if we set a different value for ClientModeID.

    Permanent Redirect


    In a situation where we want to redirect users to a newly developed page if current page is obsolete, we can use Response.Redirect to shift the page to a new page. But in this case, search engines keep the old information of the page in their indexes for search. Also, if a user navigates to this page, he would be redirected to this page and then to a new page with the help of Response.Redriect.
    But in ASP.NET 4.0, a new command Response.RedirectPermanent can be used to change the header information for the page on the server. So, if a user goes for a page, he is directly redirected to new page and it saves a double trip for him.
    Similarly, search engines, on re-indexing of that website and page, finds the updated header and updates the information in their index and shows the updated information on search.

    New Browser Definitions


    During the last few years of ASP.NET 3.5, a few browsers have been introduced including Google Chrome and those which support Blackberry SmartPhones as well. ASP.NET 4.0's HTTPBrowserCapabilities class is updated with the support for new browsers.

    Publishing a Project


    In VS2010, if you click the Properties link in Solution Explorer, you will find three new tabs:
    1. Package/Publish
    2. Deploy SQL
    3. Silverlight Applications
    I will discuss about the first two options.

    Package/Publish


    Package, Publish options provide you settings for the publish and package commands. The configuration option for Debug, Release provides options to set these values on compilation and build like in previous versions.
    If the hosting server does not have SQL Express, or if you do not want to include those in the published files, then select Exclude files from the App_Data folder. If you select the option Create a web package as a ZIP file, it will create a zip file to be deployed. Otherwise, it would be an unzipped folder by default.
    The default package folder is created under the obj folder of the application. It is not be shown by default in the Solution Explorer until you select the Show all files option. We can also set the web application name on the server and the destination server physical path as well.

    Deploy SQL


    The Deploy SQL option allows you to set the connection string as part of the deployed package. You can add the connection strings manually with different names and values, or import from the web.config by clicking the Import button. You can choose the script for Schema Only or the database option as well. On selection of a connection string, it shows the source settings and we can set the values for the destination server.

    You can also add database script files manually by clicking the Add button. You can also change the order of SQL files to run on server.

    Wednesday, March 21, 2012

    Inversion of Control : A beginner Guide

    What is Problem?
    Let, there is a class called Kids.cs. Purpose of this class is to maintain name and age of kids of a particular person.

    Kids.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class Kids
      {
      private int age;
      private string name;
      public Kids(int age, string name)
      {
      this.age = age;
      this.name = name;
      }
     
      public override string ToString()
      {
      //return base.ToString();
      string m = this.age.ToString();
      return "KIDs Age " + m + " Kids Name " + name;
      }

      }
    }
    Now requirement is like each person has Kids. So at time of creation of a Person, associated Kids should also get created. So this may achieve by following code
    Person.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class Person
      {
      private int age;
      private string name;
      private Kids obj;
      public Person(int personAge,string personName, int kidsAge, string kidsName)
      {
      obj = new Kids(kidsAge, kidsName);
      age = personAge;
      name = personName;
      }
     
      public override string ToString()
      {
      //return base.ToString();
      string s= age.ToString();
      Console.Write(obj);
      return "ParentAge" + s + " ParentName" + name;
      }
      }
    }
    Main.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class Program
      {
      static void Main(string[] args)
      {
      Person p = new Person(35, "Dev", 6, "Len");
      Console.WriteLine(p);
      Console.Read();
      }
      }
    }
    Output


    The above code is a typical example of COMPOSITION design pattern or Object Dependency.
    Note: What is Object Dependency?

    When one objects needs other object for its working then it is called one object is dependent on other object.

    Let there are three classes Man, Woman and Children
    If Man-> Woman
    And Woman -> Children
    So Man -> Children
    This is called Transitive Object Dependency.
    Object Coupling and Object Dependency are same term.
    A Good Design should contain loose object coupling or object dependency.

    Problems in above approach
    1. It is using Part of Relationship. 
    2. Here object of Kids has been created inside constructor of Person class. So here coupling is very high or tight.
    3. If due to any reason object creation of Kids is failed. Then Person class also cannot be instantiated in its constructor itself. 
    4. If object of Person class is killed then by default object of Kids class is also getting killed. 
    5. If a new type of Kids has been created or a new property is being added in Kids class then it need code modification in Person class also. 
    6. This also raises chances of Dangling Reference.
    7. Person class cannot work for Default constructor. 
    8. Kidsâ?T class cannot work for Default constructor.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class Person
      {
      private int age;
      private string name;
      private Kids obj;    (Refrence) 
      public Person(int personAge,string personName, int kidsAge, string kidsName)
      {
      obj = new Kids(kidsAge, kidsName);  (known Concrete class)
      age = personAge;
      name = personName;
      }
     
      public override string ToString()
      {
      //return base.ToString();
      string s= age.ToString();
      Console.Write(obj);
      return "ParentAge" + s + " ParentName" + name;
      }
      }
    }

    How to solve above problem?
    1. Assign task of object creation (Kids class) to some other entity, like other class, another function. 
    2. Assign task of object creation to third party.
    So, assigning task of object creation to Third Party is somehow INVERTING CONTROL to third party. And this is called "INVERSION OF CONTROL"
    In other words IOC could be defined as

    "Delegating task of object creation to third party,  to achieve low coupling between objects and to minimize dependency between objects is called Inversion of Control design pattern ".

    So IOC says,
    1. Main class (Pesron.cs) which is composing other class, should not directly depends on implementation of other class (Kids.cs) . 
    2. There should be an abstraction between classes and classes should fully depend upon that abstraction. 
    3. Abstraction could be either an interface or and abstract class.
    Dependency Injection
    This is the way to implement IOC.  Dependency Injection
    1. Eliminates tight coupling between objects. 
    2. Make object and application more flexible. 
    3. It facilitates creation of more loosely coupled objects and their dependencies.
    "Dependency Injection isolates implementation of object from the construction of object on which it depends".



    Constructor Injection

    Here object reference would get pass to constructor of business class Person.  In this case, since Person class depends on Kids class.  So reference of Kids class will pass to constructor of Person class. So at the time of object creation of Person class, Kids class will get instantiated.
    Steps to implement constructor Injection

    Step 1:  Create an interface

    IBuisnessLogic.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      public interface IBuisnessLogic
      {
     
      }
    }
    1. Only methods of interface will be exposed to business logic class (Person)
    Step 2:  Implement interface to Kids class.

    Kids.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      public class Kids :IBuisnessLogic
      {
      private int age;
      private string name;
      public Kids(int age, string name)
      {
      this.age = age;
      this.name = name;
      }
     
      public override string ToString()
      {
     
      string m = this.age.ToString();
      return "KIDs Age " + m + " Kids Name " + name;
      }
     

      }
    }

    Object of Kids class is going to be referenced by Person class. So this class needs to implement interface.

    Step 3: 

    Make reference of interface in Person class.

    Person.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class Person
      {
      private int age;
      private string name;
      IBuisnessLogic refKids;
      public Person(int personAge,string personName,IBuisnessLogic obj)
      {
     
      age = personAge;
      name = personName;
      refKids = obj;
      }
     
      public override string ToString()
      {
      string s= age.ToString();
     
      return "ParentAge" + s + " ParentName" + name;
      }
      }
    }

    Step 4: 

    Now to create a third party class, where task of, creation of object will be done.

    IOCClass.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class IOCClass
      {
      IBuisnessLogic objKid = null;
      Person p;
     
      public void factoryMethod()
      {
      objKid = new Kids(12,"Ren");
      p= new Person (42,"David",objKid);
      }
      public override string ToString()
      {
      //return base.ToString();
      Console.WriteLine(p);
      Console.WriteLine(objKid);
      return "Displaying using Constructor Injection";

      }
      }
    }

    In above code inside a factorymethod (), object is getting created.

    Step 5
    :

    Now using third party class at client side

    Program.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class Program
      {
      static void Main(string[] args)
      {
     
      IOCClass obj = new IOCClass();
      obj.factoryMethod();
      Console.WriteLine(obj);


      Console.Read();
      }
      }
    }

    Disadvantage

    1. In constructor Injection, business logic class cannot have default constructor.
    2. Once the class is instantiated, objectâ?Ts dependency cannot be changed then.
    Setter Injection
    This uses the Properties to inject the dependency.  Here rather than creating reference and assigning them in constructor, it has been done in Properties.  By this way, Person class could have default constructor also.

    Advantage:
    1. It is more flexible than constructor injection. 
    2. Here dependency of object can be changed without creating any instance. 
    3. Here dependency of objet can be changed without changing the constructors. 
    4. Setters has constructive and self descriptive meaningful name that simplify understanding and usning them .
    Implementation:

    Step 1
    :
    same as Constructor Injection.

    Step 2: Same as Constructor Injection.

    Step 3:  Pesron.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class Person
      {
      private int age;
      private string name;
      //private Kids obj;
      private IBuisnessLogic refKids;
      public Person(int personAge,string personName)
      {
     
      age = personAge;
      name = personName;
     
      }
      public IBuisnessLogic REFKIDS
      {
      set
      {
      refKids = value;

      }
      get
      {
      return refKids;
      }
      }
     
      public override string ToString()
      {
     
      string s= age.ToString();
     
      return "ParentAge" + s + " ParentName" + name;
      }
      }
    }

    In Person class, there is Property REFKIDS, which is setting and getting value of reference of interface.

    Step 4:
    There are some changes in third party class.

    IOC.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace IOC
    {
      class IOCClass
      {
      IBuisnessLogic objKid = null;
      Person p;
     
      public void factoryMethod()
      {
      objKid = new Kids(12,"Ren");
      p= new Person (42,"David");
      p.REFKIDS = objKid;
      }
      public override string ToString()
      {
      //return base.ToString();
      Console.WriteLine(p);
      Console.WriteLine(objKid);
      return "Displaying using Setter Injection";

      }
      }
    }

    Step 5:
    Same as constructor injection.

    This interface would be implemented by Business Logic class.  Here Kids is a business logic class. 

    IoC Pattern

    Introduction:
    IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.
    As a matter of fact every system does not make assumptions about what other systems do or should do, so no side effect when replacing a system by another one.
    Let’s have a first example showing classes having strong dependencies between them. Here we have a main class Singer, which let us know the song style and what formation it is.
    01public class Song
    02{
    03  public string GetStyle()
    04  {
    05      return "Rock n Roll !";
    06  }
    07}
    08 
    09public class LineUp
    10{
    11  public string GetFormation()
    12  {
    13      return "Trio";
    14  }
    15}
    16 
    17public class Singer
    18{
    19  Song song;
    20  LineUp lineUp;
    21 
    22  public Singer()
    23  {
    24      song = new Song();
    25      lineUp = new LineUp();
    26  }
    27 
    28  public string Sing()
    29  {
    30      return "Singer sings " + song.GetStyle() + " and it is a " +  lineUp.GetFormation();
    31  }
    32}
    here’s the Main method :
    1Singer singer = new Singer();
    2Console.WriteLine(singer.Sing());
    As result we have : singer sings Rock n Roll ! and it is a Trio
    But what would we do if we want to hear another song?? Hearing the same one is good but at the end it could break your tears!!
    Implementation of interfaces to replaces instanciate classes (Song, LineUp), and by this way uncoupling main class Singer with the others.
    01public interface ISong
    02{
    03  public string GetStyle();
    04}
    05 
    06public interface ILineUp
    07{
    08  public string GetFormation();
    09}
    10 
    11public class Song : ISong
    12{
    13  public string ISong.GetStyle()
    14  {
    15      return "Hip Hop !";
    16  }
    17}
    18 
    19public class LineUp : ILineUp
    20{
    21  public string ILineUp.GetFormation()
    22  {
    23      return "Solo";
    24  }
    25}
    26 
    27public class Singer
    28{
    29  ISong _isong;
    30  ILineUp _ilineup;
    31 
    32  public string Singer(ISong is, ILineUp il)
    33  {
    34      _isong = is;
    35      _ilineup = il;
    36  }
    37 
    38  public string Sing()
    39  {
    40      return Singer sings " + _isong.GetStyle() + "it is a " +  _ilineup.GetFormation();
    41  }
    42}
    here’s the Main method : Now if we want to here another artist, we just have to
    instanciate so many class that we want
    01//Creating dependencies
    02Song oldsong = new Song();
    03LineUp oldlineUp = new LineUp();
    04//Injection of dependencies
    05Singer singer = new Singer(oldsong,oldlineup);
    06Console.WriteLine(singer.Sing());
    07 
    08//Creating dependencies
    09Song newsong = new Song();
    10LineUp newlineUp = new LineUp();
    11//Injection of dependencies
    12Singer singer = new Singer(newsong,newlineup);
    13Console.WriteLine(singer.Sing());
    Thanks for reading !!

    A basic introduction to the Unity Application Block

    Introduction

    With its latest release, the Enterprise Library from Microsoft introduces a new component named Unity. This application block provides an easy path to implement the IoC pattern, and consequently the Dependency Injection pattern.
    All the references for the Enterprise Library documentation can be found at the end of the article.

    Background

    Inversion of Control and Dependency Injection are the key points to understand how Unity works and the benefits of including it in our projects. If you want a deep dive on these patterns: http://martinfowler.com/articles/injection.html.
    The scope of this article is writing code that is loosely coupled. Let's examine the following DummyLogger class:
    public class DummyLogger
    {
        private IWriter _selectedWriter;
    
        public DummyLogger()
        {
            //The container class is in charge for the initialization of the interface. 
            //the result is a strong dependency between the two objects
            _selectedWriter = new ConsoleWriter();
        }
    
        public void WriteOutput(string msg)
        {
            _selectedWriter.Write(msg);
        }
    }
    The first thing that comes to mind to break the relationship between the two objects is to delegate the creation of the class member to someone else:
    public class DummyLogger
    {
        private IWriter _selectedWriter;
    
        public void SetWriter(IWriter writer)
        {
            _selectedWriter = writer;
        }
    
        public void WriteOutput(string msg)
        {
            _selectedWriter.Write(msg);
        }
    }
    Nothing new until now. This can be interpreted as a trivial implementation of the IoC pattern. The contained object is no more controlled by its container class.
    But what if we don't care about the real implementation of the IWriter interface ? Here's where Unity and Dependency Injection comes. The concrete implementation of the class member will be "injected" by Unity depending on its configuration. The first thing we need to do is expose the class/interface with its get/set methods and mark it with the [Dependency] attribute to make it visible to the application block.
    public class DummyLogger
    {
    
        private IWriter _selectedWriter;
    
        public void SetWriter(IWriter writer)
        {
            _selectedWriter = writer;
        }
    
        public void WriteOutput(string msg)
        {
            _selectedWriter.Write(msg);
        }
    }
    Behind the scenes, each class/interface decorated with the [Dependency] attribute will be created according to the Unity container's configuration. This can be done programmatically or via the .config file.
    <type type="George2giga.TestUnity.Library.IWriter,George2giga.TestUnity.Library" 
       mapTo="George2giga.TestUnity.Library.ConsoleWriter,George2giga.TestUnity.Library" />

    Using the code

    Given below is a basic implementation of Unity. Here's the class diagram of our sample application:

    IWriter, the interface is shared between the logging providers:
    public interface IWriter
    {
        void Write(string msg);
    }
    Of the three logging providers, depending on the configuration, one of them will be "injected" to create the IWriter instance:
    public class ConsoleWriter : IWriter
    {
        #region IWriter Members
    
        public void Write(string msg)
        {
            Console.WriteLine(msg);
            Console.ReadLine();
        }
    
        #endregion
    }
    
    public class FileWriter : IWriter
    {
        #region IWriter Members
    
        public void Write(string msg)
        {
            using (StreamWriter streamWriter = 
                   new StreamWriter("c:\\TestUnity.txt",true))
            {
                streamWriter.WriteLine(msg);
            }
        }
        #endregion
    }
    
    public class EventViewerWriter : IWriter
    {
        #region IWriter Members
    
        public void Write(string msg)
        {
            EventLog.WriteEntry("TestUnity", msg, 
                                EventLogEntryType.Information);
        }
    
        #endregion
    }
    The logging class contains the dependency property:
    public class DummyLogger
    {
        private IWriter selectedWriter;
    
        [Dependency]
        public IWriter SelectedWriter
        {
            get { return selectedWriter; }
            set { selectedWriter = value; }
        }
    
        public void WriteOutput(string msg)
        {
            selectedWriter.Write(msg);
        }
    }
    The entry point of the application is responsible for the initialization of the Unity container:
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            UnityConfigurationSection section = 
              (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Containers.Default.Configure(container);
            DummyLogger dummyLogger = container.Resolve();
            dummyLogger.SelectedWriter.Write("Hello");}
    }
    Here is the App.config:
    xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
          <section name="unity" 
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
                   Microsoft.Practices.Unity.Configuration" />
        </configSections>
        <unity>
          <containers>
            <container>
              <types>
                <type 
                   type="George2giga.TestUnity.Library.IWriter,George2giga.TestUnity.Library" 
                   mapTo="George2giga.TestUnity.Library.ConsoleWriter,
                          George2giga.TestUnity.Library" />
              </types>
            </container>
          </containers>
        </unity>
    </configuration>

    Points of interest

    Design patterns are without doubt a very interesting argument. With Unity, we are able to implement two of them in a very easy way. Dependency Injection allows us to create code that is decoupled, where we can create dependencies without hard-coding anything on our project.

    References