Saturday, November 1, 2014

nHibernate, SQL Server and WCF

Hi Guys,

This time I made a small program to illustrate the power and maturity of nHibernate ORM and integration of WCF with it. Hope you like it.


Solution


1) Create a Solution like following 






















2) Download the nHibernate from http://nhforge.org/ and add it to your solution

3) Create Domain -> EP_TimeLog.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateDL.Domain
{
    /// <summary>
    /// Time Log Class 
    /// </summary>
    [Serializable]    
    [DataContract]
    public class EP_TimeLog
    {
        [DataMember]
        public virtual long Id { get; set; }
        [DataMember]
        public virtual string Name { get; set; }
        [DataMember]
        public virtual string Description { get; set; }
        [DataMember]
        public virtual DateTime StartTime { get; set; }
        [DataMember]
        public virtual DateTime EndTime { get; set; }
        [DataMember]
        public virtual decimal Duration { get; set; }
        [DataMember]
        public virtual string CreatedBy { get; set; }
        [DataMember]
        public virtual DateTime CreatedOn { get; set; }
        [DataMember]
        public virtual string EditedBy { get; set; }
        [DataMember]
        public virtual DateTime? EditedOn { get; set; }
        [DataMember]
        public virtual byte[] RowVer { get; set; }
    }
}

4) Create nHibernateDL -> Domain -> EP_TimeLogRepository.cs and paste the following code

using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateDL.Domain
{
    /// <summary>
    /// Interface for Repository
    /// </summary>
    public interface IEP_TimeLogRepository
    {
        EP_TimeLog GetById(long id);
        bool Add(EP_TimeLog log);
        bool Update(EP_TimeLog log);
    }

    /// <summary>
    /// Class for the Repository
    /// </summary>
    public class EP_TimeLogRepository : IEP_TimeLogRepository
    {
        /// <summary>
        /// Method to get data by ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public EP_TimeLog GetById(long id)
        {
            using (ISession session = nHibernateHelper.OpenSession())
            {
                var timeLog = session.Get<EP_TimeLog>(id);
                return timeLog;
            }
        }

        /// <summary>
        /// Method to Add new entity
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public bool Add(EP_TimeLog log)
        {
            bool isSaved = false;
            using (ISession session = nHibernateHelper.OpenSession())
            {
                
                    session.Save(log);                    
                    isSaved = true;           
                
            }

            return isSaved;
        }

        /// <summary>
        /// Method to update entity
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public bool Update(EP_TimeLog log)
        {
            bool isSaved = false;
            using (ISession session = nHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(log);
                    transaction.Commit();
                    isSaved = true;
                }

            }

            return isSaved;
        }
    }

}

5) Create nHibernateDL-> Mappings -> EP_TimeLog.hbm.xml and paste the following xml

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

  <class name="EP_TimeLog">
    <id name="Id" type="long">
      <generator class="identity"/>
    </id>
    
    <property name="Name" />
    <property name="Description" />
    <property name="StartTime" />
    <property name="EndTime" />
    <property name="Duration" />
   
    <property name="CreatedOn" />
    <property name="CreatedBy" />
    <property name="EditedBy" />
    <property name="EditedOn" />
   
  </class>

</hibernate-mapping>

6) Create nHibernateDL-> hibernate.cfg.xml and paste the following xml

<?xml version="1.0" encoding="utf-8" ?>


<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=KPICatalog;Integrated Security=true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    
   
  </session-factory>
</hibernate-configuration>

7) Create nHibernateDL-> nHibernateHelper.cs and paste the following code

