Monday, 26 August 2013

Working with Active Directory

Introduction


This sample will help in connecting to the Active Directory, Authentication the user on the defined Active Directory and get all the users present in the defined groups in Active Directory. This code contains plug and play classes which can be directly placed into an application and can be used. On can also customize them according to the needs.

Working and the Sample Description


This sample to be working you need .Net Framework 4.0. It contains one class library project and one Web site to show the demonstration.Class Library project contains one class named "LDAP.cs", this is the class which is actually interacting with the Active Directory. This project needs a reference of "System.DirectoryServices", so if one wants to interact with Active Directory then the library which will be interacting with Active Directory should have reference to this .Net DLL(s). "LDAP.cs" contains two public methods, one of which authenticates the user and other one helps in retrieving all the users from the Directory. Other class which is present in this library project is the "User.cs" this is the custom class created so as to get the user details from the Active Directory then fill in the details into this class, so as to keep the solution generic as every application has one User Entity of its own.Website contains a sample page and one class which is interacting with the class library.Sample page will demonstrate the Authentication logic along with the logic of getting users from the Active Directory in a particular group. Last is the application settings key added into "Web.config".First one is "ActiveDirectoryPath"  - This will contain the path to your Active DirectorySecond is "DomainName" - This is the domain on which your Active Directory is present.Third and the last is the "ActiveDirectoryGroups" - This will contain all the groups for which you want to retrieve users from Active Directory. If you have multiple groups then you can give the Group name(s) as pipe("|") separated.

<appSettings> 
    <!--Active Directory Path  --> 
    <add key="ActiveDirectoryPath" value=""/> 
    <!--Domain Name  --> 
    <add key="DomainName" value=""/> 
    <!--User Groups for which search needs to be performed, User groups are Pipe Separated. example: "Admin|Guest" --> 
    <add key="ActiveDirectoryGroups" value=""/> 
</appSettings>

For Downloading the code, please refer the following URL: Source Code

I welcome some valuable feedback.
So to get it working you just need to make changes in Web.Config and the sample will be running....

Wednesday, 21 August 2013

Factory Pattern vs Factory Method Pattern vs Abstract Factory Pattern

Factory Pattern

Suppose we have two classes ClassA and ClassB

Now i am having a Third Class or suppose a Web Page where i need to create objects of both of these class(ClassA & ClassB). So what we can do here simply is:

ClassA a = new ClassA();
ClassB b = new ClassB();

But it is not a good way as the Client or the consumer is directly having permission to create an object or the you can say Client or Consumer should not be responsible for creating the objects. This is because if something changes in the way of initialization (Creation of objects) then we need to change everywhere in the consumer files wherever we are initializing these classes. So best way, is to give out the responsibility of creation of objects to a new class. This is known as Factory Pattern. So whenever there is a change in the process of initialization we need to makes changes only in factory Pattern.

So, for this we can create a Factory Class which will have the responsibility of creating Objects. It can be either parameterised (Open-Close Principle is not followed) or can be based on reflection.

Parameterised Factory:

    public class SampleClass
    {
    }

    public class ClassA : SampleClass
    {

    }

    public class ClassB : SampleClass
    {

    }

    public class Factory
    {
        public SampleClass Create(int classType)
        {
            SampleClass classObject = new SampleClass();
            if (classType == 1)
            {
                classObject = new ClassA();
            }
            if (classType == 2)
            {
                classObject = new ClassB();
            }
            //So On for every Class
            return classObject;
        }
    }

So now for creating object code will be something like this:

SampleClass a = new Factory().Create(1);
SampleClass b = new Factory().Create(2);

But this breaks open close principle, so we can do it by reflection

Using Reflection:

    public class SampleClass
    {
    }

    public class ClassA : SampleClass
    {

    }

    public class ClassB : SampleClass
    {

    }

    public class Factory
    {
        public SampleClass Create(string className)
        {
            SampleClass instance = new SampleClass();
            var requiredClass = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                 from type in assembly.GetTypes()
                                 where string.Equals(type.Name, className, StringComparison.OrdinalIgnoreCase)
                                 select type).FirstOrDefault();

            if (requiredClass != null)
            {
                instance = (SampleClass)Activator.CreateInstance(requiredClass);
            }

            return instance;
        }
    }

So now for creating object code will be something like this:

SampleClass a = new Factory().Create(“ClassA”);
SampleClass b = new Factory().Create(“ClassB”);

