Translate

Wednesday, October 31, 2012

Introduction to AutoFac with a simple example (Autofac Tutorial)


Autofac is an Inversion of Control (IOC) container that was introduced in late 2007. Autofac is meant to deal with Dependency Injection.

In the console application example below, the class BootStrap uses Autofac to decide which implementation of the interface IGetdata to use.

To follow this example you need to add references to the Autofac and Autofac.Configuration dlls, which you can get from http://code.google.com/p/autofac/. I used version 2.6.3.862 for my example.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;
 
namespace AutofacExample
{
 
 
    class Program
    {
        static void Main()
        {           
            using (var container = BootStrap.Components())
            {
                var messenger = container.Resolve<IGetData>();
                messenger.GetMessage();//Displays Hi from XML
                    
            }
        }
    }
 
 
    public interface IGetData
    {
        void GetMessage();
    }
 
 
    public class GetMessageFromDatabase : IGetData
    {
        public void GetMessage()
        {
             
            Console.WriteLine("Hi from database");
        }
    }
 
 
    public class GetMessageFromXML : IGetData
    {
        public void GetMessage()
        {
            Console.WriteLine("Hi from XML");
        }
    }
 
    public class GetMessageFromTextFile : IGetData
    {
        public void GetMessage()
        {
            Console.WriteLine("Hi from Text File");
        }
    }
 
    public class BootStrap
    {
        public static IContainer Components()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<GetMessageFromXML>().As<IGetData>();
 
            return builder.Build();
        } 
 
    } 
 
}


Check this article (Autofac with MVC) out for a little bit more 
advanced example on Autofac

Wednesday, October 24, 2012

C# using tutorial



The keyword using in C# has different meanings based on the context in which you use it.

using directive
When you see this on the top of a C# code page

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

what you are doing is qualifying the namespace.The advantage of doing this is that, instead of typing
 System.Console.WriteLine("Hello, World!");
  you could instead add  using System; on the top of the page and then just type
Console.WriteLine("Hello, World!");


Basically it saves you some typing and your code would be easier to read.
Note: You CANNOT qualify a class this way. This is only meant for qualifying namespaces.


using statement

using (GetDataFromFile GF = new GetDataFromFile())
{
    data = GF.ReadFile();
}

This code is equivalent to 
try
{             
    data= GF.ReadFile();
}
finally
{
    GF.Dispose();
}

When you use a using statement, all you are doing is telling the .net runtime to call the Dispose method after the execution of the code inside the braces. The dispose method gets called even if the code inside the braces throws an error.

Tuesday, October 23, 2012

c# search for file in directory

The code below finds all the text files in the directory and the child directories in which the exe resides.


using System; 
using System.IO;
 
namespace FindFiles
{
   class Program
   {
      static void Main(string[] args)
      {
            
         string path = Directory.GetCurrentDirectory();//path to be searched
         string[] textFiles = Directory.GetFiles(path, "*.txt"SearchOption.AllDirectories);
 
 
         foreach (string file in textFiles)
         {
             Console.WriteLine(file);
 
         } 
 
 
      }
   }
}

Monday, October 22, 2012

Difference between IEnumerable and IEnumerable of T

IEnumerable
IEnumerable<T>
A class should implement this, to be able to use foreach on an instance of that class.
A class should implement this, to be able to use foreach and LINQ on an instance of that class.
Belongs to the System.Collections Namespace.
Belongs to the System.Collections.Generic namespace.



Check this for an example on IEnumerable

Check this for an example on IEnumerable<T>

IEnumerable of T tutorial

Why implement IEnumerable<T>?

If you want to use Linq on an instance of a class, it must implement the interface IEnumerable<T>.


What are the methods that need to be implemented?

 IEnumerable<T>:
 namespace System.Collections.Generic
{

    public interface IEnumerable<T> : IEnumerable    
    {   
        IEnumerator<T> GetEnumerator();
    }
}
Since IEnumerable<T> inherits from IEnumerable, you must implement it too.


 IEnumerable:
namespace System.Collections
{  
    public interface IEnumerable   

   {      
        IEnumerator GetEnumerator();
    }
}


Check this article for an easy introduction to the non generic version IEnumerable.


