Sunday, 19 January 2014

Customize Password Policy in ASP.Net Identity

Microsoft has released a new version of ASP.NET Identity, 2.0.0-alpha 1. You can refer to ASP.NET Identity Preview to get the idea of this release.
In that context, we are here today to create a MVC application using ASP.NET Identity to customize the password to provide better security to the application. You'll learn here to modify the minimum length of the password and to make the entering of numeric and special characters in the password mandatory and disallow recently used passwords.
By default the ASP.NET Identity requires that the minimum length of the password is 6 characters and here we change it to 8. We'll work on the Visual Studio 2013 version and you must update all the assemblies related to the ASP.NET Identity.
So, let's proceed with the following sections:
  • Create ASP.NET MVC Application
  • Modifying the Minimum Length
  • Customize Password Validation
Create ASP.NET MVC Application
Now we create the MVC application using the following procedure.
Step 1: Open Visual Studio 2013 and click on "New Project".
Create Web Application in VS 2013
Step 2: Select the MVC Project Template to create the application and click "OK".
MVC Project Template in VS 2013
Step 3: In Solution Explorer, right-click on References and click "Manage NuGet Packages...".
NuGet Package Reference
Step 4: Select "Include Prerelease" and search for "Identity". Update all the Identity related packages.
Idenetity in NuGet Package
After this you can see in your Pacakages.Config that all the packages are updated. We can also look at the following points to understand how the user is created in the application. You can see the following code in your AccountController class under the Controllers folder:
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}
  • The Account controller uses an instance of the UserManager class. This takes a UserStore class that has persistence-specific API for user management.
  • The preceding method creates a new user. The call to CreateAsync in turn calls the ValidateAsync on the PasswordValidator property for the password validation.
Modifying the Minimum Length
Now in this section we'll modify the minimum length of the password to 8. The PasswordValidator property is used to set the length, this value can be changed. Proceed with the following procedure.
Step 1: Add a new folder named IdentityExtentions to the project.
Step 2: Add a new class named AppUserManager in this folder.
Adding Class in MVC
Step 3: Replace the class code with the code below.
First add the following assemblies:
using CustomizePasswordApp.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework
Code:
namespace CustomizePasswordApp.IdentityExtentions
{
    public class AppUserManager : UserManager<ApplicationUser>
    {
        public AppUserManager()
            : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
        {
            PasswordValidator = new MinimumLengthValidator(8);
        }
    }
}
Step 4: Now we need to change the AccountController to use the AppUserManager class . Change the constructor code and class property with the highlighted code below:
public class AccountController : Controller
{ 
    public AccountController()
        : this(new AppUserManager())
    {
    }
    public AccountController(AppUserManager userManager)
    {
        UserManager = userManager;
    }

