Friday, January 10, 2014

Using MvcScaffolding Packages to Generate Repositories for your LoB Applications

ASP.NET MVC’s tooling support goes a long way in making it a LOB Application friendly platform. However the default Controller scaffold contains direct references to the DBContext. This is a little smelly when it comes to separation of concerns and can often lead to ending up with ‘fat-controllers’. Instead, if our Scaffolder could generate a Repository Interface and its corresponding implementation, our LoB apps would not only achieve better ‘separation of concerns’ but also becomes more testable. The MvcScaffolder extension that comes as Nuget Package enables us to do precisely this type of scaffolding. Let’s see how we can use it in a simple Contact app.

Getting Started – Installing MvcScaffolder

Step 1: We start off by creating a new MVC 4 Application in Visual Studio. We use the Basic Application template for now.
Step 2: Install the MvcScaffolder using Nuget Package Manager

installing-mvc-scaffolding

This will install the T4Scaffolding dependency as well.

Adding a Model entity and generating the CRUD Screens

Now that we have the MvcScaffolding package installed we are ready to setup our Model and then run the scaffolder on it.

Step 3: Add the following Contact class in the Model folder and build the application.

public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}

  
Step 4: Right Click on the Controller folder and select Add Controller. It brings up the standard Add Controller dialog but if you look at the DropDown, it has two additional options thanks to MvcScaffolding.

mvc-scaffolding-option-in-add-controller

Step 5: Now setup the Add Controller dialog as follows to generate CRUD screens for Contact model object.

- Controller Name: ContactController
- Template as MvcScaffolding: Controller with read/write action and views, using repositories.
- Model Class: Contact (ScaffoldingRepositories.Model)
- Data Context Class: ScaffoldingRepositories.Models.ScaffoldingRepositoriesContext

mvc-scaffolding-option-in-add-controller

Click on Add to complete the scaffolding process.

Step 6: On completion of the Scaffolding process you will see the following files added to your solution

generated-files-and-folders

Controller – ContactController.cs

Models –
a. ContactRespository.cs: This has the Interface and the Implementation for persisting Contact Data. The implementation uses the next generated class i.e. ScaffoldingRepositoriesContext
b. ScaffoldingRepositoriesContext.cs: Contains the EF DbContext implementation used for persisting the data to LocalDb.

Views – Views has the standard CRUD views generated. One thing to note here is that there is a partial view called _CreateOrEdit.cshtml. This view as we will see shortly, is common to both Create and Edit screens and hence separated out into its own partial.

Applying Script References

The generated views have one minor gotcha, as in the script references for jQuery Validation are added at the top of the Create and Edit views.

Our jQuery references are added at the bottom of the _Layout.cshtml. As a result of this the jQuery Validation scripts fail when trying to load ‘before’ the jQuery script itself.

The solution is simple.

Move the jQuery Validation references to the bottom of the page inside a Script section as follows

@section scripts{


}

  
The Script section is important because in the _Layout.cshtml we have the following code


@RenderBody()
 
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)


  
What this means is, Razor view engine will add reference to the jQuery bundle to the Scripts section and then try to render the Scripts section if present in any other child views. The contents of the Scripts section in child view will be after the jQuery bundle has been rendered.

With the Script references fixed, we are ready to run the application.

Running the Application

When we run the application, now we should be able to save data to the database

index-create-index

Neat! So our application is up and running as if it were built using the default MVC Scaffold tool. Time to dig in and see what’s different with the MvcScaffolding extension.

Digging deeper into generated code

Now that everything is working fine, let’s pop the hood and see how things are running. First up the repository.

The Repository

The ContactRepository.cs has the Interface and the implementation for Contact Repository.

generated-contact-repository
Note that the IContactRepository inherits from IDisposable. The implementation uses an instance of the ScaffoldingRepositoriesContext object that uses EF to persist data.

There is an interesting Repository method called AllIncluding and as we can see in the code below, it can accept a parameter consisting of an array of Model properties. This way we can limit the amount of data loaded if required. It can also be used for excluding Navigation properties etc.

The InsertOrUpdate method checks if the Id property has the default value, if it does, it saves it as a new entity. If the Id already has a non-default value, attempt to Update the entity.

generated-contact-repository-impl

The ContactController