Implementing the above two interfaces cannot be achieved without implementing these interfaces below


IEnumerator<T>:
namespace System.Collections.Generic
{
    public interface IEnumerator<T> : IDisposableIEnumerator  

    {     
        T Current { get; }
    }
}


IEnumerator:
namespace System.Collections

    public interface IEnumerator   

   {      
        object Current { get; }  
        bool MoveNext(); 
        void Reset();
    }
}


IDisposable:
namespace System

    public interface IDisposable  

   {     
        void Dispose();
    }
}


Okay, now give me an example that shows an IEnumerable<T> implementation

In the example below, the class BookEnumerable implements IEnumerable<T>. Hence you can apply LINQ on an instance of that class.


using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
 
namespace ConsoleApplication4
{
 
    class Program
    {
        static void Main(string[] args)
        {
            BookEnumerable books = new BookEnumerable();
 
            var x = from b in books
                    where b.cost > 10
                    select b;
 
            foreach (var b in x.ToList())
            {
                Console.WriteLine(b.title);
            }
 
        }
    }
 
    public class Book
    {
        public string title;
        public int cost;
    }
 
    class BookEnumerable : IEnumerable<Book>
    {
        IEnumerator<Book> er = new BookEnumerator();
 
 
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
 
        public IEnumerator<Book> GetEnumerator()
        {
            return er;
        }
    }
 
 
    class BookEnumerator : IEnumerator<Book>
    {
 
        Book[] books = Utilities.GetBookArray();
 
        int position = -1;
 
        public Book Current
        {
            get
            {
                return books[position];
            }
        }
 
        object IEnumerator.Current
        {
            get
            {
                return Current;

            }
        }
 
        public bool MoveNext()
        {
 
            position++;
            if (position < books.Length)
            {
                return true;//this means a next item exists
            }
            else
            {
                return false;//this means there are no more items to move further to
            }
        }
 
        public void Reset()
        {
            position = -1;
        }
 
        public void Dispose() { }
 
 
    }
 
    public class Utilities
    {
        public static Book[] GetBookArray()
        {
            Book b1 = new Book();
            b1.title = "Code Complete";
            b1.cost = 28;
 
            Book b2 = new Book();
            b2.title = "The Pragmatic Programmer";
            b2.cost = 33;
 
            return new Book[] { b1, b2 };
 
        }
    }
}

Sunday, October 7, 2012

nhibernate tutorial for beginners with a super simple example ( Nhibernate with Linq )


What is NHibernate?

An ORM tool called Hibernate that has been around since 2001, was immensely popular in the Java world . Since Hibernate was so hugely popular it was decided that .net should have access to this tool too. That's why a .net version of Hibernate called NHibernate was created.

Nhibernate is a set of dlls that serve as your persistence (data access) layer. The way it works  is you create a mapping (using an xml file) between the database tables and classes in your application. Once the mapping is set up, you can just modify an instance of the class and let nhibernate generate the SQL statements for you.

 For example if I create a mapping between a professor class and a professor table, I could do something like

Professor prof1 = new Professor { firstName = "Julia", lastName = "Roberts" };
session.Save(prof1);

to save a new professor to the database. 

Or do this to update an existing record (update last name to Stallone where first name is Sam)
using (ITransaction transaction = session.BeginTransaction())
                {
                    var prof = session.QueryOver<Professor>().Where(x => x.firstName == "Sam").SingleOrDefault();
                    prof.lastName = "Stallone";
                    transaction.Commit();
                }

                    

That simple.


What are the benefits of using NHibernate?

Besides the fact that once you learn nhibernate, you will save a lot of time not having to write all that code for the data access layer, there are other benefits too.

  • NHibernate is a very mature tool. (Hibernate came into existence in 2001)
  • Among other things it takes care of SQL injection and database concurrency for you.
  • If you want to switch from SQL to Oracle, the application code doesn't have to change.(NHibernate supports many database management systems)
  • NHibernate is opensource.


How to use NHibernate?

I will create an application that manipulates a table called professors in a SQL server 2008  database HelloNhibernate.

This is how a select on that table looks like.
























