European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Amsterdam :: Using Dependency Injection with AutoFac in the ASP.NET Web API

clock March 26, 2013 11:07 by author Scott

This post is going to tell you exactly how to use the same in DI container in your MVC Controllers and your Web Api controllers, so you can share the same set of services. Of course after you have seen this, it will be immediately clear how to use different containers in both, if you like to do so. The example will be implemented using the Repository pattern, AutoFac, Entity Framework 5 and the EF powertools.

Setting things up

Fire up Visual Studio 2012 RC and start a new MVC 4 empty project:

Call it anything you like. After Visual Studio is done creating your project layout, we’re going to implement the Repository pattern. In a production application you’ll probably want to split your solution into multiple projects, but for now we’re going to do everything in one. First, make sure you have installed the Entity Framework powertools using the Visual Studio extension manager:

After this, use NuGet to add EF 5.0 support to your MVC project:

If you don’t see the PreRelease version, make sure to set the combobox in the top of the screen to “Include Prerelease”. There is one last thing left to do to complete the setup and that’s adding a DI container to our project. You can of course use anything you like, but I’m going with AutoFac. If you want to find out why you should use AutoFac too you can read this. In short, AutoFac combines a full feature set with great performance, is easy to configure and has great support. You can use NuGet to add AutoFac to your project:

Make sure you get the “MVC 4 RC Integration” package. This will provide you with easy integration and will also install the basic AutoFac DLL’s. That’s it, now we’ve got everything we need (assuming you already have a database).

Creating the repository

Create the following interface:

01           using System;
02           using System.Collections.Generic;
03           using System.Linq;
04           using System.Text;
05           using System.Threading.Tasks;
06          
07           namespace Adventureworks.DAL.Repository
08           {
09               public interface IRepository<in TKey,TEntity>    {
10                   void Add(TEntity entity);
11                   void Delete(TEntity entity);
12                   void Update(TEntity entity);
13                   IEnumerable<TEntity> GetAll();
14                   TEntity GetById(TKey id);
15               }
16           }

Now let’s implement it using EF 5.0 and the powertools. I really like the Code only feature of the new Entity Framework release, totally removing the .edmx file. But until recently you couldn’t reverse engineer code only from an existing database. Luckily the EF powertools fix this for us. Right click your Web Project and go the “Entity Framework” menu and select “Reverse engineer Code first”:

Select the database of your choosing and let the tooling do it’s magical stuff. After all is said and done, you will have Entity classes, a DBContext and a file containing the code for configuring the DbContext. Create a class which implements the IRepository interface like this:

1              using System;
2              using System.Collections.Generic;
3              using System.Data.Entity.Infrastructure;
4              using System.Linq;
5              using System.Text;
6              using System.Threading.Tasks;
7              using Adventureworks.Domain;
8             
9              namespace Adventureworks.DAL.Repository.EntityFramework
10           {
11               public class EntityFrameworkProductRepository : IRepository<int,Product>
12               {
13          
14                   public void Add(Product entity)
15                   {
16                       PerformAction((context) =>
17                           {
18                               context.Product.Add(entity);
19                               context.SaveChanges();
20                           });
21          
22                   }
23          
24                   public void Delete(Product entity)
25                   {
26                       PerformAction((context) =>
27                           {
28                               context.Product.Attach(entity);
29                               context.Product.Remove(entity);
30                               context.SaveChanges();
31                           });
32                   }
33          
34                   public void Update(Product entity)
35                   {
36                       PerformAction((context) =>
37                           {
38                              context.Product.Attach(entity);
39                              context.Entry(entity).State = System.Data.EntityState.Modified;
40                              context.SaveChanges();
41                           });
42                   }
43          
44                   public IEnumerable<Product> GetAll()
45                   {
46                       return Read((context) =>
47                           {
48                               return context.Product.AsNoTracking().ToArray();
49                           });
50          
51                   }
52          
53                   public Product GetById(int id)
54                   {
55                       return Read((context) =>
56                           {
57                               Product p = context.Product.AsNoTracking().SingleOrDefault((pr) => pr.ProductID ==
id);
58                               if (p == null)
59                               {
60                                   throw new ArgumentException("Invalid id: " + id);
61                               }
62                               return p;
63                           });
64                   }
65          
66                   private void PerformAction(Action<AdventureWorks2012Entities> toPerform)
67                   {
68                       using (AdventureWorks2012Entities ents = new AdventureWorks2012Entities())
69                       {
70                           ConfigureDbContext(ents);
71                           toPerform(ents);
72                       }
73                   }
74          
75                   private T Read<T>(Func<AdventureWorks2012Entities, T> toPerform)
76                   {
77                       using (AdventureWorks2012Entities ents = new AdventureWorks2012Entities())
78                       {
79                           ConfigureDbContext(ents);
80                           return toPerform(ents);
81                       }
82                   }
83          
84                   private void ConfigureDbContext(AdventureWorks2012Entities ents)
85                   {
86                       ents.Configuration.AutoDetectChangesEnabled = false;
87                       ents.Configuration.LazyLoadingEnabled = false;
88                       ents.Configuration.ProxyCreationEnabled = false;
89                       ents.Configuration.ValidateOnSaveEnabled = true;
90          
91                   }
92          
93               }
94           }

