Monday, 9 May 2016

Display Roles for the users in Asp.Net MVC Membership


Before proceeding to this tutorial please go to Asp.Net MVC Membership Provider
In previous tutorial we learned how to use membership provider in asp.net mvc.Here we will learn how to Display Roles for the users in Asp.Net MVC Membership.
First proceeding to this we need to add a class or we need a model name is Role. Add this role model inside the account model.
Add the following code to the account model.cs class
[Table("webpages_Roles")]
public class Role
{
[Required(ErrorMessage = "Enter Role name")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string RoleName { get; set; }

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
}

 After creating this Role model we need to add a Acton method name RoleCreate  for HttpPost and HttpGet , so for that write following code in account controller
[HttpGet]
public ActionResult UserRole()
{
return View(new Role());
}

[HttpPost]
public ActionResult UserRole(Role role)
{
return View(role);
}


After creating action method for Role we need to add a view for this, For adding view right click on the “UserRole” action method a window will open there you select model class as Role model and select scaffold template as Create,And after selecting all these click on Add.


It will add a view for you and you will see this view under the account folder in View.


Now run your application and login to the page which you created account before. After login to account ,navigate to the following URL
http://localhost:50526/Account/UserRole
 When you will hit this URL it will go to userRole view and page will look like this

After making this view we need to insert role to database so for that we need to add code to insert data into database , so for that  we need to add code in HttpPost method of UserRole action method.
Inside this action method there is a property name is [Roles.RoleExists(role.RoleName) ]to check that this Role is already exist or not in database ,  it return Boolean value. So write the following code in UserRole Action method.
     [HttpPost]
        public ActionResult UserRole(Role role)
        {
            if (ModelState.IsValid)
            {
                if (Roles.RoleExists(role.RoleName))
                {
                    ModelState.AddModelError("Error", " This Rolename already exists");
                    return View(role);
                }
                else
                {
                    Roles.CreateRole(role.RoleName);
                    return RedirectToAction("RoleIndex", "Account");
                }
            }
            else
            {
                ModelState.AddModelError("Error", "Please enter proper Username and Password");
            }
            return View(role);
        }

So far we created Role for the user. Now  we will learn how to assign role to the user.
Assign Roles to the user And Display the Role
For displaying all the user role we will use code first approach so for that we have to creaet a class name is “userContext”  which will be inherited from the “DbContext” class .If you are internet application then is it already exist in account model at top. Code for this class is like following
public class UsersRoleContext : DbContext
    {
        public UsersRoleContext()
            : base("DBConnectionForMembership")
        {
        }

        public DbSet<Role> UserRoles { get; set; }
    }

DBConnectionForMembership is the connection string name which we defined in web config file.
Now we need to add action method for displaying the role of users and add a action methos in account controller class name is “DisplayRoleForUsers”.
  [HttpGet]
        public ActionResult DisplayRoleForUsers()
        {
            IEnumerable<Role> ListRoles;
            using (UsersRoleContext db = new UsersRoleContext())
            {
                ListRoles = db.UserRoles.ToList();
            }
            return View(ListRoles);
        }

After adding action method ,now need to add view for displaying the role of user so for that right click on DisplayRoleForUsers action method add a view without creating strongly typed view.


Now this view will create a empty view and for showing role of user we need a grid.
Adding MVC Grid to application
For adding grid to the application right click on the application and select “Nuget package manager”


After click on nugget packet manager a window will open  there you search “Grid.Mvc” under online panel. And install this grid to the application.
After adding grid to the application go the “DisplayRoleForUsers” view
Add grid.mvc to this view

Write the following code to this view
@model IEnumerable<MvcMembershipProvider.Models.Role>
   
@using GridMvc.Html
@{
    ViewBag.Title = "Display roles for users";
}

<h2>DisplayAllRoles</h2>

<link href="~/Content/Gridmvc.css" rel="stylesheet" />
<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/gridmvc.js"></script>

@Html.Grid(Model).Columns(columns =>
{
    columns.Add(c => c.RoleId).Titled("Role ID").SetWidth(300);
    columns.Add(c => c.RoleName).Titled("RoleName").Filterable(true).SetWidth(300);
}).WithPaging(5).Sortable(true)