    public AppUserManager UserManager { get; private set; }
Step 5: Build the solution and run the application. Now try to register a new user. If the password length is less then 8, you'll get the error as shown below:
Password Validation in MvcApp Registeration
Customize Password Validation
As mentioned above now we'll customize the password in this section. Use the following procedure to do that.
Password must have one special and one numeric character
Step 1: Add a new class named CustomizePasswordValidation in the IdentityExtensions folder.
Step 2: Replace the code with the code below:
using Microsoft.AspNet.Identity;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CustomizePasswordApp.IdentityExtentions
{
    public class CustomizePasswordValidation : IIdentityValidator<string>
    {
        public int LengthRequired { get; set; }

        public CustomizePasswordValidation(int length)
        {
            LengthRequired = length;
        }

        public Task<IdentityResult> ValidateAsync(string Item)
        {
            if (String.IsNullOrEmpty(Item) || Item.Length < LengthRequired)
            {
                return Task.FromResult(IdentityResult.Failed(String.Format("Minimum Password Length Required is:{0}", LengthRequired)));
            }

            string PasswordPattern = @"^(?=.*[0-9])(?=.*[!@#$%^&*])[0-9a-zA-Z!@#$%^&*0-9]{10,}$";

            if (!Regex.IsMatch(Item, PasswordPattern))
            {
                return Task.FromResult(IdentityResult.Failed(String.Format("The Password must have at least one numeric and one special character")));
            }

            return Task.FromResult(IdentityResult.Success);
        }
    }
}
In the code above, the ValidateAsync method is used to check the password length at first and then by the regular expression we can check whether or not the password entered satisfys the requirements.
Step 3: Now we need to provide this validator in the PasswordValidator property of the UserManager. Open the AppUserManager class and change the PasswordValidator property as shown below:
public class AppUserManager : UserManager<ApplicationUser>
{
    public AppUserManager()
        : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
    {
        PasswordValidator = new CustomizePasswordValidation(8);
    }
}
Step 4: Run the application and register a new user that does not meet the requirements.
Custom Password Validation in MVC 5
Password cannot be reusable
While changing the password, we can prevent the user from entering the previous password. Use the following procedure to do that.
Step 1: Open the IdentityModels.cs in the Models folder and create a new class named UsedPassword and change the code with the highlighted code as shown below:
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CustomizePasswordApp.Models
{
    public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
            : base()
        {
            UserUsedPassword = new List<UsedPassword>();
        }

        public virtual IList<UsedPassword> UserUsedPassword { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }

    public class UsedPassword
    {
        public UsedPassword()
        {
            CreatedDate = DateTimeOffset.Now;
        }

        [Key, Column(Order = 0)]
        public string HashPassword { get; set; }
        public DateTimeOffset CreatedDate { get; set; }
        [Key, Column(Order = 1)]
        public string UserID { get; set; }
        public virtual ApplicationUser AppUser { get; set; }
    }
}
In the preceding we used the UserUsedPassword property to hold the list of used passwords.
Step 2: Now we need to store the password hash in the history table when the user is created for the first time. We need to override the existing UserStore now because since the UserStore does not define such a method separately to store the password history. So, add a new class in the IdentityExtensions folder named AppUserStore and add the following code:
using CustomizePasswordApp.Models;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Threading.Tasks;

namespace CustomizePasswordApp.IdentityExtentions
{
    public class AppUserStore : UserStore<ApplicationUser>
    {
        public AppUserStore(DbContext MyDbContext)
            : base(MyDbContext)
        {
        }

        public override async Task CreateAsync(ApplicationUser appuser)
        {
            await base.CreateAsync(appuser);
            await AddToUsedPasswordAsync(appuser, appuser.PasswordHash);
        }

        public Task AddToUsedPasswordAsync(ApplicationUser appuser, string userpassword)
        {
            appuser.UserUsedPassword.Add(new UsedPassword() { UserID = appuser.Id, HashPassword = userpassword });
            return UpdateAsync(appuser);
        }
    }
}
In the code above The AddToUsedPasswordAsync() method stores the password in the UsedPassword table separately.
Step 3: Now we need to override the ChangePassword and ResetPassword methods in the AppUserManager class with the following code:
public class AppUserManager : UserManager<ApplicationUser>
{
    private const int UsedPasswordLimit = 3;

    public AppUserManager()
        : base(new AppUserStore(new ApplicationDbContext()))
    {
        PasswordValidator = new CustomizePasswordValidation(8);
    }

    public override async Task<IdentityResult> ChangePasswordAsync(string UserID, string CurrentPassword, string NewPassword)
    {
        if (await IsPreviousPassword(UserID, NewPassword))
        {
            return await Task.FromResult(IdentityResult.Failed("You Cannot Reuse Previous Password"));
        }

        var Result = await base.ChangePasswordAsync(UserID, CurrentPassword, NewPassword);

       if (Result.Succeeded)
       {
           var appStore = Store as AppUserStore;
           await appStore.AddToUsedPasswordAsync(await FindByIdAsync(UserID), PasswordHasher.HashPassword(NewPassword));
        }

        return Result;
    }

    public override async Task<IdentityResult> ResetPasswordAsync(string UserID, string UsedToken, string NewPassword)
    {
        if (await IsPreviousPassword(UserID, NewPassword))
        {
            return await Task.FromResult(IdentityResult.Failed("You Cannot Reuse Previous Password"));
        }

        var Result = await base.ResetPasswordAsync(UserID, UsedToken, NewPassword);

        if (Result.Succeeded)
        {
            var appStore = Store as AppUserStore;
            await appStore.AddToUsedPasswordAsync(await FindByIdAsync(UserID), PasswordHasher.HashPassword(NewPassword));
        }

        return Result;
   }

