Friday 1 July 2016

Twitter authentication for ASP.NET MVC Wb Application

Here we will how to use Twitter login for our asp.net mvc application . Now in these days all the commercial website use external login facility means user can login to their website using Twitter  , google, twitter etc. Like Flipkart,amazon.
So here will learn how to give login using Twitter .
 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 “TwitterLoginMVCApplication”.

 

 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


AuthConfig file in Asp.net MVC application
This AuthConfig file is exist under “App_start”s folder. It is automatically created by the asp.net mvc application when we create a project.

This AuthConfig.cs file contains the entire external client as comment by default. So we need to uncomment for auth config for Twitter then the code we like following


At this time if you will run your application it will give error that you can’t be put empty value for “appID,secreted”. For that we need to register in Twitter.
Register MVC application with Twitter
Before run mvc application we have to pass consumerKey and consumerSecret so for that we need to register in Twitter or login if you have account in Twitter ,after login go to the following URL and register there. There will be register button at right click side at top.
For creating your own twitter app on twitter then go to following Url
https://apps.twitter.com/
 When you will redirect to this link you will see following screen


Here click on Create new app ,it will redirect to the create application form there you fill information like
1.   First you give your app name ,in my case it is “TwitterAppForMvcApplication”.
2.   Give the description as “twitter for mvc application”.
3.   Now third thing is to pass URL of our application ,in my case url of my application is

4.   Next is CallBack url which is not a mandatory.



After filling all these information then click on accept agreement and click on “create twiiter app”.
It will redirect to following screen there you will see that your application app is created.









Now click on Keys and Access Tokens tab to get your [ consumerKey: "" and, consumerSecret: "" ]


Copy your “consumerSecret” and “consumerKey” and paste in your application in AutthConfig File , It is under App_start folder.

Now run your application and you will see following screen




Click on Twitter link ,it will redirect to the twitter authentication Login page there you give your twitter credential (if you already login then it will redirect to the authorize page) now click on the Authorize app button

and then you it will redirect to ExternalLoginCallback  page there you will see a textbox with the username which is taken from your twitter account, Now click on register button after that you can login your application using the twitter


Now check the database table (UserProfile) for checking that current twitter account user is added

now check that authentication membership in database table ("webpages_OAuthMembership") for  new account

all the data added successfully to the database, this is the way to authenticate your mvc website with twitter account.

Friday 13 May 2016

Facebook authentication for ASP.NET MVC Wb Application

Here we will how to use facebook login for our asp.net mvc application . Now in these days all the commercial website use external login facility means user can login to their website using facebook , , google, twitter etc. Like Flipkart,amazon.
So here will learn how to give login using facebook.
 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 “FacebookLoginMVCApplication”.

 

 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

AuthConfig file in Asp.net MVC application
This AuthConfig file is exist under “App_start”s folder. It is automatically created by the asp.net mvc application when we create a project.

This AuthConfig.cs file contains the entire external client as comment by default. So we need to uncomment for auth config for faceBook then the code we like following



At this time if you will run your application it will give error that you can’t be put empty value for “appID,secreted”. For that we need to register in facebook.
Register MVC application with facebook
Before run mvc application we have to pass appID and secret id so for that we need to register in facebook or login if u have account in face,after login go to the following URL and register there. There will be register button at right click side at top.
"http://developers.facebook.com/"
After register you need to create Appid for your website ,it will redirect to that page after register or you can go to following URL and fill the information which it is asking like following snapshot.
https://developers.facebook.com/apps/
From here click on create new App id it will open a window like following


There I gave display name as "dotnetmunesh" and Email and category i select as “Education and after that click on create App ID.
After click on this ,your account will be created and it will redirect to following page where it will ask security answer for selecting image


After selecting click ok then a window will open

Here you can see your app id and Appsecret on Dashboard section. Now go to setting and on basic section enter field , and app domain as empty after that click on add platform and select website.
When you will click on add flat form following window will open


From here you have to select Website.
After selecting add platform a small panel will popup asking Site URL here you will be adding your project URL like http://localhost:63695/.To see where project URL is just right click on Project then select Properties like as shown below.
After selecting Properties a new window will open inside that select Web Menu just below Build at bottom of page you will see Project URL which we highlighted in yellow here project URL like http://localhost:63695/.Just copy that URL.