Now we don’t need to change Factory class, but right now we are having type of classes “SampleClass” that is our both the classes are inherited by this “SampleClass”, what if a new base class comes into picture, then we need to have multiple factories and which is fine (But then the consumer should know that which factory needs to be referred to get the objects of that type and also each factory can have different methods which actually create the object and returns them, example: Right now Factory class which we created above is having a method “Create” but in future someone can create a new Factory say “FactoryNew” to get the objects of some other type and the method which will be creating and returning the object can be named as “CreateNew”). So here comes the Factory Method and Abstract factory pattern into the picture.

Factory Method

It’s the way of imposing that every Factory should have a method “Create” which should return the desired object(Sub classes that are original factories can decide which type of object needs to be returned)
It helps the consumer to directly call a method “Create” to get the object irrespective of which factory going to be used.

Here goes the code:

    public class SampleClass
    {
    }

    public class SampleClassA : SampleClass
    {
    }

    public class SampleClassB : SampleClass
    {
    }

    public class ClassA : SampleClassA
    {

    }

    public class ClassB : SampleClassA
    {

    }

    public class ClassC : SampleClassB
    {

    }

    public class ClassD : SampleClassB
    {

    }

    public abstract class Factory
    {
        public SampleClass GetObject(string className)
        {
            return CreateObject(className);

        }

        //Acting as a Factory Method
        protected abstract SampleClass CreateObject(string className);
    }

    public class FactoryA : Factory
    {
        protected SampleClass CreateObject(string className)
        {
            SampleClass instance = new SampleClassA();
            var requiredClass = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                 from type in assembly.GetTypes()
                                 where string.Equals(type.Name, className, StringComparison.OrdinalIgnoreCase)
                                 select type).FirstOrDefault();

            if (requiredClass != null)
            {
                instance = (SampleClassA)Activator.CreateInstance(requiredClass);
            }

            return instance;
        }
    }

    public class FactoryB : Factory
    {
        protected SampleClass CreateObject(string className)
        {
            SampleClass instance = new SampleClassB();
            var requiredClass = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                 from type in assembly.GetTypes()
                                 where string.Equals(type.Name, className, StringComparison.OrdinalIgnoreCase)
                                 select type).FirstOrDefault();

            if (requiredClass != null)
            {
                instance = (SampleClassB)Activator.CreateInstance(requiredClass);
            }

            return instance;
        }
    }

So now for creating object code will be something like this:

SampleClass a = new FactoryA().GetObject(“ClassA”);
SampleClass b = new FactoryA().GetObject(“ClassB”);
SampleClass c = new FactoryB().GetObject(“ClassC”);
SampleClass d = new FactoryB().GetObject(“ClassD”);

So what’s the problem now which still persists, any guesses?????

As of now everything is perfect just one problem is remaining and that is client or the consumer has to create the objects of factory (knowing that which factory will return which type of object). This problem can be eliminated by adding one more level of abstraction on Factories (i.e. Factory for numerous factories). It that case consumer don’t have to create the object of factory themselves they will just provide which object they need and based on that it’s the task of the parent factory to decide which factory needs to be initiated to create that kind of object). So here comes the Abstract Factory into picture.

Abstract Factory:
I don’t think I need to explain what Abstract Factory pattern is and why we need it. But anyways, Abstract Factory is used to provide one more level of modularization by which consumer don’t have to worry to create an instance of the Factory also, the responsibility goes inside the Parent Factory