There are a couple of things going on here. Starting on line 66 I’ve created three helper methods which set up the DbContext correctly and dispose it. These methods are used by calling them and supplying a Lambda which uses the DbContext. Let’s take a look at the GetAll method on line 44. You can see that I don’t use change tracking. Change tracking is something you get as a bonus when using the EF, I like to abstract this away with my Repository implementation. It’s also completely useless in a web application since all state is gone after each request and it has a lot of overhead. “But how do you update if you don’t have any change tracking?” you ask?, well take a look at the Update method on line 34. Just set the whole entity as “Modified” and the EF will perform an update for you.

Creating a Web API Controller

Now let’s create a Web API controller to perform some CRUD functionality:

Implement it like this:

1              using System;
2              using System.Collections.Generic;
3              using System.Linq;
4              using System.Net;
5              using System.Net.Http;
6              using System.Web.Http;
7              using Adventureworks.DAL.Repository;
8              using Adventureworks.Domain;
9             
10           namespace Adventureworks.Web.Controllers
11           {
12               public class ProductController : ApiController
13               {
14          
15                   private IRepository<int, Product> _productRepository;
16          
17                   public ProductController(IRepository<int,Product> repository)
18                   {
19                       _productRepository = repository;
20                   }
21          
22                   public IEnumerable<Product> Get()
23                   {
24                       return _productRepository.GetAll();
25                   }
26          
27                   public Product Get(int id)
28                   {
29                       try
30                       {
31                           return _productRepository.GetById(id);
32                       }
33                       catch (ArgumentException ex)
34                       {
35                           throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound){ Content = new StringContent(ex.Message)});
36                       }
37                   }
38          
39                   // POST api/product
40                   public HttpResponseMessage Post(Product product)
41                   {
42                      ValidateProduct();
43                      _productRepository.Add(product);
44                      return new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(Url.Route("DefaultApi",
45                          new{controller="Product",id=product.ProductID}))};
46                   }
47          
48                   // PUT api/product/5
49                   public HttpResponseMessage Put(Product product)
50                   {
51                       ValidateProduct();
52                       _productRepository.Update(product);
53                       return new HttpResponseMessage(HttpStatusCode.NoContent);
54                   }
55          
56                   // DELETE api/product/5
57                   public HttpResponseMessage Delete(Product product)
58                   {
59                       _productRepository.Delete(product);
60                       return new HttpResponseMessage(HttpStatusCode.NoContent);
61                   }
62          
63                   private void ValidateProduct()
64                   {
65                       if (!ModelState.IsValid)
66                       {
67                           throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
68                       }
69                   }
70               }
71           }

Let’s go to line 65 first. This is a helper method which uses the built in Model Binding feature to validate the incoming product. This means that you can just decorate your Product class with attributes or implement IValidatable object to implement data validation. Keeping up with the spirit of rest, this method will generate a BadRequest statuscode when the incoming product is invalid. Now jump up to the constructor. The controller only works with an IRepository interface to perform the crud functionality, it never knows anything about the Entity Framework. This is the key advantage of DI, as we can now mock the repository and unittest our controller. Now jump to line 42; The Post method. A post in REST means an insert. It’s also in the spirit of REST that you use the HTTP statuscodes to signal what’s going on. When you create new content, you should provide the caller with an url to the new content. Similar to the Post method, you can see that the other methods also use statuscodes to indicate if everything went well or not.