The ContactController is also generated a little differently, as in, instead of an instance of DbContext, we have a direct assignment of an Interface to its concrete class hardcoded in the constructor.

private readonly IContactRepository contactRepository;
// If you are using Dependency Injection, you can delete the following constructor
public ContactController() : this(new ContactRepository())
{
}

  
To resolve this, we have to introduce an IoC Container to inject the dependency instance into the controller via the constructor. At this point, we can go ahead and integrate our favorite IoC container/DI framework as we want.

Other MvcScaffolding features

The MvcScaffolding package also has the ability to let you create your own Scaffolds. It creates a bootstrap set of files when you use the following command at the Package Manager Console

PM> Scaffold CustomScaffolder MyScaffolder

What this does is, it adds T4 templates required for Scaffolding into a CodeTemplates folder. All T4 files are in a folder by the name of the scaffolder you created (MyScaffolder).

custom-scaffolder

Now you can update the t4 template to generate a particular type of file and then run the Scaffolding as

PM> Scaffold MyScaffolder

This will generate the file ExampleOutput.cs as follows

namespace ScaffoldingRepositories
{
public class ExampleOutput
{
  // Example model value from scaffolder script: Hello, world!
}
}

  
Essentially the Scaffolding plugin is not only helping generate CRUD screens, but if you have repetitive code that you want to automate, you can very well use the Custom Scaffolder feature to make life easier for yourself.

Conclusion

MvcScaffolding is a nifty extension that adds additional scaffolding capabilities to the default MVC tooling that comes out of the box.

Caveat is that it’s not an officially supported Microsoft plugin. It was developed by Steve Sanderson and Scott Hanselman and you can find more information on Steve’s blog at http://blog.stevensanderson.com/?s=scaffolding

Working with Roles in ASP.NET MVC 4+

In this article, We'll look into how to create a new role, delete a role and attach a user to a specific role in ASP.NET MVC using default Role provider under System.Web.Security namespace.


Introduction


Authentication (Login and Registration) is simple in ASP.NET MVC as the default project template provides all the necessary controller code, model and view to register and login. However adding roles and assigning roles to a particular user seems to be lost in all these stuffs. In this article, we will learn all that is related with Roles for a particular user in ASP.NET MVC 4.

Objective


The objective of this article is to explain how to work with Roles in ASP.NET MVC 4 +.

Assumption


Here we are assuming that we have used the default ASP.NET MVC template (ASP.NET MVC 4  Web Application project type and Internet Application template) that automatically creates a database for us when we try to register for the first time and the default database tables it creates for roles are following


  1. webpages_Roles
  2. webpages_UserInRoles

Creating a new role in ASP.NET MVC


In order to create a new Role, the default template doesn't provide any UI, so we have to build it our self. Below is the simple UI we have built in Razor under Views/Account folder (In fact all views we are going to work with in this article are in this folder). In this case we have used a different Layout page as we do not want the default website Layout to appear.

