Ehsan Ghanbari

Experience, DotNet, Solutions

Fluent Nhibernate Sample Project in Asp.net MVC

NHibernate is an ORM designed for Microsoft.Net, it's free and open source and it's a port of Java mapper to Dot Net. And fluent NHibernate is a separate version of NHibernate which lets you write your entities according to your business instead of starting from creating tables, Fluent NHibernate is just a fluent API for mapping classes with NHibernate. what an ORM does, is persisting object In database and then retrieving when it is needed, indeed it translates the object to the database and vice versa.

In Entity Framework, you use DbContext or objectContext(in earlier versions) to make configuration, in this case, Models or properties acts as a UnitOfWork pattern but In NHibernate by Using ISessionFactory Models are keep in a separate in-memory database. I'm going to show a simple NHibernate configuration in this article, Now let's start!

create a new MVC4 project and get the latest version of Fluent NHibernate by Nuget:

NH

Or you can go to the website and get the latest version and reference the Fluent NHibernate, now create a new class named Product : 

 

    public class Product
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual Category Category { get; set; }
    }

 

 and then add the Category Class to your Model folder in your project :

 

    public class Category
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
    }

 

you should define the properties as virtual because of lazy loading(retrieving an object or so-called data from the database when it's needed is lazy loading) , now create two separate class for mapping this Model classes via Fluent NHibernate :

 

    public sealed class ProductMapping : ClassMap<Product>
    {
        public ProductMapping()
        {
            LazyLoad();
            Table("Product");
            Id(p => p.Id);
            Id(p => p.Id).GeneratedBy.Identity();
            Map(p => p.Name);
            References(p => p.Category);
        }
    }

    public sealed class CategoryMapping : ClassMap<Category>
    {
        public CategoryMapping()
        {
            LazyLoad();
            Table("Category");
            Id(c => c.Id);
            Id(c => c.Id).GeneratedBy.Identity();
            Map(c => c.Name);
        }
     }

 

Now the most important and goal of this article is about configuration class of Fluent NHibernate, create the class with this definition

 

    public class SessionFactory : IHttpModule
    {
        private static readonly ISessionFactory _SessionFactory;
        static SessionFactory()
        {
            _SessionFactory = CreateSessionFactory();
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequest;
            context.EndRequest += EndRequest;
        }

        public void Dispose()
        {
        }

        public static ISession GetCurrentSession()
        {
            return _SessionFactory.GetCurrentSession();
        }

        private static void BeginRequest(object sender, EventArgs e)
        {
            ISession session = _SessionFactory.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);
        }

        private static void EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(_SessionFactory);
            if (session == null) return;
            try
            {
                session.Transaction.Commit();
            }
            catch (Exception)
            {
                session.Transaction.Rollback();
            }
            finally
            {
                session.Close();
                session.Dispose();
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c =>    c.FromConnectionStringWithKey("DefaultConnection")))
                           .Mappings(m => m.AutoMappings.Add(CreateMappings()))
                           .CurrentSessionContext<WebSessionContext>()
                           .BuildSessionFactory();
        }

        private static AutoPersistenceModel CreateMappings()
        {
            return AutoMap
                .Assembly(System.Reflection.Assembly.GetCallingAssembly())
                .Where(t => t.Namespace != null && t.Namespace.EndsWith("Models"))
                .Conventions.Setup(c => c.Add(DefaultCascade.SaveUpdate()));
        }
    }

 

Now Open Web.config file and set the connectionString tag :

 

<connectionStrings>
    <add name="DefaultConnection" connectionString="Server=EHSAN\EHSAN;Database=NhMvcDB;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

 

Notice that NhMvcDB is my database name and DefaultConnection is my connectionString Name and EHSAN\EHSAN is my SQL server instance name!

You should create the Repository class to talk to the database, to make it simple I just create the ProductRepository Class (Not a Generic class for using all entities), to do that add an Interface to your Model :

 

    public interface IProductRepository
    {
        void Add(Product product);
        Product Get(int id);
        void Remove(Product product);
        IEnumerable<Product> GetAll();
        IEnumerable<Product> GetAllProductsByCategoryQuery(int categoryId);
        IEnumerable<Category> GetAllCategoriesQuery();
    }

 