Wiring everything up

Last thing left to do is to configure our container and integrate it with MVC. Here’s my Global.asax:

1              using System;
2              using System.Collections.Generic;
3              using System.Linq;
4              using System.Web;
5              using System.Web.Http;
6              using System.Web.Mvc;
7              using System.Web.Routing;
8              using Adventureworks.DAL.Repository.EntityFramework;
9              using Adventureworks.Web.Services;
10           using Autofac;
11           using Autofac.Integration.Mvc;
12           using Autofac.Integration.WebApi;
13          
14           namespace Adventureworks.Web
15           {
16               // Note: For instructions on enabling IIS6 or IIS7 classic mode,
17               // visit http://go.microsoft.com/?LinkId=9394801
18               public class MvcApplication : System.Web.HttpApplication
19               {
20                   protected void Application_Start()
21                   {
22                       AreaRegistration.RegisterAllAreas();
23          
24                       FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
25                       RouteConfig.RegisterRoutes(RouteTable.Routes);
26          
27                       var builder = new ContainerBuilder();
28                       builder.RegisterControllers(typeof(MvcApplication).Assembly);
29                       builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
30                       builder.RegisterType<EntityFrameworkProductRepository>().AsImplementedInterfaces().InstancePerApiRequest().InstancePerHttpRequest();
31                       var container = builder.Build();
32          
33                       DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
34                       GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
35                   }
36               }
37           }

First up are lines 28-32. This is the configuring of the AutoFac container. You register all the controllers for MVC and the Web API with two lines of code. This is done on lines 29 and 30. On line 31 I am registering the EntityFrameworkProductRepository in a per request scope, for MVC controllers and Web API controllers. On line 32 the container is built. On line 35 the container is registered for MVC controllers. On line 36 it’s registered for API controllers. This is what bites people the most. To use DI with MVC, you need a class which implements IDependencyResolver. To use DI with the ASP.NET Web API, you also need a class which implements IDependencyResolver. But these interfaces aren’t the same and they live in different namespaces. The dependency resolvers are also registered differently as you can see on lines 35 and 36. Luckily, AutoFac’s MVC integration package which we installed earlier, contains dependency resolvers for use to use, otherwise we had to implement these ourselves. That’s all! Now go out and test your REST service with your favorite tool.



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Integrate Facebook Login button in ASP.NET MVC 4 application

clock March 15, 2013 07:06 by author Scott

This article demonstrates how to integrate login button on the web page in order to obtain access token that we'll need for further tutorials.

Visual Studio project setup

Firstly, let's get started by opening visual studio and creating new ASP.NET Mvc 4 Web Application. Name it FacebookLoginButton and make sure .NET Framework 4 is selected. Click on OK. Another window should now pop up asking for a type of tempalte you'd like to install in your app. Select An Empty ASP.NET MVC Project.

Once you've got your project created, right click on Controllers folder and Add Controller. Make sure controller name is set to HomeController.

What we need now is a view associated with home controller index method. To add a view, open newly created HomeController and look for a line where it returns View() ActionResult. View() should be highligted in red. Right click on it and select Add View.

Make sure you compile your project before editing anything. There is some problem with VS 2010 and MVC 4 Razor engine. When you try to edit .cshtml file without rebuilding your solution first, VisualStudio will crash.

Import and configure facebook javascript framework

Time for a little bit of javascript-ing. Buuu. Right click on Scripts and create new Javascript file. Name it Facebook.js. Paste in following content:

function InitialiseFacebook(appId) { 

    window.fbAsyncInit = function () {
        FB.init({
            appId: appId,
            status: true,
            cookie: true,
            xfbml: true
        }); 

        FB.Event.subscribe('auth.login', function (response) {
            var credentials = { uid: response.authResponse.userID, accessToken: response.authResponse.accessToken };
            SubmitLogin(credentials);
        }); 

        FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                alert("user is logged into fb");
            }
            else if (response.status === 'not_authorized') { alert("user is not authorised"); }
            else { alert("user is not conntected to facebook");  } 

        }); 

        function SubmitLogin(credentials) {
            $.ajax({
                url: "/account/facebooklogin",
                type: "POST",
                data: credentials,
                error: function () {
                    alert("error logging in to your facebook account.");
                },
                success: function () {
                    window.location.reload();
                }
            });
        } 

    }; 

    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document)); 

}