 Now run you application and go to the followinf URL and see the output
http://localhost:50526/Account/DisplayRoleForUsers





Download this project from this link Downlaod

Saturday, 7 May 2016

Asp.Net MVC Membership Provider


Here we will learn how to use membership provider in asp.net mvc, and how to create users, and their roles using asp.net mvc membership, with this we will also learn how to assign roles to users in asp.net mvc membership provider, and how remove users from roles, after getting all roles users from asp.net mvc membership and we will implement security in asp.net mvc applications with examples.
To making security in asp.net mvc application use the following method to create the security in asp.net mvc application

(1) Authentication And Authorization in asp.net mvc


Authentication: It is the process of checking that the user is valid or not

Authorization: it is the process of checking that the user is applicable for the process or not

(2) Membership providers in asp.net mvc
(3) Roles based authentication for user in asp.net mvc

We will learn how to create a database for the membership provider in asp.net mvc and how to assign role to user, we will create a registration page to understand this
Let’s create a application for membership provider asp.net mvc.
Step (1) : Go to visual studio and click on new project -> a window will open from here select a 'Asp.net MVC4 web application' and give the name for this project in my case I give it as “MvcMembershipProvider “.


 Now click ok and select a template as Internet Application and engine as Razor engine , after sleeting all these click ok. it will click a solution project this will contain .Css file ,script file and MVC application structure.
Step(2) : after creation of application let's create a database for this and give the name for this database i gave it as 'MVCApp' and then add a connection string to the database.
         <connectionStrings>
   <add name="DefaultConnection" connectionString = "Data Source=MUNESH-PC;Database=MVCApp;UID=sa;Password=*****" providerName="System.Data.SqlClient" />
  </connectionStrings>


if you are creating new connection string then existinf connection string in ewb config file we have remove with we have remove a following line of code from the "InitializeSimpleMembershipAttribute.cs" which available in filter folder. because it give double connection existing run time error.
                       // WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

         After adding the connection string to the project now we need to create membership tables to the database but before this go to the models folder and have a look on AccountModels.cs class. this class automatically create when we select mvc application as Internet application

AccountModel.cs class contain following methods.

now for creating membership tables in database initialize the connection in globel.asax . here we will use code first approach for that we need to add following code in this class
For adding data table in database membership we need to add a line of code in Global.asax
WebSecurity.InitializeDatabaseConnection("DBConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

Here namespace for WebSecurity is “using WebMatrix.WebData;

WebSecurity.InitializeDatabaseConnection
Definition for the InitializeDatabaseConnection is
public static void InitializeDatabaseConnection (string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables);

connectionStringName:  It the name of database table where user information stored.        
userTableName: It contain user profile information.        
userIdColumn: this column name of table contain user ID this should be integer.        
userNameColumn: column name of table contain user name. This column is basically used to match profile data of user with membership account data.        
 autoCreateTables: True to indicate that user profile and membership tables should be created if they do not exist; false to indicate that tables should not be created automatically. Although the membership tables can be created automatically, the database itself must already exist.
Now globel.asax page will look like


Now after all this configuration lets run your application and see the ur hoe page and click on register link which is your page right side.
After running your application you go to database and see the table, it will generate following tables for us

When you will click on registration link following screen will open with 3 field .

 we can add more field to this view, for making change in registration view 1st need to add field in database table name is “UserProfile”;

Here we added 3 column as shown above now we need to add these column parameters in registration model ,it is in Account.cs class which is available in Model.
Code for registration model is
    public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [Display(Name = "EmailID")]
        public string EmailId { get; set; }

        [Required]
        [Display(Name = "address")]
        public string Address { get; set; }

        [Required]
        [Display(Name = "Mobile No")]
        public string MobileNo { get; set; }
    }




Add these field in registration view
    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html. PasswordFor (m => m.Password)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword)
            </li>
            <li>
                @Html.LabelFor(m => m.EmailId)
                @Html.TextBoxFor(m => m.EmailId)
            </li>
            <li>
                @Html.LabelFor(m => m.Address)
                @Html.TextBoxFor(m => m.Address)
            </li>
            <li>
                @Html.LabelFor(m => m.MobileNo)
                @Html.TextBoxFor(m => m.MobileNo)
            </li>
        </ol>
        <input type="submit" value="Register" />
    </fieldset>
Now if you will run your application and you will see registration page it will look with new fields.



Now according to this we need to add or handle these field in controller also so for that go to Account Controller and we have to make changes in HTTPPost method of registration Action.
Now the code for this action according to old registration model is
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

Now will make changes in this according to new model
WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                        new
                        {
                            EmailID = model.EmailId,
                            Address = model.Address,
                            MobileNo = model.MobileNo
                        }
                        );
So the code for the Registration action method is
[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                        new
                        {
                            EmailID = model.EmailId,
                            Address = model.Address,
                            MobileNo = model.MobileNo
                        }
                        );
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


Now run your application and go to registration page and enter some data to fields then save it ,data will save in database.  
                




Download this project from this link Downlaod

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...