Here goes the Code:

    public class SampleClass
    {
    }

    public class SampleClassA : SampleClass
    {
    }

    public class SampleClassB : SampleClass
    {
    }

    public class ClassA : SampleClassA
    {

    }

    public class ClassB : SampleClassA
    {

    }

    public class ClassC : SampleClassB
    {

    }

    public class ClassD : SampleClassB
    {

    }

    public class Factory
    {
        public SampleClass GetObject(string className)
        {
            SampleClass instance = new SampleClass();

            //Here we can have Enums or XML as Depedency Injection Container have XML to get which factory needs to be initiated for which class
            //So we can read that value and use reflection code to initiate that Factory and call its method "CreateObject" here goes the code for that

            //Suppose we get the name of the factory class from XML and put it ninto the string, consider we get "FactoryA" in this example
            string factoryName = "FactoryA";

            var requiredFactory = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                   from type in assembly.GetTypes()
                                   where string.Equals(type.Name, factoryName, StringComparison.OrdinalIgnoreCase)
                                   select type).FirstOrDefault();

            if (requiredFactory != null)
            {
                object factoryInstance = Activator.CreateInstance(requiredFactory);
                // Get the operation's method, invoke it, and get the return value, Factory knows method name is CreateObject
                var methodInfo = factoryInstance.GetType().GetMethod("CreateObject");

                object[] operationParameters = new object[] { className };
                instance = (SampleClass)methodInfo.Invoke(factoryInstance, System.Reflection.BindingFlags.InvokeMethod, null, operationParameters, null);
            }

            return instance;
        }
    }

    public interface IFactory
    {
        SampleClass CreateObject(string className);
    }

    public class FactoryA : IFactory
    {
        public SampleClass CreateObject(string className)
        {
            SampleClass instance = new SampleClassA();
            var requiredClass = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                 from type in assembly.GetTypes()
                                 where string.Equals(type.Name, className, StringComparison.OrdinalIgnoreCase)
                                 select type).FirstOrDefault();

            if (requiredClass != null)
            {
                instance = (SampleClassA)Activator.CreateInstance(requiredClass);
            }

            return instance;
        }
    }

    public class FactoryB : IFactory
    {
        public SampleClass CreateObject(string className)
        {
            SampleClass instance = new SampleClassB();
            var requiredClass = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                 from type in assembly.GetTypes()
                                 where string.Equals(type.Name, className, StringComparison.OrdinalIgnoreCase)
                                 select type).FirstOrDefault();

            if (requiredClass != null)
            {
                instance = (SampleClassB)Activator.CreateInstance(requiredClass);
            }

            return instance;
        }
    }

So now for creating object code will be something like this:

SampleClass a = new Factory().GetObject(“ClassA”);
SampleClass b = new Factory().GetObject(“ClassB”);
SampleClass c = new Factory().GetObject(“ClassC”);
SampleClass d = new Factory().GetObject(“ClassD”);

Note: Abstract Factory is normally not required in small applications.


I hope it helps you in distinguishing now what is the difference between Factor Pattern, Factory Method Pattern and Abstract Factory.
Realizing Continuous Integration with Cruise Control.Net (CC.Net)

Cruise Control:

Cruise Control is free and open source build scheduler which is implemented using the .Net Framework. It composes of two components:
  1. Build Loop - The build loop is designed to run as a background process, which periodically checks the defined repository for changes in codebase, builds it and give the status as the final output.
  2. Reporting – Cruise Control provides a reporting application to browse the results of the builds along with this it also provides a dashboard for visual representations of the status.

As mentioned in by last post Cruise Control works with many source control systems (Some of the better know are TFS, SVN, and VSS etc…). Input for the build process is any parseable format so it can be integrated with any build tool (MSBuild, Nant, Maven etc…) which produces parseable format. In addition to that this is widely used because of its extensive documentation and also provides with the option of Mailing list.

Process of Cruise Control:

  •        Developer Checks-in the code
  •        Cruise Controls polls the Version control system (Repository) to see if there are any changes in  codebase
  •        If the changes are there, then Cruise Control triggers the build using the defined build tool, captures  the build data and produces the Build Status Report

CCTray

It is a standalone application which enables the developers or any other team member to check the status of the builds on their local machines which can access the CC.Net Server.



High Level Architecture of CC.Net


Setup Cruise Control.Net

First of all download CC.Net EXE (CruiseControl.NET-1.8.3.0-Setup.exe) from http://sourceforge.net/projects/ccnet/
Run that EXE as Administrator. While installing select all the three components


After the installation is complete, you can now access the dashboard by typing in the following URL:
At the physical path of installation you will see that there are three folders which have got created named:
  1.       webdashboard
  2.       Examples
  3.       server

In the “server” folder there is a file named “ccnet.config”. Open up this file to do the configuration for automated builds. We need to add four blocks named

  1. Project Configuration Block – Information about the Project that needs to be build, there can be multiple projects present in this config
  2. SourceControl block – From where the code needs to be checked out for the build
  3. Tasks block – Steps/Process of Build
  4. Publishers block – Generate output and produce reports(If needed dispatch emails also)

For adding these you can either refer to the links above or I am providing you with the sample config below:

<cruisecontrol xmlns:cb="urn:ccnet.config.builder">
  <!-- This is your CruiseControl.NET Server Configuration file. Add your projects below! -->

  <project name="Sample Application">
    <webURL>http://localhost:8080/ccnet/server/local/project/SampleApplication/ViewLatestBuildReport.aspx</webURL>
    <!--set the sourcecontrol type to subversion and point to the subversion exe-->
    <sourcecontrol type="svn">
      <executable>C:\Program Files\TortoiseSVN\bin\svn.exe</executable>
      <workingDirectory><PATHOFYOURAPPLICATION>\SampleApplication</workingDirectory>
      <trunkUrl><REPOSITORYPATH/URL>/SampleApplication</trunkUrl>
      <autoGetSource>true</autoGetSource>
      <username>XXXX</username>
      <password>XXXX</password>
    </sourcecontrol>
    <triggers>
      <intervalTrigger name="Cruise Control Continuous Integration" seconds="60" buildCondition="IfModificationExists" initialSeconds="30" />
    </triggers>
    <tasks>
      <!-- Configure MSBuild to compile the updated files -->c:\
      <msbuild>
        <executable>c:\windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe</executable>
        <workingDirectory><PATHOFYOURAPPLICATION>\SampleApplication\</workingDirectory>
        <projectFile>SampleApplication.sln</projectFile>
        <buildArgs>/noconsolelogger /p:Configuration=Debug /nologo</buildArgs>
        <targets></targets>
        <timeout>60</timeout>
        <logger>C:\Program Files (x86)\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>
      </msbuild>
      <exec>
        <executable>del.bat</executable>
        <buildArgs></buildArgs>
        <buildTimeoutSeconds>30</buildTimeoutSeconds>
      </exec>

      <exec>
        <!--Call mstest to run the tests contained in the TestProject -->
        <executable>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe</executable>
        <baseDirectory><PATHOFYOURAPPLICATION>\\SampleApplication\Web\bin\debug</baseDirectory>
        <!--testcontainer: points to the DLL that contains the tests -->
        <!--runconfig: points to solutions testrunconfig that is created by vs.net, list what test to run -->
        <!--resultsfile: normally the test run log is written to the uniquely named testresults directory  -->
        <!--                   this option causes a fixed name copy of the file to be written as well -->
        <buildArgs>

        </buildArgs>
        <buildTimeoutSeconds>60</buildTimeoutSeconds>
      </exec>
    </tasks>
    <!--Publishers will be done after the build has completed-->
    <publishers>
      <buildpublisher>
        <sourceDir><PATHOFYOURAPPLICATION>\\SampleApplication\Web\</sourceDir>
        <publishDir><PATHOFYOURAPPLICATION>\\Sample Application 9091</publishDir>
        <useLabelSubDirectory>false</useLabelSubDirectory>
        <alwaysPublish>false</alwaysPublish>
      </buildpublisher>
      <merge>
        <files>
          <file action="Merge" deleteAfterMerge="true">msbuild-results.xml</file>
          <file action="Merge" deleteAfterMerge="true"><PATHOFYOURAPPLICATION>\\SampleApplication\Web\bin\Debug\testResults.trx</file>
        </files>
      </merge>
      <xmllogger/>
      <email from="XXXX@XXXX.com" mailhost="smtp.XXXX.com" mailport="25" useSSL="FALSE" mailhostUsername=" XXXX@XXXX.com" includeDetails="TRUE" mailhostPassword="XXXX" >
        <users>
          <user name="Abhishek" group="buildmaster" address=" XXXX@XXXX.com" />
          <user name="Devs" group="developers" address=" XXXX@XXXX.com" />
        </users>
        <groups>
          <group name="developers">
            <notifications>
              <notificationType>Failed</notificationType>
            </notifications>
          </group>
          <group name="buildmaster">
            <notifications>
              <notificationType>Always</notificationType>
            </notifications>
          </group>
        </groups>
      </email>
    </publishers>
    <modificationDelaySeconds>0</modificationDelaySeconds>
  </project>

</cruisecontrol>


Once we are done with the configurations we need to start the CruiseControl.Net Server. For starting the server open Services.msc -> CruiseControl.Net Server. Start this service.


As soon as you are done with that you are ready with your entire configuration to produce automated builds. Access the URL: http://localhost:8080/ViewFarmReport.aspx  and you will see a Project which you configured on this dashboard.



From here you can force build and can also check the status of various builds along with the exception details or the error details if any.


As I mentioned earlier you can also download CCTray from this page by clicking on the link “Download CCTray”. It will help one to see when the error occurred and by looking into it one gets immediately notified for the error in the check-in and can resolve it on the fly.