This javascript will ensure that we're subscribed to login event on which we'll submit fb access token to our controller and save it in session. Also, on each window load, we'll check for fb login status and alert user accordingly.

Sign up for an app

Now, go to developers.facebook.com and create a new app. Make sure all app's urls point to the actual address of the app. If you're running the app from Visual Studio, its address will be http://localhost:[PORT NUMBER].

Login model and controller

Next, we need to add account controller that will save facebook response in session. Before we add it, let's create a model for an object that we'll pass to account controller. Right click on Models folder and add FacebookLoginModel.cs (Class).

namespace FacebookLoginButton.Models
{
    public class FacebookLoginModel
    {
        public string uid { get; set; }
        public string accessToken { get; set; }
    }
}

Once we've got our model, we can add AccountController.cs.

using System.Web.Mvc;
using FacebookLoginButton.Models; 

namespace FacebookLoginButton.Controllers
{
    public class AccountController : Controller
    {
        [HttpPost]
        public JsonResult FacebookLogin(FacebookLoginModel model)
        {
            Session["uid"] = model.uid;
            Session["accessToken"] = model.accessToken; 

            return Json(new {success = true});
        } 

    }
}

Login button configuration

To enable facebook framework, make sure you've got following lines added to your Views -> Shared -> Layout.cshtml file. Following lines should be added just before body closing tag.

<div id="fb-root"></div>
    <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/Facebook.js")"
type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            InitialiseFacebook(@System.Configuration.ConfigurationManager.AppSettings["FacebookAppId"]);
        });
    </script>

Finally, modify Views -> Home -> Index.cshtml by pasting in following code:

@{
    ViewBag.Title = "Part 1 - Facebook Login Button";    Layout = "~/Views/Shared/_Layout.cshtml";


<h2>Part 1 - Facebook Login Button</h2> 

<fb:login-button autologoutlink="true" perms="read_friendlists, create_event, email, publish_stream"></fb:login-button> 

<p>Facebook Access Token: @Session["accessToken"]</p>
<p>Facebook User Id: @Session["uid"]</p> 

<p>If you're not getting javascript prompts on each window load, make sure facebook app id in web config is correct.</p>

That's it. Feel free to download comleted solution attached to this post.

Done. Great job

 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET MVC 3 and MVC 4 Routing

clock March 11, 2013 05:59 by author Scott

Basically, Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event.

How to defining route...

public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // Route Pattern
 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for above defined parameters
 );


protected void Application_Start()
{
 RegisterRoutes(RouteTable.Routes);
 //To:DO
}

When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it returns a 404 HTTP status code.

See the picture below:

In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default values for controller,action and id parameters. Default values means if you will not provide the values for controller or action or id defined in the pattern then these values will be serve by the routing system.

Suppose your webapplication is running on www.example.com then the url pattren for you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system.

What is the Difference between Routing and URL Rewriting

Many developers compares routing to URL rewritting that is wrong. Since both the approaches are very much different. Moreover, both the approaches can be used to make SEO friendly URLs. Below is the main difference between these two approaches.

1. URL rewriting is focused on mapping one URL (new url) to another URL (old url) while routing is focused on mapping a URL to a resource.

2. Actually, URL rewriting rewrites your old url to new one while routing never rewrite your old url to new one but it map to the original route.



European ASP.NET MVC 4 Hosting - Amsterdam :: Using NHibernate in an ASP.NET MVC 4 Application

clock March 6, 2013 05:58 by author Scott

ASP.NET MVC is a common framework for developing web applications. As we all know that M in MVC stands for model, and for a Line of business (LoB application ), the model is often the backbone. For defining a model that persists in a database, ASP.NET MVC supports Entity Framework (now Open Source) out of the box. Other possible options are:

ADO.NET hand coded data layer where you write all the queries explicitly.