   private async Task<bool> IsPreviousPassword(string UserID, string NewPassword)
   {
       var User = await FindByIdAsync(UserID);

       if(User.UserUsedPassword.OrderByDescending(up=>up.CreatedDate).Select(up=>up.HashPassword).Take(UsedPasswordLimit).Where(up=>PasswordHasher.VerifyHashedPassword(up, NewPassword) != PasswordVerificationResult.Failed).Any())
       {
            return true;
       }

       return false;
    }
Step 4: Now register the local user as specified by the validation requirements.
Register in MVC Application
Step 5: Change the password using the same password when the user is created. You'll see the error message as shown below:
Change Passeord in MVC Application
Summary

This article described how to customize the validation using the ASP.NET Identity and apply various policies in the application. Thanks for reading.

ADO.NET Entity Data Model in ASP.Net Scaffolding

The ADO.NET Entity Data Model designer provide a Graphical User Interface tool to design the Entity Framework Models. We'll create and modify the entities, associations and inheritance relationships with the Entity Designer and we can also validate the model.
In that context, we'll today work on this session to create an Entity Model and use it in the application.
So, let's proceed with the following sections:
  • Application Creation
  • Working with Entity Model
  • Working with LocalDb
Application Creation
Create an ASP.NET Web Application in the MVC Project Template in Visual Studio 2013.
Working with Entity Model
Step 1: Just right-click on the Models folder to add an ADO.NET Entity Data Model named College.
Step 2: In the next wizard, select "Entity Model".
Create Entity Model
Step 3: The designer opens a blank model in which we add the entities. Just right-click on the designer to open "Properties".
Data Model Properties
Step 4: Set the Entity Container Name to CollegeDbContext as shown below:
Entity Container Name in Properties
Step 5: Right-click on "Design" then select "Add New" -> "Entity...".
Adding New Entity in DataModel
Step 6: In the next wizard enter the entity name as College and CollegeId as the key column name and click "OK".
Add Entity in Model
Step 7: Right-click on Entity to add a Scalar Property to it.
Adding Scalar Property of Entity
Step 8: Create the Name property also. Now add an another entity name Student and do the same as done above.
Step 9: Now right-click on design then select "Add New" -> "Association...".
Add Association in Entity Model
Step 10: Ensure that your wizard looks as below and click "OK".
Adding Assocaiation of Model
Working with LocalDb
Step 1: Open the Generate Database from Model by right-clicking on the design surface.
Generate Database Model
Step 2: In the next wizard click on New Connection and do as shown below:
Add Connection with LocalDb
Step 3: Click "OK" and if the wizard opens to create a new database, select "Yes".
Step 4: Select "Next" and the designer calculates to create the script of the database schema. Ensure that the Entity Connection Settings in the Web.Config option is checked.
Generate Database Wizard
Step 5: Click on "Finish" and the script opens. Right-click and select "Execute".
Execute Script of Database Schema
Step 6: Build your project. The Entity Designer creates two classes named College and Student and a model is added to your Models folder.
Step 7: You can now use the new ASP.NET Scaffolding as usual for the EDMX generated models. Now you can use your newcontext as a Data Context class while scaffolding as shown below:
Add Controller Scaffolding in MVC
Summary

This article will help you to create an Entity Model using the ADO.NET Model Designer and you can also use the new EDMX models in a ASP.NET Scaffolding. Thanks for reading.

Convert Text To Lowercase Letters Using AngularJS

In this article I will tell you how to convert text into lowercase letters using AngularJS.
AngularJS provides a feature by which you can convert all the letters of some text into uppercase letters or uppercase letters can be converted into lowercase letters. I will explain this with a sample application.
Step 1
First of all you need to add an external Angular.js file to your application, "angular.min.js".
For this you can go to the AngularJS official site or can download my source code and then fetch it or you can click on this link and download it: ANGULARJS.
After downloading the external file you need to add this file to the Head section of your application as in the following:
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
</head>
Step 2
Now after adding the External JS file the first thing you need to do is to add ng-app in the Tag otherwise your application will not run.
<html ng-app xmlns="http://www.w3.org/1999/xhtml">
Now I will create a simple application that will help you understand this feature.
First I will create a JavaScript function in which some initial values will be passed.
   <script>
        function x($scope) {
            $scope.test = "this text will be displayed in Uppercase";
            $scope.test1 = "THIS TEXT WILL BE DISPLAYED IN LOWERCASE";
        }
    </script>
Here I have created a function named "x". In that function some initial values are passed to variables named "test" and "test1", the text provided in the "text" will be converted into uppercase letters but as you can see, at this point all the letters are in lowercase letters. Similarly text provided in the "text1" will be converted into lowercase letters but right now they are in capital letters.
Step 3
Our work on the View is complete. Now I will work on the View Model of this application.
<body>
    <form id="form1" runat="server">
    <div ng-controller="x">
    Without Lowercase:- <p>{{test1}}</p>
        <br />
    With Uppercase:- <p>{{test|uppercase}}</p>
    </div>
    </form>
</body>
Here a Div is created that is bound to the function using the ng-controller.
In this Div two tags are taken, the first one is bound to the initial value of test1 but right now nothing special is done so it will not convert the data into lowercase. The second tag is bound to the "test" but along with it "uppercase" is also written so it will convert the text into the uppercase letters.
If at this time I run the application then output like this will be seen:
convert into lowercase using AngularJS
Nothing is converted to lowercase, that's because I have not applied anything to convert it but now I will add one more tag and will convert the text to lowercase.
<body>
    <form id="form1" runat="server">
    <div ng-controller="x">
    Without Lowercase:- <p>{{test1}}</p>
        <br />
    With Uppercase:- <p>{{test|uppercase}}</p>
        <br />
    With Lowercase:- <p>{{test1|lowercase}}</p>
    </div>
    </form>
</body>
In the third tag you can see that I had again bound the initial value but with it one more thing is written, lowercase, this should be written in this format: {{ lowercase_expression | lowercase}}. Now if I run the application then output like this can be seen:

Complete Code
The complete code of this application is as follows:

<html ng-app xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <script>
        function x($scope) {
            $scope.test = "this text will be displayed in Uppercase";
            $scope.test1 = "THIS TEXT WILL BE DISPLAYED IN LOWERCASE";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div ng-controller="x">
    Without Lowercase:- <p>{{test1}}</p>
        <br />
    With Uppercase:- <p>{{test|uppercase}}</p>
        <br />
    With Lowercase:- <p>{{test1|lowercase}}</p>
    </div>
    </form>
</body>
</html>

Best Programming Language Analysis 2014

For some people, the best programming language is the one that earns them the most money. For some it is the one that can be used to build the coolest stuff. For some, it is the language that is in high demand and can get them a job quickly. So, you need to ask yourself a question. What do you mean by “the best”? What is your goal?
Is your goal to get paid more? Or build cool stuff? Or be in high demand? Or anything else? For example, you can see COBOL is a high-paid language but it may not be in high demand. On the other hand, you can say, WordPress and PHP developers are in high demand but that may not fetch you a great paying job. So “the best” is all relative.
In this article, I will discuss various aspects of various programming languages and their demand.
Most Popular Language
If you look at the Most Popular Programming Languages over the past decade or so, you will find that C, C++ and Java are the top 3 languages. Based on the research and statistics by Udemy, TIOBE, and langpop, the following list may be used to list the top 10 most-used programming languages.
  • Java
  • C
  • C++
  • C#
  • Objective-C
  • PHP
  • Python
  • Ruby
  • SQL
  • JavaScript 
But the purpose of this article is not to talk about the Most Popular Programming Language but to determine the best programming language for you.
Most Demanding Language in 2013
Let’s have a look at the most demanding languages of 2013. ComputerWorld published a report on June 11, 2013 of the top 10 programming languages that are in demand by employers in major US cities.
Language Job Count City
SQL 98,454 New York, DC, San Francisco, Boston, Chicago
Java 66,485 New York, DC, San Jose, San Francisco, Boston
HTML 45,456 New York, DC, San Francisco, Boston, LA
JavaScript 43,189 New York, DC, San Francisco, Boston, Silicon Valley
C++ 32,018 Santa Clara, Seattle, New York, San Francisco
C# 31,936 Seattle, New York, Boston, Chicago, Atlanta
XML 31,431 DC, New York, San Francisco, Boston, Atlanta
C 24,801 Santa Clara, Seattle, New York, San Francisco, San Diego
Perl 20,579 San Jose, New York, Seattle, San Francisco, Boston
Python 19,627 Mountain View, San Francisco, New York, Seattle, Boston
Structured Query Language (SQL) may not be a fully functional programming language but has been in demand more than any other language in year 2013. And it is very obvious due to data processing and demand. The demand of a language changes from year to year and from city to city. As you can see from the preceding table, C# language is in most demand in Seattle. The reason is obvious. Microsoft is the biggest employer in Seattle area. Similarly, if you look at the last item in the preceding table, Python is the most demanded language in Mountain View. So it all depends on the location, the project type and the interest. If your interest is in working with a mobile startup, you may not find C or C# attractive compare to Objective-C or if your goal is to make more money, C# may be the way to go.
Best Paid Language
Programmers’ salaries usually depend on several factors such as the location, experience, skills, and company. For example, Juniper Networks in the same city pays a lot more than Microsoft for same experience and skillset.
Let’s refer to a list ComputerWorld published on June 11, 2013 on the top 10 most paid programming languages in major US cities.
Language Average Salary City
Java $95,000 New York, DC, San Jose, an Francisco, Boston
C++ $94,000 Santa Clara, Seattle, New York, San Francisco
C $93,000 Santa Clara, Seattle, New York, San Francisco, San Diego
Perl $93,000 San Jose, New York, Seattle, San Francisco, Boston
XML $92,000 DC, New York, San Francisco, Boston, Atlanta
C# $91,000 Seattle, New York, Boston, Chicago, Atlanta
SQL $90,000 New York, DC, San Francisco, Boston, Chicago
JavaScript $88,000 New York, DC, San Francisco, Boston, Silicon Valley
Python $83,000 Mountain View, San Francisco, New York, Seattle, Boston
HTML $81,000 New York, DC, San Francisco, Boston, LA
As you can see from the preceding table, Java is the best-paid language. But it does not mean that you can’t make more money in C#. There may be some companies that may pay more to a C# developer than a Java developer. For example, in the Philadelphia area, there is high demand of senior .NET developers, they can earn pretty much more than an average salary. It also depends on how badly a company needs a skilled developer.
Most Exciting Language
So you like excitement? Excitement is all about building cool and cutting-edge solutions. Today, Mobile, Big Data, and Cloud are in very much demand.
 
Mobile development was the most demanding skillset in 2013. As you can see from the stats published by StatCounter, Android leads all the mobile platforms followed by iOS. Obviously, Java and Objective-C will be the most demanding languages for the mobile development.
Most Versatile Language
Out of the preceding listed programming languages C, C++, Java and C#, probably the most versatile among them all are C++ and C#. Using C#, you can develop Windows client applications, Web applications, components, Windows Store apps, Windows Phone app, Enterprise, and even iOS and Android mobile applications. The details of this topic I will cover in my next article titled, What C# can do for you. Stay tuned!
Conclusion

The best programming language is all relative to you. It depends on what your goal is. In this article, we talked about various aspects of programming languages. Clearly, Mobile, Big Data, Wearable and Cloud are the leading trends for 2014. It will be interesting to see where 2014 goes from here. I hope you liked this article. I definitely would love to hear what your take is on this article as well as some programming languages you may have used.

Friday, 17 January 2014

database msdb cannot be opened it has marked suspect by recovery

Hello Freinds,
 today i am facing a serious error in sql server database
 when i open sql server management studio first it will not logging from my sa user account, then i will logged in from window authentication, then i was expand my database it will shown a error.....

Database 'msdb' cannot be openned. It has been marked SUSPECT by recovery.


First I have tried starting SQL Server exe with the following parameters
which has not allowed me to login to the server.

-c -m
-c -T3806

but sql server not started.

i was just the find the solutions of it 
Simple way to resolve the "msdb cannot be opened. it has been marked suspect by recovery" issue,just run the INSTMSDB.SQL script, which is under SQL server install directory under INSTALL folder.
This script can be re-run WITHOUT causing loss of data, hence we only create the database if it missing (if the database already exists we test that it has enough free space and if not we expand both the device and the database)