The column professorID is set as an Identity.


 In this example I will use NHibernate to
  • Query the record where first name is Sam   (Read)
  • Update Sam's last name to Stallone            (Update)
  • Add a new professor Julia Roberts             (Create)
  • Delete Steve Balmer                                  (Delete)



To follow the tutorial first download the NHibernate version 3.3.1. Then follow the steps below

1>Create a console application called ConsoleApplication1 and add a reference to these two dlls that you get in the download above
Iesi.Collections
NHibernate

Set the Copy local property for these two dlls to true.


2>Add the class that corresponds to the professors table in the database

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

namespace LearnNHibernate
{
    class Professor
    {
        public virtual int professorID { getset; }
        public virtual string firstName { getset; }
        public virtual string lastName { getset; }

    }


}


3>Add an XML file for mapping called Professor.hbm.xml (the .hbm is what tells the application that this is an nhibernate mapping file). This file maps columns on the table [HelloNhibernate].[dbo].[professors] to the class Professor.


<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="ConsoleApplication1"
                   namespace="LearnNHibernate">

       <class name="Professor" table="professors">
             <id column="professorID" name="professorID" type="int">
                    <generator class="identity"/>
             </id>
             <property column="firstName" name="firstName" />
             <property column="lastName" name="lastName" />
       </class>

</hibernate-mapping>

The property build action of this xml file should be set as Embedded Resource. If you don't do that, no error would be thrown but then no data would be fetched from the database either. 

The assembly and namespace in the <hibernate-mapping> element is the assembly and namespace of the class that is listed in the mapping file.

4>Add an app.config to your application. Just update the connection string in the config below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
       <configSections>
             <section name="hibernate-configuration"
             type="NHibernate.Cfg.ConfigurationSectionHandler,
NHibernate"/>
       </configSections>
       <connectionStrings>
             <add name="db" connectionString="Server=yourServerName;Database=HelloNhibernate; Trusted_Connection=SSPI"/>
       </connectionStrings>
       <hibernate-configuration
       xmlns="urn:nhibernate-configuration-2.2">
             <session-factory>

                    <property name="dialect">
                           NHibernate.Dialect.MsSql2008Dialect,
                           NHibernate
                    </property>
                    <property name="connection.connection_string_name">
                           db
                    </property>

             </session-factory>

       </hibernate-configuration>
</configuration>




5>Copy paste this into your program.cs

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


namespace LearnNHibernate
{
    class Program
    {


        static void Main(string[] args)
        {

            //***** Configure Nhibernate ******************
            var nhConfig = new Configuration().Configure();
            nhConfig.AddAssembly(typeof(Professor).Assembly);
//Name of the assembly that contains the mapping file. If mapping file is in the current assembly , then use   nhConfig.AddAssembly(Assembly.GetExecutingAssembly());

            var sessionFactory = nhConfig.BuildSessionFactory();
            //*********************************************


            //***** Read ******************************

            //Print the last name of the professor named Sam
            using (ISession session = sessionFactory.OpenSession())
            {
                var prof = session.QueryOver<Professor>().Where(x => x.firstName == "Sam").SingleOrDefault();
                Console.WriteLine(prof.lastName);

            }
            //*********************************************

            //***** Update ******************************

            //Update Sam's last name to Stallone
            using (ISession session = sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    var prof = session.QueryOver<Professor>().Where(x => x.firstName == "Sam").SingleOrDefault();
                    prof.lastName = "Stallone";
                    transaction.Commit();
                }

            }
            //*********************************************


            //***** Add ******************************

            //Insert a professor named Julia Roberts
            Professor prof1 = new Professor { firstName = "Julia", lastName = "Roberts" };

            using (ISession session = sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(prof1);
                    transaction.Commit();
                }

            }
            Console.ReadKey();

            //*********************************************


            //***** Delete ******************************

            //Delete the professor named Steve
            using (ISession session = sessionFactory.OpenSession())
            {
                var delProf = session.QueryOver<Professor>().Where(x => x.firstName == "Steve").SingleOrDefault();
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(delProf);
                    transaction.Commit();
                }

            }

        }



    }
}


At this point this is how the app looks like in my Visual studio.




















Now you can go ahead and run the app.

 This is how a select on that table looks like after you have run this app




















Some helpful resources

NHibernate Mapping Generator