After copying just paste that URL inside Site URL (http://localhost:63695/)and then click on save changes button.

After that just copy App ID and App Secret and just add in AuthConfig.cs files.


After adding just save your application then Run application. Following is our login page after adding oAuth facebook login in asp.net mvc applicaition.


Here you will see a Facebook button on right part of login page. Now just click on this Facebook button then it will redirect you to Facebook login page ,here you enter Facebook credentials and then login in to Facebook.
After login in to Facebook now new dialog will pop up for allowing App to take your all profile information which you provide in facebook (like name, profile picture, age range, gender etc). Now just click on Okay button to proceed further.


After clicking on okay button it will redirect to "ExternalLoginCallback" view and on that page we will see Username textbox which contains Username (Munesh Sharma) which we have got from Facebook Oauth service. 

 now just click on Register button and you are login in to your web application. 

The user name with facebook is successfully saved in UserProfile table and second table which  is webpages_OAuthMembership table.

you can download this project from here Download




Thursday 12 May 2016

Cross-site Request Forgery in Asp.Net MVC

Here will learn what Cross- site Request forgery in Asp.net mvc  ,and how to protect our asp.net mvc application from the CSRF.Cross- site Request forgery is abbreviated as “CSRF”.
What is CSRF
CSRF is a attack in which a user login to a website like ABC.Com and after login user open other site called malicious site in other tab, then this malicious site send request to (ABC.com) valid site using existing credential or existing session for attacking the site, Valid site( ABC.com) assume that this coming request is a valid request or coming from a valid user , So it execute that request and site is hacked by the CSRF.

After recognizing this attack ,Microsoft provide a Attribute called “AntiForgeryToken”.  It is very simple to use in our site ,just we need to add “@Html.AntiForgeryToken” in view with that we need to add this in controller also as a attribute [ValidateAntiForgeryToken] to validating this. Basically AntiForgeryToken is used in HTTPPost method.
Now we learn this with a example using asp.net mvc
Go to visual studio and create a new project and select a Asp.net MVC4 web application and give the name for project ,in my case it is  “CSRFInMVCApplication” after that click ok then a window will open from there select a template as “Besic” and view engine as “Rezor”.




After click ok it will create a project, After that right click on model folder and add a class name is “CollageInfo.cs”  ,and write the following code to this class
  public class CollageInfo
    {
        [Key]
        public int CollageID { get; set; }
        [Required(ErrorMessage = " please Enter Name")]
        public string CollageName { get; set; }
        [Required(ErrorMessage = "pleaes Enter Address")]
        public string CollageAddress { get; set; }
        [Required(ErrorMessage = "please Enter Department")]
        public string CollageDepartment { get; set; }

    }

After completion of model class we need to add a controller to this project so for that right click on the controller folder and a controller and give the name as “CollageController” with Empty MVC Controller template.


After adding controller we need to add action method name is “collageInfo” with [HttpGet] and [HttpPost]. So for that write the following code in controller collageInfo action method.
        [HttpGet]
        public ActionResult collageInfo()
        {
            return View();
        }

        [HttpPost]
        public ActionResult collageInfo(CollageInfo _clgInfo)
        {
            return View(_clgInfo);
        }

After adding the action method we need to add the view , for adding the view right click on the collageInfo action method and add the view like following


After click on  add it will generate code for the view ,following is the code for the view
@model CSRFInMVCApplication.Models.CollageInfo

@{
    ViewBag.Title = "collageInfo";
}

<h2>collageInfo</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>CollageInfo</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.CollageName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CollageName)
            @Html.ValidationMessageFor(model => model.CollageName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CollageAddress)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CollageAddress)
            @Html.ValidationMessageFor(model => model.CollageAddress)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CollageDepartment)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CollageDepartment)
            @Html.ValidationMessageFor(model => model.CollageDepartment)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Now run your application, go to the following URL and see the output
http://localhost:50688/Collage/Collageinfo

Right click on this page and click on View Source ,you will see source code of this page and save this code as .HTML file
After saving this file as .HTML ,Now open this file(.HTML)

Code for HTML file is
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>collageInfo</title>
    <link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.6.2.js"></script>

</head>
<body>
   

<h2>collageInfo</h2>

<form action="http://localhost:50688/Collage/Collageinfo" method="post">    <fieldset>
        <legend>CollageInfo</legend>

        <div class="editor-label">
            <label for="CollageName">CollageName</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-required=" please Enter Name" id="CollageName" name="CollageName" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="CollageName" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="CollageAddress">CollageAddress</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-required="pleaes Enter Address" id="CollageAddress" name="CollageAddress" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="CollageAddress" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="CollageDepartment">CollageDepartment</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-required="please Enter Department" id="CollageDepartment" name="CollageDepartment" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="CollageDepartment" data-valmsg-replace="true"></span>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
</form>
<div>
    <a href="/Collage">Back to List</a>
</div>



    <script src="/Scripts/jquery-1.8.2.js"></script>

   
    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>





</body>
</html>
Now double click on html file and enter some data then click on “Create” ,this window will be same like view.
now enter some data and click on “create” button .


now enter some data and click on “create” button .


When you click on create button, you will see that this is redirecting to action method “CollageInfo” this wrong ,its called CSRF attack.
To prevent from this attack Microsoft provide us  a keyword name “@Html.AntiForgeryToken() “ For view ,we have to add this keyword as shown below

After this we need to add a attribute to action method attribute is  [ValidateAntiForgeryToken]

Now if you will run your HTML file and will click on create button it will give error name is
required anti-forgery form field "__RequestVerificationToken" is not present
Like this we can prevent from this CSRF attack.


you can download this project from here Download


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...