And then  implement the members in ProductRepository class like this

 

    public class ProductRepository : IProductRepository
    {
        private readonly ISession _session;

        public ProductRepository()
        {
            _session = SessionFactory.GetCurrentSession();
        }
        public void Add(Product product)
        {
            SessionFactory.GetCurrentSession().Save(product);
        }

        public Product Get(int id)
        {
            return SessionFactory.GetCurrentSession().Get<Product>(id);
        }

        public void Remove(Product product)
        {
            SessionFactory.GetCurrentSession().Delete(product);
        }

        public IEnumerable<Product> GetAll()
        {
            return _session.Query<Product>();
        }

        public IEnumerable<Product> GetAllProductsByCategoryQuery(int categoryId)
        {
            var products= _session.Query<Product>();
            var productsByCategory = from c in products
                                     where c.Id == categoryId
                                     select c;
            return productsByCategory;
        }

        public IEnumerable<Category> GetAllCategoriesQuery()
        {
            return _session.Query<Category>();
        }
    }

 

Now create the Service interface

 

    public interface IProductService
    {
        void AddProduct(Product product);
        void RemoveProduct(Product productId);
        Product GetProduct(int productId);
        IEnumerable<Product> GetAllProducts();
        IEnumerable<Product> GetAllProductsByCategory(int categoryId);
        IEnumerable<Category> GetAllCategory();
    }

 

And Service implementation :

 

    public class ProductService : IProductService
    {
        private readonly IProductRepository _productRepository;
        public ProductService(IProductRepository productService)
        {
            _productRepository = productService;
        }
        public void AddProduct(Product product)
        {
            _productRepository.Add(product);
        }
        public void RemoveProduct(Product productId)
        {
            _productRepository.Remove(productId);
        }
        public Product GetProduct(int productId)
        {
            var product = new Product { Id = productId };
            return product;
        }
        public IEnumerable<Product> GetAllProducts()
        {
            var products = _productRepository.GetAll();
            return products;
        }
        public IEnumerable<Product> GetAllProductsByCategory(int categoryId)
        {
            var products = _productRepository.GetAllProductsByCategoryQuery(categoryId);
            return products;
        }
        public IEnumerable<Category> GetAllCategory()
        {
            var categories = _productRepository.GetAllCategoriesQuery();
            return categories;
        }
    }
 

 and in Controllers folder create the ProductController with this definition

 

    public class ProductController : Controller
    {
      private readonly IProductService _productService;

        public ProductController(IProductService productService)
        {
            _productService = productService;
        }

        public ActionResult List()
        {
            var products = _productService.GetAllProducts();
            return View(products);
        }

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

        [HttpPost]
        public ActionResult Add(Product product)
        {
            if (ModelState.IsValid)
            {
                _productService.AddProduct(product);
            }
            return View();
        }
  }

 

Which list action returns the list of products and by Add action, you can add a product, about the Dependency Resolver, add Ninject by Nuget :

 

Nuget

 

Then add this configuration class to your project

 

    public class NinjectConfig
    {
        private static IKernel _ninjectKernel;
        public class NinjectDependencyResolver : DefaultControllerFactory
        {
            public NinjectDependencyResolver()
            {
                _ninjectKernel = new StandardKernel();
                ConfigurDepndency();
            }
            protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
            {
                return controllerType == null ? null : (IController)_ninjectKernel.Get(controllerType);
            }
        }
        private static void ConfigurDepndency()
        {
            _ninjectKernel.Bind<IProductRepository>().To<ProductRepository>();
            _ninjectKernel.Bind<IProductService>().To<ProductService>();
        }
    }

 

And add this line of code to your global.asax in Application_Start()

 

 ControllerBuilder.Current.SetControllerFactory(new NinjectConfig.NinjectDependencyResolver()); 

 

 end!



Layer Supertype pattern with example in C#

First of all look at the definition by @martinfowler "A type that acts as the supertype for all types in its layer" all you need is a Supertype Class for all the Objects. I usually use it in the Repository layer as a generic Repository. I recommend to use it if you have more than one kind of object in your layer. Let's consider an example in the real world, Create a class and name it Profile

 

   public class Profile
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

 

 Then create a generic interface called IRepository

 

 public interface IRepository<T>
    {
        void Add(T entity);
        void Delete(T entity);
    }

 

Now create the IProfileRepository

 

    public interface IProfileRepository : IRepository<Profile>
    {
    }

 

Then create the Repository Class, this is the Generic Class that we talk about

 

    public class Repository<T> : IRepository<T>
    {
        public void Add(T entity)
        {
            throw new NotImplementedException();
        }

        public void Delete(T entity)
        {
            throw new NotImplementedException();
        }
    }

 

As you see you have to implement the Add and Delete methods, now if you want to create the ProfileRepository you don’t need to create the Delete and Add again

 

    public class ProfileRepository : Repository<Profile>, IProfileRepository
    {
    }

 

 That's it, Thanks for reading!



Using Generic type for type casting in F#

In order to validate some input of type object into numeric types, you can use System.Convert in C#. We have them in F# as well! Look at the following function:

 

open System