@{
    ViewBag.Title = "RoleCreate";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<div class="spacerBody">
    &nbsp;</p>
    @Html.ActionLink("Roles", "RoleIndex") | @Html.ActionLink("Add Role to User", "RoleAddToUser")

Role Create</h2> @using(Html.BeginForm()){     @Html.AntiForgeryToken()     @Html.ValidationSummary(true)    
    Role name</
div>             @Html.TextBox("RoleName")     </p>     > }     </div>

Picture - 1

Notice that we have a simple TextBox in the above View with the name as  "RoleName" that we are going to use to create a new Role into our database.

Below are two methods in our AccountController.cs responsible for creating a new Role.

        [Authorize(Roles = "Admin")]
        public ActionResult RoleCreate()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleCreate(string RoleName)
        {
            
                Roles.CreateRole(Request.Form["RoleName"]);
                // ViewBag.ResultMessage = "Role created successfully !";
            
            return RedirectToAction("RoleIndex", "Account");
        }
The first method simply renders the view provided the logged in user has Roles as "Admin" assigned to the database (because of Authorize attribute in this method). So to get started first go to your database table "webpages_Roles" and insert and "Admin" role then map this role to the user id you are logged in with in the "webpages_UsersInRoles" table.


In above case, I am logged in to the application as "SheoNarayan" that has UserId as "2" in the "UserProfile" table that is created by default by ASP.NET MVC project.

Now when Save button is clicked in Picture - 1, the 2nd method of the above code snippet fires and calls the "Roles.CreateRole" method to create a role that is entered into the Textbox.


Listing Roles in ASP.NET MVC


To list roles created in ASP.NET MVC, we have created another view called "RoleIndex" and here is the Razor code for this.

@{
    ViewBag.Title = "Role Listing";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
&nbsp;</p>
<div class="spacerBody">
    @Html.ActionLink("Create New Role", "RoleCreate") | @Html.ActionLink("Add Role to User", "RoleAddToUser")

Role Index</h2>    
            @foreach (string s in Model) {    
       
            @s         </
div>         <div class="td">             <span onclick="return confirm('Are you sure to delete?')">         <a href="/Account/RoleDelete?RoleName=@s" class="delLink"><img src="/images/deleteicon.gif" alt="Delete" class="imgBorder0" /> Delete</a>                            </span>         </div>     </div> }         </div> </div>


In this view, we are simply looping through the Model we are receiving from the controller. The controller method that is responsible to render all the roles are below.
        [Authorize(Roles = "Admin")]
        public ActionResult RoleIndex()
        {
            var roles = Roles.GetAllRoles();
            return View(roles);
        }

The above code simply executes Roles.GetAllRoles() method that gives all roles from the webpages_Roles database table in the form of string array and returns to the view. The same is being used to list the roles on the view.

You must have noticed that we have also added a Delete link against each Role so that we can delete a role too. The Delete link passes the Role name as querystring to the RoleDelete method of the controller, lets see that too.

Delete a Role in ASP.NET MVC


To delete a role, we have just created a method in the controller named "RoleDelete" and making sure that it gets executed only when an Admin user is trying to browse it.

        [Authorize(Roles = "Admin")]
        public ActionResult RoleDelete(string RoleName)
        {
            
                Roles.DeleteRole(RoleName);
                // ViewBag.ResultMessage = "Role deleted succesfully !";
            
            
            return RedirectToAction("RoleIndex", "Account");
        }
This method takes "RoleName" as parameter and calls Roles.DeleteRole method to delete a role.

Note that there is no method in the Roles class called "EditRole" or "UpdateRole" so be careful while creating a new role and deleting a new role.


Assigning a Role to the User in ASP.NET MVC


Now, lets see how to assign a role to the user, to do that we have created a simple form that has a TextBox to accept username and a DropDown that lists all the roles from the database and it looks like below. In the same view, we have also created another form that accepts username and list all the roles associated with that username.

@{
    ViewBag.Title = "Role Add To User";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<div class="spacerBody">
    &nbsp;</p>
    @Html.ActionLink("Create New Role", "RoleCreate") | @Html.ActionLink("Roles", "RoleIndex")
        

Role Add to User</h2> @using(Html.BeginForm("RoleAddToUser", "Account")){     @Html.AntiForgeryToken()     @Html.ValidationSummary(true)    
@ViewBag.ResultMessage</
div>             Username : @Html.TextBox("UserName")         Role Name: @Html.DropDownList("RoleName", ViewBag.Roles as SelectList)             </p>         > } <div class="hr"></div> @using(Html.BeginForm("GetRoles", "Account")){     @Html.AntiForgeryToken()     Username : @Html.TextBox("UserName")         <input type="submit" value="Get Roles for this User" />     </p> }         @if(ViewBag.RolesForThisUser != null) {        

Roles for this user </

h3>    
    @foreach (string s in ViewBag.RolesForThisUser){    
  1. @s</li>   }                 </ol>     </text> }         </div>



    The Controller code for this view page looks like below

            /// 
            /// Create a new role to the user
            /// 

           
    ///
           
    [Authorize(Roles = "Admin")]
           
    public ActionResult RoleAddToUser()
           
    {
               
    SelectList list = new SelectList(Roles.GetAllRoles());
               
    ViewBag.Roles = list;

               
    return View();
           
    }

           
    ///
           
    /// Add role to the user
           
    ///
           
    ///
           
    ///
           
    ///
           
    [Authorize(Roles = "Admin")]
           
    [HttpPost]
           
    [ValidateAntiForgeryToken]
           
    public ActionResult RoleAddToUser(string RoleName, string UserName)
           
    {

                   
    if (Roles.IsUserInRole(UserName, RoleName))
                   
    {
                       
    ViewBag.ResultMessage = "This user already has the role specified !";
                   
    }
                   
    else
                   
    {
                       
    Roles.AddUserToRole(UserName, RoleName);
                       
    ViewBag.ResultMessage = "Username added to the role succesfully !";
                   
    }
               
               
    SelectList list = new SelectList(Roles.GetAllRoles());
               
    ViewBag.Roles = list;
               
    return View();
           
    }

           
    ///
           
    /// Get all the roles for a particular user
           
    ///
           
    ///
           
    ///
           
    [Authorize(Roles = "Admin")]
           
    [HttpPost]
           
    [ValidateAntiForgeryToken]
           
    public ActionResult GetRoles(string UserName)
           
    {
               
    if (!string.IsNullOrWhiteSpace(UserName))
               
    {
                   
    ViewBag.RolesForThisUser = Roles.GetRolesForUser(UserName);
                   
    SelectList list = new SelectList(Roles.GetAllRoles());
                   
    ViewBag.Roles = list;
               
    }
               
    return View("RoleAddToUser");
           
    }
    The first method of above code snippet simply gets all the roles from the database using "GetAllRoles()" method into SelectList and sets into the ViewBag.Roles. The same is being populated as DropDown into the view.

    Clicking on Save method fires the 2nd method that first checks whether this user is already in the selected role, if not then calls "Roles.AddUserToRole" method to adds the username entered into textbox to associate with the role selected in the DropDown.

    Listing Roles associated with a particular user in ASP.NET MVC

    To list roles associated with a particular username, we have created another form in the same view that executes GetRoles method of the controller and calls "Roles.GetRolesForUser" method to get all roles associated with the username entered into the textbox. These roles are converted into SelectList and then set as "Roles into the ViewBag that ultimately renders the roles associated with a particular username.


    How to remove a user from a role in ASP.NET MVC?


    In order to remove a user from a particular role, I have again created a small form in the same above view (RoleAddToUser.cshtml) and here is the view code for this.

        

    Delete A User from a Role


    @using (Html.BeginForm("DeleteRoleForUser", "Account"))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

       

            Username : @Html.TextBox("UserName")
            Role Name: @Html.DropDownList("RoleName", ViewBag.Roles as SelectList)
           
       

       
       
    type="submit" value="Delete this user from Role" />
    }
    Writing the username in the TextBox, selecting a role from the DropDown and clicking Save button submit this form to the DeleteRoleForUser action method in the Account controller.


    In the Account controller, my action method looks like this 

            [HttpPost]
            [Authorize(Roles = "Admin")]
            [ValidateAntiForgeryToken]
            public ActionResult DeleteRoleForUser(string UserName, string RoleName)
            {
    
                    if (Roles.IsUserInRole(UserName, RoleName))
                    {
                        Roles.RemoveUserFromRole(UserName, RoleName);
                        ViewBag.ResultMessage = "Role removed from this user successfully !";
                    }
                    else
                    {
                        ViewBag.ResultMessage = "This user doesn't belong to selected role.";
                    }
                    ViewBag.RolesForThisUser = Roles.GetRolesForUser(UserName);
                    SelectList list = new SelectList(Roles.GetAllRoles());
                    ViewBag.Roles = list;
                
    
                return View("RoleAddToUser");
            }
    In the above code snippet, I am checking whether the given username exists for that role or not, if yes then calling "Roles.RemoveUserFromRole" method. Following code is to write proper message and to make sure that the form is again getting loaded with the default data in the Role DropDown.


    Checking for a particular role before performing any action in ASP.NET MVC


    Now, there might be scenario where you need to check into the code block for a particular role for the  user before performing certain activity, to do that use below code

    if (User.IsInRole("Admin"))
                {
    
                    // Code to execute only when the logged in use is in "Admin" role
    
                }
    The above code gets executed only when the logged in user belongs to "Admin" role.

    Dig more methods of the "Roles" class and you will find many more interesting methods that helps you working with user roles in ASP.NET MVC.


    Conclusion


    Working with roles in ASP.NET MVC default project template is little tricky and this article explains that. Hope this article would be useful for people looking for working with Roles and managing roles in ASP.NET MVC.

    Thanks for reading, do let us know your feedback and share this article to your friends and colleague if you liked. Do vote for this article.

    Could not find a part of the path ... bin\roslyn\csc.exe

    I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added a...