using NHibernate;
using NHibernate.Cfg;
using nHibernateDL.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateDL
{
    /// <summary>
    /// Helper Class to Create an nHibernate Session
    /// </summary>
    public class nHibernateHelper
    {
        private static ISessionFactory _sessionFactory;
 
        private static ISessionFactory SessionFactory
        {
            get
            {
                if(_sessionFactory == null)
                {
                    var configuration = new Configuration();
                    configuration.Configure();
                    configuration.AddAssembly(typeof(EP_TimeLog).Assembly);
                    _sessionFactory = configuration.BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }
 
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    
    }
}

8) Create nHibernateWcfServiceLibrary -> HibernateService.cs and paste the following code

using nHibernateDL.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using nHibernateDL;

namespace nHibernateWcfServiceLibrary
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    public class HibernateService : IHibernateService
    {
        /// <summary>
        /// Get Data Method
        /// </summary>
        /// <param name="value">Id of the Log</param>
        /// <returns>Return Message of Time Log</returns>
        public ReturnMsg<EP_TimeLog> GetData(long value)
        {
            ReturnMsg<EP_TimeLog> objReturn = new ReturnMsg<EP_TimeLog>();

            try
            {
                nHibernateHelper.OpenSession();
                IEP_TimeLogRepository repo = new EP_TimeLogRepository();

                objReturn.Data = repo.GetById(value);

                objReturn.Status = Status.Success;  
            }
            catch (Exception ex)
            {
                objReturn.Message = ex.Message + Environment.NewLine + ex.StackTrace;
                objReturn.Status = Status.Failed;               
            }

            return objReturn;
        }

        /// <summary>
        /// Save Method
        /// </summary>
        /// <param name="log">Log to Save</param>
        /// <returns>Return whether saved</returns>
        public ReturnMsg<bool> Save(EP_TimeLog log)
        {
            ReturnMsg<bool> objReturn = new ReturnMsg<bool>();

            try
            {
                nHibernateHelper.OpenSession();
                IEP_TimeLogRepository repo = new EP_TimeLogRepository();

                if (log.Id > 0)
                {
                    objReturn.Data = repo.Update(log);
                }
                else
                {
                    objReturn.Data = repo.Add(log);
                }               

                objReturn.Status = Status.Success;
            }
            catch (Exception ex)
            {
                objReturn.Message = ex.Message + Environment.NewLine + ex.StackTrace;
                objReturn.Status = Status.Failed;
            }

            return objReturn;
        }

        
    }
}

9) Create nHibernateWcfServiceLibrary -> IHibernateService.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using nHibernateDL.Domain;

namespace nHibernateWcfServiceLibrary
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IHibernateService
    {
        [OperationContract]
        ReturnMsg<EP_TimeLog> GetData(long value);   
     
        [OperationContract]
        ReturnMsg<bool> Save(EP_TimeLog log); 
    }

   
}

10) Create ReturnMsg.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateWcfServiceLibrary
{
    public enum Status : byte
    {
        Success = 1,
        Failed = 2
    }

    [DataContract]
    public class ReturnMsg<T>
    {
        [DataMember]
        public T Data { get; set; }
        [DataMember]
        public string Message { get; set; }
        [DataMember]
        public Status Status { get; set; }
    }
}

11) Add the nHibernateWcfServiceLibrary as a Service reference to the nHibernateTest

12) Open nHibernateTest -> Program.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using nHibernateTest.HibernateService;

namespace nHibernateTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (HibernateServiceClient objService = new HibernateServiceClient())
            {

                EP_TimeLog objToAdd = new EP_TimeLog()
                {
                    Name = "Test Task through WCF",
                    Description = "Test Task through WCF",
                    StartTime = DateTime.Parse("11/01/2014 16:00"),
                    EndTime = DateTime.Parse("11/01/2014 16:30"),
                    Duration = 30,
                    CreatedBy = "sshahim",
                    CreatedOn = DateTime.Now,
                    EditedBy = "sshahim",
                    EditedOn = DateTime.Now
                };

                ReturnMsgOfboolean objSaveReturn = objService.Save(objToAdd);

                if (objSaveReturn.Status == Status.Success && objSaveReturn.Data)
                    Console.WriteLine("Data Saved Successfully!");
                
                ReturnMsgOfEP_TimeLog6f00b6nb objReturnMsg = objService.GetData(15);
                if (objReturnMsg.Status == HibernateService.Status.Success)
                {
                    EP_TimeLog objToUpdate = objReturnMsg.Data as EP_TimeLog;

                    Console.Write(string.Format("Id : {0}\nName : {1}\n", objToUpdate.Id, objToUpdate.Name));

                    objToUpdate.Name = objToUpdate.Name + " Modified";

                    ReturnMsgOfboolean objUpdateReturn = objService.Save(objToUpdate);

                    if (objUpdateReturn.Status == Status.Success && objUpdateReturn.Data)
                    Console.WriteLine("Data Modified Successfully!");

                }
            }

            Console.Read();
        }
    }
}

Before Adding New Record












After adding New Record














After Modifying