Search This Blog

Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Sunday, March 16, 2014

Dynamic Data Provider(DDP) and EntityDataSource Control for EF6



Dynamic Data Provider(DDP) and EntityDataSource 

Control for Entity Framework 6


Microsoft has announced an update to ASP.NET DynamicData and EntityDataSource control, so that they work with Entity Framework 6.


How to install this preview

You can download this preview for ASP.NET DynamicData.EFProvider (http://www.nuget.org/packages/Microsoft.AspNet.DynamicData.EFProvider/) and EntityDataSource (http://www.nuget.org/packages/Microsoft.AspNet.EntityDataSource/) as preview NuGet packages from the NuGet gallery. You can install these pre-release packages through NuGet using the NuGet Package Manager Console, like this:
  • Install-Package Microsoft.AspNet.DynamicData.EFProvider -Version 6.0.0-alpha1 –Pre
  • Install-Package Microsoft.AspNet.EntityDataSource -Version 6.0.0-alpha1 –Pre

Microsoft.AspNet.DynamicData.EFProvider

This package has a DynamicData EFProvider for Entity Framework 6. This provider can work with a Model (either Code First or EF Designer) which was created using Entity Framework 6. This package also installs the Page Templates, Entity Templates and Field Templates which are required for DynamicData. The templates have been updated to useMicrosoft.AspNet.EntityDataSource control which we are also previewing today as well.
Following are the steps for using this package in a ASP.NET DynamicData application:
  1. Create a new ASP.NET Dynamic Data Entities Web Application
  2. Add the Microsoft.AspNet.DynamicData.EFProvider NuGet package
  3. This will do the following
    1. Add a reference to the DynamicData EFProvider binary
    2. Install the templates. If you are starting with a new project, then you can override the templates. If you have an existing application, then you should be careful when overriding the changes. The templates replace the EntityDataSource control which shipped in .NET with Microsoft.AspNet.EntityDataSource and also have a few bug fixes in the Many-Many field template so they work with Entity Framework 6.
  4. Create your model using Entity Framework Code First or EF Designer.
  5. Add the following code in RegisterRoutes in Global.asax.cs to register your EF Model:
    DefaultModel.RegisterContext(
        new Microsoft.AspNet.DynamicData.ModelProviders.EFDataModelProvider(
            () => newNorthwindEntities1()),
        newContextConfiguration { ScaffoldAllTables = true });
  6. Run the project
  7. You would see all the tables listed on the Default page.

Microsoft.AspNet.EntityDataSource Control

This is an update to the EntityDataSource control which shipped in the .NET Framework. The EntityDataSource control has been updated to work with Entity Framework 6.
To use this control, please do the following
  1. Create an ASP.NET application
  2. Install the package Microsoft.AspNet.EntityDataSource
    1. This package will
      1. install the runtime binary for Microsoft.AspNet.EntityDataSource
      2. Install the EntityFramework version 6 NuGet package
      3. Add the following tag prefix in web.config
         
           
                  tagPrefix="ef" 
              assembly="Microsoft.AspNet.EntityDataSource" 
              namespace="Microsoft.AspNet.EntityDataSource" /> 
           
         
  3. Create a new Web Form page
  4. Use the control as follows and bind it to any Databound control such as GridView, FormView etc.
     

Known Issues

  • The templates in Microsoft.AspNet.DynamicData.EFProvider are for C# only.
  • The templates in Microsoft.AspNet.DynamicData.EFProvider are for Web Application projects only and will not work for WebSites projects.

ASP.NET MVC 5 Identity system

The Identity System used in ASP.Net MVC 5

ASP.NET has long supported two basic types of authentication: 1.Windows authentication and 2.forms authentication. Windows authentication is seldom practical for public Web sites because it’s based on Windows accounts and access control list (ACL) tokens. Thus, it requires users to have a Windows account in the application’s domain, and it also assumes clients are connecting from Windows-equipped machines. The other option is forms authentication, a widely adopted approach. Forms authentication is based on a simple idea. For each access to a protected resource, the application ensures the request includes a valid authentication cookie. If a valid cookie is found, then the request is served as usual; otherwise, the user is redirected to a login page and asked to provide credentials. If these credentials are recognized as valid, then the application issues an authentication cookie with a given expiration policy. It’s simple and it just works.

Implementation of any forms authentication module can’t happen without a distinct module that takes care of collecting user credentials and checking them against a database of known users. Writing this membership subsystem has been one of the key responsibilities of development teams—but also one of the most annoying things ever. Writing a membership system is not hard, per se. It mostly requires running a query against some sort of storage system and checking a user name and password. This code is boilerplate and can grow fairly big as you add new authentication features such as changing and recovering passwords, handling a changing number of online users and so on. In addition, it has to be rewritten nearly from scratch if you change the structure of the storage or add more information to the object that describes the user. Back in 2005, with the release of ASP.NET 2.0, Microsoft addressed this problem by introducing right into the framework a provider-based architecture and the membership provider. Instead of reinventing the wheel every time, you could just derive membership from the built-in system and override only the functions you intended to change.

The ASP.NET native membership provider is a standalone component that exposes a contracted interface. The ASP.NET runtime, which orchestrates the authentication process, is aware of the membership interface and can invoke whatever component is configured as the membership provider of the application. ASP.NET came with a default membership provider based on a new given database schema. However, you could easily write your own membership provider to basically target a different database—­typically, an existing database of users.
Does that sound like a great chunk of architecture? In the beginning, nearly everybody thought so. In the long run, though, quite a few people who repeatedly tried to build a custom membership provider started complaining about the verbosity of the interface. Actually, the membership provider comes in the form of an inheritable base class, MembershipProvider, which includes more than 30 members marked as abstract. This means that for any new membership provider you wanted to create, there were at least 30 members to override. Worse yet, you didn’t really need many of them most of the time. A simpler membership architecture was needed.

Introducing the Simple Membership Provider

To save you from the burden of creating a custom membership layer completely from scratch, Microsoft introduced with Visual Studio 2010 SP1 another option: the simple membership API. Originally available in WebMatrix and Web Pages, the simple membership API has become quite a popular way of managing authentication, especially in ASP.NET MVC. In particular, the Internet application template in ASP.NET MVC 4 uses the simple membership API to support user management and authentication.
Looking under the hood of the API, it turns out that it’s just a wrapper on top of the classic ASP.NET membership API and its SQL Server-based data stores. Simple membership lets you work with any data store you have and requires only that you indicate which columns in the table serve as the user name and user ID.
The major difference from the classic membership API is a significantly shorter list of parameters for any methods. In addition, you get a lot more freedom as far as the schema of the membership storage is concerned. As an example of the simplified API, consider what it takes to create a new user:
  1. WebSecurity.CreateUserAndAccount(username, password,
  2.   new { FirstName = fname, LastName = lname, Email = email });
You do most of the membership chores via the WebSecurity class. In ASP.NET MVC 4, however, the WebSecurity class expects to work with an extended membership provider, not a classic membership provider. The additional capabilities in an extended membership provider are related to dealing with OAuth accounts. As a result, in ASP.NET MVC 4, you have two parallel routes for membership implementation: classic membership API using the MembershipProvider class and simple membership API using the ExtendedMembershipProvider class. The two APIs are incompatible.
Before the arrival of Visual Studio 2013 and ASP.NET MVC 5, ASP.NET already offered quite a few ways to handle user authen­tication. With forms authentication, you could rely on classic membership, the simple membership API as defined in Web Pages and a variety of custom membership systems. Consider the common position among ASP.NET experts was that complex real-world applications require their own membership provider. More often than not, the main reason for having a custom membership system was to circumvent structural differences between the required database format and the format of the existing database of user credentials, which might have been in use for years.
Clearly, this wasn’t a situation that could last forever. The community of developers demanded with loud voices a unified system for membership that’s simple to use, narrowly focused and usable in the same way from within any flavor of ASP.NET. This idea weds together well with the One ASP.NET approach pushed by Visual Studio 2013.

One Identity Framework

The purpose of authentication is getting the identity associated with the current user. The identity is retrieved and the provided credentials are compared to records stored in a database. Subsequently, an identity system such as ASP.NET Identity is based on two primary blocks: the authentication manager and the store manager. In the ASP.NET Identity framework, the authentication manager takes the form of the UserManager class. This class basically provides a façade for signing users in and out. The store manager is an instance of the UserStore class. Figure 1 shows the skeleton of an ASP.NET MVC account controller class that’s based on ASP.NET Identity.
Figure 1 Foundation of a Controller Based on ASP.NET Identity
  1. public class AccountController : Controller
  2. {
  3.   public UserManager UserManager { get; private set; }
  4.   public AccountController(UserManager manager)
  5.   {
  6.     UserManager = manager;
  7.   }
  8.   public AccountController() :
  9.     this(new UserManager(
  10.       new UserStore(new ApplicationDbContext())))
  11.   {
  12.   }
  13.   ...
  14. }
The controller holds a reference to the authentication identity manager, UserManager. This instance of UserManager is injected into the controller. You can use either an Inversion of Control (IoC) framework or the poor man’s alternative, the dependency injection (DI) pattern, which uses two controllers, one of which gets a default value (see Figure 1). 
The identity store, in turn, is injected into the authentication identity manager, where it’s used to verify credentials. The identity store takes the form of the UserStore class. This class results from the composition of multiple types:
  1. public class UserStore :
  2.   IUserLoginStore,
  3.   IUserClaimStore,
  4.   IUserRoleStore,
  5.   IUserPasswordStore,
  6.   IUserSecurityStampStore,
  7.   IUserStore,
  8.   IDisposable where TUser : IdentityUser
  9.   {
  10.   }
All interfaces implemented by UserStore are basic repositories for optional user-related data such as passwords, roles, claims and, of course, user data. The identity store needs to know about the actual data source, though. As shown in Figure 1, the data source is injected in the UserStore class through the constructor.
Storage of users’ data is managed through the Entity Framework Code First approach. This means you don’t strictly need to create a physical database to store your users’ credentials; you can, instead, define a User class and have the underlying framework create the most appropriate database to store such records.
The ApplicationDbContext class wraps up the Entity Framework context to save users’ data. Here’s a possible definition for the ApplicationDbContext class:
  1. public class ApplicationDbContext : IdentityDbContext
  2. {
  3. }
Basically, the database context of ASP.NET Identity handles the persistence of a given user type. The user type must implement the IUser interface or just inherit from IdentityUser. Figure 2 presents the source code of the default IdentityUser class.
Figure 2 Definition of the Default User Class in ASP.NET Identity
  1. namespace Microsoft.AspNet.Identity.EntityFramework
  2. {
  3.   public class IdentityUser : IUser
  4.   {
  5.     public string Id { get; }
  6.     public string UserName { get; set; }
  7.     public string PasswordHash { get; set; }
  8.     public string SecurityStamp { get; set; }
  9.     public ICollection Roles { get; private set; }
  10.     public ICollection Claims { get; private set; }
  11.     public ICollection Logins { get; private set; }
  12.   }
  13. }
Here’s an example of a realistic custom user class you might want to use in your applications:
  1. public class ApplicationUser : IdentityUser{
  2.   public DateTime Birthdate { get; set; }
  3. }
The use of Entity Framework Code First is a great move here as it makes the structure of the database a secondary point. You still need one, but to create it, you can use code based on classes. In addition, you can use Entity Framework Code First migration tools to modify a previously created database as you make changes to the class behind it.

To Authenticate a User

ASP.NET Identity is based on the newest Open Web Interface for .NET (OWIN) authentication middleware. This means the typical steps of authentication (for example, creating and checking cookies) can be carried out through the abstract OWIN interfaces and not directly via ASP.NET/IIS interfaces. Support for OWIN requires the account controller to have another handy property, like this:
  1. private IAuthenticationManager AuthenticationManager
  2. {
  3.   get {
  4.   return HttpContext.GetOwinContext().Authentication;
  5.   }
  6. }
The IAuthenticationManager interface is defined in the Microsoft.Owin.Security namespace. This property is important because it needs to be injected into any operation that involves authentication-related steps. Here’s a typical login method:
  1. private async Task SignInAsync(ApplicationUser user, bool isPersistent)
  2. {
  3.   var identity = await UserManager.CreateIdentityAsync(user,
  4.     DefaultAuthenticationTypes.ApplicationCookie);
  5.   AuthenticationManager.SignIn(new AuthenticationProperties() {
  6.     IsPersistent = isPersistent }, identity);
  7. }
The method SignInAsync checks the specified user name and password against the store associated with the authentication manager. To register a user and add the user to the membership database, you use code like this:
  1. var user = new ApplicationUser() { UserName = model.UserName };
  2. var result = await UserManager.CreateAsync(user, model.Password);
  3. if (result.Succeeded)
  4. {
  5.   await SignInAsync(user, isPersistent: false);
  6.   return RedirectToAction("Index", "Home");
  7. }
All in all, ASP.NET Identity provides a unified API for tasks related to authentication. For example, it unifies the code required to authenticate against a proprietary database or a social network OAuth-based endpoint. Figure 3 shows a fragment of the code you need to authenticate users against an external login engine. The code in Figure 3 gets called once the OAuth authentication (for example, against Facebook) has been completed successfully.
Figure 3 Finalizing the Authentication Process through an External Endpoint
  1. public async Task ExternalLoginCallback(
  2.   string loginProvider, string returnUrl)
  3. {
  4.   ClaimsIdentity id = await UserManager
  5.   .Authentication
  6.   .GetExternalIdentityAsync(AuthenticationManager);
  7.   var result = await UserManager
  8.     .Authentication
  9.     .SignInExternalIdentityAsync(
  10.       AuthenticationManager, id);
  11.   if (result.Success)
  12.     return RedirectToLocal(returnUrl);
  13.   else if (User.Identity.IsAuthenticated)
  14.   {
  15.     result = await UserManager
  16.       .Authentication
  17.       .LinkExternalIdentityAsync(
  18.         id, User.Identity.GetUserId());
  19.     if (result.Success)
  20.       return RedirectToLocal(returnUrl);
  21.     else
  22.       return View("ExternalLoginFailure");
  23.   }
  24. }
In this post reference is taken from the microsoft magazine.

Thursday, March 13, 2014

How to Upgrade an ASP.NET MVC 4 and Web API Project to ASP.NET MVC 5 and Web API 2

To upgrade an ASP.NET MVC 4 and Web API Project to ASP.NET MVC 5 and Web API 2


follow this simple and easy steps to upgrade MVC 4 to MVC 5 Project :

1.Backup your project. This walkthrough will require you to make changes  to your project file, package configuration, and web.config files.

2.For upgrading from Web API to Web API 2, in global.asax, change:     

          WebApiConfig.Register(GlobalConfiguration.Configuration)
           to       
         GlobalConfiguration.Configure(WebApiConfig.Register);

3.Make sure all the packages that your projects use are compatible with  MVC 5 and Web API 2. The following table shows the MVC 4 and Web API related  packages than need to be changed. If you have a package that is dependent on  one of the packages listed below, please contact the publishers to get the  newer versions that are compatible with MVC 5 and Web API 2. If you have the  source code for those packages, you should recompile them with the new  assemblies of MVC 5 and Web API 2. 

4.Open your project in Visual Studio 2013.

5.Remove any of the following ASP.NET NuGet packages that are installed.  You will remove these using the Package Manager Console (PMC). To open the  PMC, select the Tools menu and then select Library  Package Manager, then select Package Manager Console.  Your project might not include all of these.Microsoft.AspNet.WebPages.Administration 
  1. This package is typically added when upgrading from MVC 3 to MVC 4.  To remove it, run the following command in the PMC:
  2. Uninstall-Package -Id Microsoft.AspNet.WebPages.Administration
Microsoft-Web-Helpers 
  1. This  package has been rebranded as Microsoft.AspNet.WebHelpers.  To remove it, run the following command in the PMC:
  2. Uninstall-Package -Id Microsoft-Web-Helpers
Microsoft.AspNet.Mvc.FixedDisplayMode  
This package contains a work around for a bug in MVC 4 that has been  fixed in MVC 5. To remove it, run the following command in the PMC:
Uninstall-Package -Id Microsoft.AspNet.Mvc.FixedDisplayModes

The Update-Package command without any parameters will update every  package. You can update packages individually by using the ID argument. For  more information about the update command, run get-help update-package.

Update the Application web.config File

Be sure to make these changes in the app web.config file, not the web.config file in the Views folder.
Locate the / section, and  make the following changes:
  1. In the elements with the name attribute “System.Web.Mvc”, change the  version number from “4.0.0.0” to “5.0.0.0”. (Two changes in that element.)
  2. In elements with the name attribute "System.Web.Helpers” and  "System.Web.WebPages" change the version number from “2.0.0.0” to “3.0.0.0”.  Four changes will occur, two in each of the elements.

   xmlns="urn:schemas-microsoft-com:asm.v1">
    
    
       name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
       oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
    
          name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />       oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />               name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />       oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />          
3.Locate the  section and update the  webpages:version from 2.0.0.0.0 to 3.0.0.0 as shown below:

     key="webpages:Version" value="3.0.0.0" />
     key="webpages:Enabled" value="false" />
     key="PreserveLoginUrl" value="true" />
     key="ClientValidationEnabled" value="true" />
     key="UnobtrusiveJavaScriptEnabled" value="true" />
  
4.Remove any trust levels other than Full. For example:

   

Update the web.config files under the Views folder

If your application is using areas, you will also need to update each web.config file in the Views sub-folder of each Area folder.
  1. Update all elements that contain “System.Web.Mvc” from version “4.0.0.0”  to  version“5.0.0.0”.

   factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
   pageBaseType="System.Web.Mvc.WebViewPage">
    
       namespace="System.Web.Mvc" />
      
    
 

-->
  <pages
      validateRequest="false"
      pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    
      <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
    </controls>
  </pages>
</system.web>
  2. Update all elements that contain “System.Web.WebPages.Razor”  from  version “2.0.0.0”  to  version“3.0.0.0”. If this section contains “System.Web.WebPages”,  update those elements from  version “2.0.0.0” to  version“3.0.0.0”


  
     name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      
name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />      
name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />    
 
 3.If you removed the Microsoft-Web-Helpers NuGet package in a  previous step, installMicrosoft.AspNet.WebHelpers  with  the following command in the PMC:

Install-Package -Id  Microsoft.AspNet.WebHelpers
 4. If your app uses the  User.IsInRole() method, add the following to the Web.config file.

    
       name="RoleManager" />
    

Final Steps

Build and test the application.
 Remove the MVC 4 project type GUID from the project files.
  1. In Solution Explorer, right-click the project name and then select Unload Project.
  2. Right-click the project  and select Edit ProjectName.csproj.
  3.  Locate the ProjectTypeGuids element and then remove  the MVC 4 project GUID, {E3E379DF-F4C6-4180-9B81-6769533ABE47}.
  4. Save and close the open project file.
  5. Right-click the project and select Reload Project.