let validate<'a, 'b> (cast: 'a -> 'b) (x: 'a) =
    try
        cast x |> Some
    with _ -> None

let a = validate int "3423"
let d = validate<obj, decimal> Convert.ToDecimal (null :> obj)
let e = validate<string, DateTime> Convert.ToDateTime "2017-10-10"

 

Validate has been used to convert obj to decimal and even to DateTime. In order to see the result of the following piece of code, you can use it in F#.Net Core console application: 

 

[<EntryPoint>]

let main argv =

    printfn "%A" e // or d and a that has calculated by Validate<,>

    0

 



Introducing sqlbulktools

In my previews blog post I wrote about Z.bulkOperation. I migrated to sqlbulktools just because it's free with the same ability! (to be frank). Now to see the reason for my migration, fire up visual studio and Install the latest version of the library using the following command in console package manager:

 static void Main(string[] args)

        {



            var list = new List<User>();



            for (int i = 0; i < 100000; i++)

            {

                list.Add(new User

                {

                    Id = Guid.NewGuid(),

                    Name = "Ehsan",

                    Email = "mail@ehsanghanbari.com"

                });

               

            }



            Insert(list);



            Update(list);



            Delete(list);



        }



        public static void Insert(IList<User> users )

        {

            var bulkOperation = new BulkOperations();



            using (var trans = new TransactionScope())

            {

                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString))

                {

                    bulkOperation.Setup<User>()

                        .ForCollection(users)

                        .WithTable("Users")

                        .AddAllColumns()

                        .BulkInsert()

                       // .SetIdentityColumn(x => x.Id, ColumnDirection.Output)

                        .Commit(connection);

                }



                trans.Complete();

            }

        }



        public static void Update(IList<User> users)

        {

            var bulkOperation = new BulkOperations();



            using (var trans = new TransactionScope())

            {

                using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString))

                {

                    bulkOperation.Setup<User>()

                        .ForCollection(users)

                        .WithTable("Users")

                        .AddAllColumns()

                        .BulkUpdate()

                        .MatchTargetOn(x => x.Id)

                        .Commit(conn);

                }



                trans.Complete();

            }

        }



        public static void Delete(List<User> list)

        {

            var bulkOperation = new BulkOperations();



            using (var trans = new TransactionScope())

            {

                using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString))

                {

                    bulkOperation.Setup<User>()

                        .ForCollection(list)

                        .WithTable("Users")

                        .AddColumn(x => x.Id)

                        .BulkDelete()

                        .MatchTargetOn(x => x.Id)

                        .Commit(conn);

                }



                trans.Complete();

            }

        }

Install-Package sqlbulktools

And get started!

Simply copy and paste the above code in your console application and run it. The result of CRUD operation with sqlbulktools  on 100000 of records in my machine would be:

insert   5,066ms

update   12,372ms

delete   2,0305ms

It could be different in every machine. But I think it's a good idea to use it in an enterprise application. Cheers!



Multiple submit buttons in asp.net MVC

In asp.net MVC you can submit a form by @using(Html.BeginForm()). You can Post the model you have bound via this operation and command the beginning form to post to a Post action: 

@using(Html.BeginForm("Create","FooController")).

Now if you have more than one submit button to send the page content to different post action, there are few ways: one of them is to post the content to a specific action and then decide in it to redirect which action:

 Razor:

<input type="submit" value="Field1" name="submitButton"  />

<input type="submit" value="Field2" name="submitButton"  />

 

Controller:

         public ActionResult SpecificOne(DTO dTO, string submitButton)

         {

                switch (submitButton)

                {

                    case "Field1":

                            return RedirectToAction("FirstCreate")

                    case "Field2":

                              return RedirectToAction("SecondCreate")

                 }

          }

 

But the way that I like it more is to use the attribute in post actions, this attribute would be like this:

   [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

    public class HttpParamActionAttribute : ActionNameSelectorAttribute

    {

        public string Name { get; set; }



        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)

        {

            return controllerContext.HttpContext.Request[Name] != null;

        }

    }

 

 

Now in your razor view, you should give a name to your buttons (names should be the same as your target actions) :

@model DTO 

@using(Html.beginForm(null, null))

{

   <button type="submit" name="FirstCreate" >First</button>

   <button type="submit" name="SecondCreate" >Second</button>        

}

And about the actions you should use the mentioned attribute and give the button name property:

        [HttpPost]

        [HttpParamAction(Name = "FirstCreate")]

        public ActionResult FirstCreate()

        {

            return View();

        }





        [HttpPost]

        [HttpParamAction(Name = "FirstCreate")]

        public ActionResult SecondCreate()

        {

            return View();

        }

 

Good luck!



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to query over Icollection<> of a type with linq
How to use PagedList In asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
Redis as a cache server