- Use commercial O/R mappers like LLBLGen
- Use Open Source O/R mapper like NHibernate.

Today we will see how we can get started using Nhibernate

Getting Started with NHibernate

You can get additional information about the NHibernate from here.

Once you identify various models and relationship in your data model, you can now introduce NHibernate for mapping these models to a persistence store like (SQL Server, Oracle etc).
One of the most important part of using ORM is establishing mapping between Model objects and the Database tables. If we use NHibernate, then this mapping needs to be set explicitly using XML file.

In the following steps, we will be exploring use of NHibernate in ASP.NET MVC 4 application.

Step 1: Open VS 2012 and create MVC 4 application. On the project, right click and select  Manage NuGet Packages’. You will see the Manage Nuget Packages screen. In the search TextBox enter ‘NHibernate’ and you will get the following result:

Once you click the ‘Install’, you will get below references in then project:

- NHibernate
- Lesi.Collections

Step 2: Now it is a time to define the Model layer. As I wrote in the beginning that based upon the application requirement, you need to decide upon the Model objects and the relationship between them. So now let’s define an application that is used to maintain employee records (very simple, but you can extend the concept). Let’s add the new class in the Models folder as shown below:

public class EmployeeInfo
{
int _EmpNo;
public virtual int EmpNo
{
  get { return _EmpNo; }
  set { _EmpNo = value; }
}
string _EmpName;
public virtual string EmpName
{
  get { return _EmpName; }
  set { _EmpName = value; }
}
int _Salary;
public virtual int Salary
{
  get { return _Salary; }
  set { _Salary = value; }
}
string _DeptName;
public virtual string DeptName
{
  get { return _DeptName; }
  set { _DeptName = value; }
}
string _Designation;
public virtual string Designation
{
  get { return _Designation; }
  set { _Designation = value; }
}
}

The class EmployeeInfo contains properties. These properties will be used for mapping with the Table Columns. These properties are defined as virtual properties because of the lazy association which is used by NHibernate to set proxy entity on association property.

Step 3: Once the Model class for mapping is ready, now let’s think of the database to persist the data. For this simple application, we will use a database called Company in SQL Server. The name of the table is EmployeeInfo which can be created as shown below:

USE [Company]
GO
/****** Object:  Table [dbo].[EmployeeInfo]    Script Date: 1/17/2013 11:22:12 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[EmployeeInfo](
    [EmpNo] [int] IDENTITY(1,1) NOT NULL,
    [EmpName] [varchar](50) NOT NULL,
    [Salary] [decimal](18, 0) NOT NULL,
    [DeptName] [varchar](50) NOT NULL,
    [Designation] [varchar](50) NOT NULL,
CONSTRAINT [PK_EmployeeInfo] PRIMARY KEY CLUSTERED
(
    [EmpNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING
OFF
GO

Step 4: To set the mapping, we need to add an XML file in the project as ‘Embedded Resource’. For this sample, I’ll use two folders under the default Model folder - NHibernate\Configuration and NHibernate\Mappings.

The naming convention for the mapping files are by default <ModelName>.hbm.xml, so in our case it will be ‘EmployeeInfo.hbm.xml’. This file goes into the Mappings folder. This file maps the Model class with the database table columns with the constraints like primary key, data types etc. The file is as shown below:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping
xmlns="urn:nhibernate-mapping-2.2"
assembly="MVC4_Using_NHB"
namespace="MVC4_Using_NHB"
auto-import="true">
<class name="MVC4_Using_NHB.Models.EmployeeInfo,MVC4_Using_NHB">
  <id name="EmpNo" access="property" column="EmpNo" type="Int32">
   <generator class="native"></generator>
  </id>
  <property name="EmpName" access="property"
   column="EmpName" type="String"></property>
  <property name="Salary" access="property"
   column="Salary" type="Int32"></property>
  <property name="DeptName" access="property"
   column="DeptName" type="String"></property>
  <property name="Designation" access="property"
   column="Designation" type="String"></property>
  </class>
</hibernate-mapping>


The above xml file demonstrates the mapping between EmployeeInfo class and its properties with the columns. The mapping table is defined by the NHibernate APIs while establishing connection to database.

Note: One important thing is that by default no intellisense is available so to achieve this add nhibernate-configuration.xsd and nhibernate-mapping.xsd in below path

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Xml\Schemas

Step 5: Once the mapping is defined, now let’s define the NHibernate configuration for the application. This provides information about the database provider, connection string and the mapping file used for the connectivity. So in the project, add a new XML file in the Models\Configuration folder created above; the name of the file will be ‘hibernate.cfg.xml’. Add the following configuration in it:

<?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="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
  <property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver</property>
  <property name="connection.connection_string">Data Source=.;Initial Catalog=Company;Integrated Security=SSPI</property>
  <property name="show_sql">false</property>
</session-factory>
</hibernate-configuration>


Step 6: Now it’s time to add some code to do CRUD operations against the database table using the mapping model. NHibernate provides various classes and interfaces for performing operations, some of them are used in this implementation and they are as below:

ISession: This is a main runtime interface between NHibernate and .NET and is used to manipulate entities.

ISessionFactory: A Session is created by this interface. The method ‘OpenSession()’ is provided to create session. One session factory is required per database. The implementation is thread safe and can live till the life time of the application.

As you can see in the code below, we have provided the absolute path of the configuration file to the configuration object and also provided it with the Directory Information where all the mapping files will be kept (in the OpenSession method).

IQuery: This is an object representation of NHibernate query. This is created using ‘CreateQuery()’ method of the ISession. This is the method where the table name is passed and based upon which column the mapping can take place.

ITransaction: Used to manage transactions. This is required during DML operations.
Add a new class in the Models folder and add the following code in it:

/// <summary>
/// class to perform the CRUD operations
/// </summary>
public class EmployeeInfoDAL
{
//Define the session factory, this is per database
ISessionFactory sessionFactory;
/// <summary>
/// Method to create session and manage entities
/// </summary>
/// <returns></returns>
ISession OpenSession()
{
  if (sessionFactory == null)
  {
   var cgf = new Configuration();
   var data = cgf.Configure(
         HttpContext.Current.Server.MapPath(
            @"Models\NHibernate\Configuration\hibernate.cfg.xml"));
   cgf.AddDirectory(new System.IO.DirectoryInfo(
         HttpContext.Current.Server.MapPath(@"Models\NHibernate\Mappings")));
   sessionFactory = data.BuildSessionFactory();
  }
  return sessionFactory.OpenSession();
}
public IList<EmployeeInfo> GetEmployees()
{
  IList<EmployeeInfo> Employees;
  using (ISession session = OpenSession())
  {
   //NHibernate query
   IQuery query = session.CreateQuery("from EmployeeInfo");
   Employees = query.List<EmployeeInfo>();
  }
  return Employees;
}
public EmployeeInfo GetEmployeeById(int Id)
{
  EmployeeInfo Emp = new EmployeeInfo();
  using (ISession session = OpenSession())
  {
   Emp = session.Get<EmployeeInfo>(Id);
  }
  return Emp;
}
public int CreateEmployee(EmployeeInfo Emp)
{
  int EmpNo = 0;
  using (ISession session = OpenSession())
  {
   //Perform transaction
   using (ITransaction tran = session.BeginTransaction())
   {
    session.Save(Emp);
    tran.Commit();
   }
  }
  return EmpNo;
}
public void UpdateEmployee(EmployeeInfo Emp)
{
  using (ISession session = OpenSession())
  {
   using (ITransaction tran = session.BeginTransaction())
   {
    session.Update(Emp);
    tran.Commit();
   }
  }
}
public void DeleteEmployee(EmployeeInfo Emp)
{
  using (ISession session = OpenSession())
  {
   using (ITransaction tran = session.BeginTransaction())
   {
    session.Delete(Emp);
    tran.Commit();
   }
  }
}
}

Build the project and make sure that it is error free.

Step 7: Add a new Controller in the Controllers folder, name it as ‘EmployeeInfoController’. Add the following action methods in the controller class:

using MVC4_Using_NHB.Models;
using System.Web.Mvc;
namespace MVC4_Using_NHB.Controllers
{
public class EmployeeInfoController : Controller
{
  EmployeeInfoDAL objDs;
  public EmployeeInfoController()
  {
   objDs = new EmployeeInfoDAL();
  }
  //
  // GET: /EmployeeInfo/
  public ActionResult Index()
  {
   var Employees = objDs.GetEmployees();
   return View(Employees);
  }
//
// GET: /EmployeeInfo/Details/5
public ActionResult Details(int id)
{
  return View();
}
//
// GET: /EmployeeInfo/Create
public ActionResult Create()
{
  var Emp = new EmployeeInfo();
  return View(Emp);
}
//
// POST: /EmployeeInfo/Create
[HttpPost]
public ActionResult Create(EmployeeInfo Emp)
{
  try
  {
   objDs.CreateEmployee(Emp);
   return RedirectToAction("Index");
  }
  catch
  {
   return View();
  }
}
//
// GET: /EmployeeInfo/Edit/5
public ActionResult Edit(int id)
{
  var Emp = objDs.GetEmployeeById(id);
  return View(Emp);
}
//
// POST: /EmployeeInfo/Edit/5
[HttpPost]
public ActionResult Edit(int id, EmployeeInfo Emp)
{
  try
  {
   objDs.UpdateEmployee(Emp);
   return RedirectToAction("Index");
  }
  catch
  {
   return View();
  }
}
//
// GET: /EmployeeInfo/Delete/5
public ActionResult Delete(int id)
{
  var Emp = objDs.GetEmployeeById(id);
  return View(Emp);
}
//
// POST: /EmployeeInfo/Delete/5
[HttpPost]
public ActionResult Delete(int id,FormCollection collection)
{
  try
  {
   var Emp = objDs.GetEmployeeById(id);
   objDs.DeleteEmployee(Emp);  
   return RedirectToAction("Index");
  }
  catch
  {
   return View();
  }
}
}


Each action method makes a call to the method defined in the EmployeeInfoDAL class. That’s it. Now add views for each action method and test them.

Conclusion

We saw how easy it is to make use of NHibernate in MVC application for building Line of Business (LOB) applications.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Seeding Membership &amp; Roles in ASP.NET MVC 4

clock March 5, 2013 06:44 by author Scott

Jon Galloway has an overview of the new membership features in ASP.NET MVC 4. The Internet project template moves away from the core membership providers of ASP.NET and into the world of SimpleMembershipProvider and OAuth.

There is quite a bit I could write about the new features and the code generated by the Internet project template, but for this post I just want to cover a scenario I've demonstrated in the past - seeding the roles and membership tables. If you are using Entity Framework code-first migrations it's relatively easy to add some code to the Seed method of the migrations configuration to populate the membership tables with some initial roles and users. Just remember every update-database command will call the Seed method, so you have to write the code to make sure you don't try to create duplicate data.

First, the new project template creates an MVC 4 Internet application without any provider configuration, but for the membership features to work properly during a migration, it appears you need at least some configuration. The following code makes sure the SimpleMembershipProvider and SimpleRolesProvider are in place.

<roleManager enabled="true" defaultProvider="simple">
 
<providers>
   
<clear/>
   
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider,
                             WebMatrix.WebData"/>
 
</providers>     
</roleManager>
<membership defaultProvider="simple">
 
<providers>
   
<clear/>
   
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider,
                             WebMatrix.WebData"/>
 
</providers>
</membership>

Then inside the Seed method of the DbMigrationsConfiguration<T> derived class, you can have:

protected override void Seed(MovieDb context)
{           
    //context.Movies.AddOrUpdate(...);

    // ...

    SeedMembership();
}

private void SeedMembership()
{           
    WebSecurity.InitializeDatabaseConnection("DefaultConnection",
        "UserProfile", "UserId", "UserName", autoCreateTables: true);
 
    var roles = (SimpleRoleProvider) Roles.Provider;
    var membership = (SimpleMembershipProvider) Membership.Provider;
 
    if (!roles.RoleExists("Admin"))
    {
        roles.CreateRole("Admin");
    }
    if (membership.GetUser("sallen",false) == null)
    {
        membership.CreateUserAndAccount("sallen", "imalittleteapot");
    }
    if (!roles.GetRolesForUser("sallen").Contains("Admin"))
    {
        roles.AddUsersToRoles(new[] {"sallen"}, new[] {"admin"});
    }
}



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in