Authentication in ASP.Net MVC

Hi Friends,

In today’s discussion, we’ll be discussing more about authentication. However,authentication which is not new here, it is basically the same what we have been using with other .net legacy systems, but it’s a good idea to discuss the same here as well. So, let’s get started. So, in a nutshell authentication is basically verifying the users, you don’t want UN-authenticated users to come in and access your portal.
There are 3 ways to do the same with ASP.Net:-
1) Forms Authentication:- so, with this website basically provides a page where in user can enter their user names and passwords and same will get authenticated in the system and then user can land in the portal. we’ll see the same in more detail how to work with the same. Forms authentication relies on cookies by default. so, once user signed in app, will store cookie in the client’s machine browser. so,user don’t need to sign in again during the same browsing session.

2) OpenID/OAuth:- Another technique is that open ID and Open authentication, these are open standards for authentication and authorization respectively and using these means your users don’t need to get himself registered with my membership db, rather same will be taken care by 3rd party provider, 3rd party could be anything like gmail, Facebook,yahoo etc.

3) Windows Authentication:- This is the same approach what we have used earlier. So,am not going to discuss the same in detail.Basically, windows application are being used in Intranet application,where in authentication is taken care by Active Directory. However, in order to get the feel of windows authentication, what you can do is instead of selecting internet application, you can select intranet application, it will give by default all the settings for windows.

Forms Authentication:- So, let’s discuss the same in the MVC perspective. so,when your are creating the any internet application, the project directories will have everything in place which users would be needing to get themselves registered and use all the basics of Forms, it also gives us the capability to override any scenario @ any level. so, all these basic setting provided by accounts folder as shown below.


so, basically when you see inside the authentication code,you will see that Microsoft is using websecurity class to implement the Forms Authentication. so,it’s this class’s responsibility to validate the user’s password. Websecurity in return talks to simpleMembershipProvider. so, in a nutshell membership provider is storing all the user’s credentials to database.  However, we could go ahead and take the ownership of membership controller.we could easily override the same as well. so,basically inside the filters folders, there is a file called “InitializeSimpleMembershipAttribute” as shown below:-


so, if you open up this file and see the same in detail, you will find that, this is written in a generic way, and you won’t need everything in here.the one which really interests you is the below section which initializes the database connection.


so, it takes couple of things, like connection name is DefaultConnection, UserProfile is the name of the table which contains the user information with UserId as in primary key, it also contains that gives username as well. we could override this behavior as well, we could have as many columns as we want, but we atleast need these two columns to store a user and retrieve the same as well.

However, since i already know that am using Forms authentication so, i’ll take this piece of code and run the same from global.asax during application start event.


Now, since i have taken the code here itself i won’t be needing that initialize membership file any more in the filters folder,so i could go ahead and delete the same. However, one more thing is that i would also like to override the UserProfile Table, by having certain more specific column pertaining to my site itself.


so, above is the default implementation of AccountModel file, where i would like to control the behavior of UserProfile table. so, for that to happen i need the same thing to be controlled by our dbContext, not by the EF default dbcontext. so, i can go ahead and delete the same dbcontext. however, we do need UserProfile table and since, this is the one which is my custom code,so i also cut the same from here and create a new class with the name UserProfile as shown below:




Now, inorder to use the same with my dbcontext i need to add the dbset property in my declaration as shown below.


Now, since we have done the change in model class so, we need to do the migartion. Now, when i build the same, it will give couple of errors,1st will be for [initializeMembership], since we have moved this section, so,we could simply delete this section. And the other would be where it is expecting UsersDb initialization, so i would change the same for my dbcontext as shown below:-


now, since i have built the solution. so,now i can go ahead and do the migrations as shown below:-


Now, let’s do some demo with the same. Let’s try to register myself and then login and check, how it is behaving.



Now, once i have registered my self, i will then be redirected to Home page as shown below, with my user name flagging on the top.



however, i could go ahead and do the following things like changing my passwords, logging off from the portal as shown below.


Now, let’s see some other details like table structure and all and where it is getting stored. 149th

so, we can see that User Profile table has been added. there are other tables as well which is pertaining to websecurity. One good way to identify these tables are, these all tables have prefix “webpages_”. Now, if we see the below table,we can see the new column which we have added in the table.


Now, if i open this table and see the record,i could see my name in there.



Now, since i have not supplied any movie while registering the same, hence it didn’t get stored.  However, we could also go ahead and force user to authenticate before they reach specific section of the page as shown below. So, for doing the same we will be using one Action Filter [Authorize] as shown below:



Now, as soon as user will invoke Create action, he needs to get authenticated 1st. so, Authorize could be done @ action level or @ the controller level as well. so,it entirely depends upon you, where and how do you want to put the checkpoint.



so, once i logged in, same will get created. Now,next thing what i could do here, i can associate roles and groups for the user. So, for doing the same i could use, SimpleMembership Provider API. So, i could go ahead and seed membership data just to push sample values in there in the membership table. Below is the code which i need to inject in the Configuration file under the Migrations folder.


Now, i could go ahead and run the powershell command to update the db.



and upon running the same,it gave me below error



so, the problem in this case is explicit configuration that needs to be enabled in the web.config file.


so, just with the above changes in place in the config file,i could run the powershell command successfully. Now,let’s go ahead and apply the authorize attribute in the create Movie section with the user having admin role only.


However, i need to change my view a bit, i need to display the Create Link when the user is Admin as shown below


Now, let’s try the same


so, since i didn’t logged in, so i cannot see create link, however, in the below screen shot,when i logged in, i can see the create Link.



Now,  let’s see open ID and OAuth are things where in we are no managing passwords, these are basically delegated to 3rd party vendor to do authenticate the user. so, this is very beneficial, as it saves lot time while doing registration,if am a gmail user, i can get authenticated my self @ gmail server, and once done, i will get redirected to the portal am on. there could so many other options like Gmail sucha as yahoo, Twitter, LinkedIn, Facebook etc. For using them, we need to get app id and secretkey for the same. so, basically, we need to register our app on their site and get the app key. I’ll be using Gmail here as it is open to use. This doesn’t need any secret key.


so, AuthConfig file resides in App_Start folder, here we just need to supply the appId and secret key, but i just used the Google Account to demo the same. so, with the above change in place, i could go ahead and build the app and then refresh the page, i can see the change.


so, with this i would like to wrap this session. Till then stay tuned and Happy Coding.


1,919 total views, no views today

Paging with ASP.Net MVC

Hi Friends,

In today’s discussion we’ll be adding paging capabilities on our page to enable the user to get the idea of the next present records. To do, the paging in here, we need to rely on the 3rd party component, so we’ll be injecting the same from the nugget as shown below.



now, we’ll start making changes in our code to accommodate the changes, we’ll start with home controller, so instead of returning 10 records, we’ll return all and this paged list api also gives me extension method that i can use in query to get the results, and also html helpers to display the next or previous widgets.


and then, add the extension method in the query as shown below


Now, this was the server side code change, now other changes will be done in UI. so, 1st change would be to return correct model type, because now it has become IPagedList type, so we need to fix the same in our view. Now, in order to take this change effect, i need to add few more namespaces in web.config under views folder as shown below.


Now, in order to take this effect, save everything and restart visual studio.


Now, it has taken the effect. Now, from the index view, we are also rendering partial view, so we need to also go there in the partial view and change the model directive there.



now, inside here, i need to place the pager as shown below



Now, with the above changes in place, when i build the solution and refresh the page, i should be getting a page like below:-



However, CSS in this case needs to be fixed, and this is very easy fix. so if you see your content folder, you will see one pagedlist.css file which is included with pagedList package. so, we just need to include the same in the css package in the bundle and do a build. And then, when we refresh the page, we’ll get a little beautiful pager as shown below.

132th 133th 134th

Now, there is one problem with this, whenever, i click on pager, it redraws the complete page, i just want to update the below div. so, with the below code i would be able to update the above section of div only.

135th 136th


Now, with the above code in place, now the pager will work in a desired way. So, with this i would like to wrap this module, Till then stay tuned and happy coding.

Happy coding

2,052 total views, 2 views today

AJAX with ASP.Net MVC – Part 1

Hi Friends,

In today’s discussion we’ll be looking @ Ajax implementation with ASP.Net MVC. So, before jumping to these let’s see the script organization which in our visual studio solution tree.



Now, here by default Visual Studio put all the scripts under one Scripts folder, so obviously you could go ahead and organize the same as your way. you could update the versions of default scripts provided in there with the help of powershell command. Now, let’s start ajaxify our home page. currently, as shown below the search is pretty simple and synchronous.


Currently i have limited set of movie data, now let’s go ahead and seed data with anonymous movie and director, just to have a hefty set of dataset. so for doing this i’ll go to configuration file and simple run a loop 100 times and populate the data in the db, thats it as shown below



Now, i just need to update the database using powershell command as shown below


Now, i should be able to see more data on my home page.



Now, currently as per query my home page is listing only 10 records, but thats ok if go and search with anony_movie_5


this is listing the correct record, but the fact is am losing the scroll position completely because it’s re-drawing the complete page rather than that searched portion. So, to fix this we’ll be using Ajax.BeginForm, Ajax.BeginForm() is very similar to HTML.BeginForm(). It writes out the form tag and we can instruct what controller, actions and route.


so, here with that ajax options we can tell what actually we want to do, here i have also specified the div to be updated, so that it will draw only that portion which is required. So, basically this div will delimit the area which we want to update.


Now, when i do the above changes and refresh the page, search seems to work but, page gets broken, because entire page is getting redrawn means page is getting embedded inside a page, and this will keep going on. so, basically here what happened is client side worked perfectly, but server side didn’t work appropriately, so server side should know how to respond to respond ajax request, and in case of ajax request how to render the view.


so, to fix the same, i need to do below mentioned changes, 1st i need to do make a partial view and render the same from index view as shown below.


Now, in order to decide from the server side, whether it’s an ajax request or not, one small change i need to do in the home controller as shown below:


Now, with this code in place, let me just go ahead and refresh the page.


However, we could go ahead and do the same async search with our custom script with the form tag. so, if you see the page source of the page, you will find data- attribute which is basically html 5 specifications,  so i could go ahead and add as many data- attribute as shown below. so, this will also work when java script is disabled.




so, here i have added some of my custom data- attribute and and action method just to make sure that this form has an action attribute, so am using the url helper to generate a url to a controller action. Now, we need our custom script to read these data- attributes. so, for that i’ll simply add one javascript file in the scripts folder and call it movies. so, this javascript file i’ll be using everywhere so i’ll include the same in layout page. However, there are other ways also to include javascript in the pages like with bundling and minification. But, am skipping that topic for now. I’ll cover the same in different segment. so, below is the custom script doing the same job. Why used is this, because it’s easy to extend and update the same.


so, with this i would like to wrap, in the next session, we’ll see more ajaxification and more about using paging and all. Till then, stay tuned and happy coding.

Happy Coding

1,872 total views, 1 views today

Stateless Path drawing based on incoming data

Hi Friends,

I was recently working on one assignment where in we need to draw the flow of inventory movements based on the incoming data from the database. These datasets have to configured based on the routes coming from the database. Also, the case is values coming from database are redundant as well, so the algorithm has to be smart enough to figureout which route has been drawn and if same is getting repeated, then skip that part for the next time.

For making the same i have used one open API by google (, then modified the built in api based on my requirement. It’s a fairly, good combination of server side and client side projection. Below, is the sample code which i have used for the same.


Happy Coding

1,859 total views, 1 views today

.Net Fiddle Came out

Hi Friends,

Today, i came to know about this fiddle, hence thought to blog about the same. It’s really interesting to see .Net Fiddle in action. it’s entirely like JSFiddle. Now, you can test your snippets anywhere, anytime. I’m Loving it.

.Net Fiddle

Happy Coding

1,384 total views, 2 views today

Adding CRUD Functionality to the Movies DB.

Hi Friends,

In today’s discussion, we’ll talk more about adding CRUD functionality in our application. So, let’s get started. But, i’ll be doing all these sort of things on a new link, let’s say Movies Link. so, the 1st thing is i’ll be modifying the layout links as shown below and then creating the view accordingly.



Obviously, we would be needing Movies controller, so let’s create that as well. But, this time with the following options as shown below:-


so, when i clicked add, it has not only created Movies controller but also all the required views in Movies sub folder as shown below in the section.



now, with these changes in place, when i build the app and refresh the page, i will be able to see one new view with complete CRUD functionality in there.



so, let’s suppose when you click either of the link, it will emit the things accordingly, let’s suppose i click on edit, it will emit me text boxes, in case of details simple list type div will get emitted and same in case of delete with one confirmation box. Also, Create New will emit new entry as in text boxes.

67th 68th

similarly for creating new Movie

69th 70th


so, this is the basic CRUD functionality provided by the scaffolding template when i created the controller. so, basically idea behind using this scaffolding template is reusing the logic which we usually write in any application, which obviously is going to save me lots of time. On the of this, i always have this liberty to tweak certain implementations my way and implement the same.


However, one thing which i found missing here is when i click on details link, i didn’t find reviews associated with each movie. This is fairly simple to put that, i can just tweak the view one foreach statement and print the Reviews for each associated movie.

Now, for listing Reviews, i would be taking a different step here. Now, for this approach i would be using Reviews controller separately and invoking the same. so, I don’t need the details view, hence i’ll delete the details view and also associated action method from my Movies Controller. Now, since we don’t have details action, so we need to change Index view,  as shown below



Now, accordingly i need to modify the my reviews controller, so ultimately i will be deleting all the methods and in memory data which i have written initially to test my reviews, rather than this i would be using below piece of code.



Now, at this point i don’t have any view associated with it. so, i’ll add one by just rt-clicking the action result with the following options.





Now, i need to tweak this review a bit, because, l’ll take the same cut it from here and create a partial view for the MovieReview.



Now, replace the code copied from index view of review in the partial view as



so, here model is going to Ienumerable of MovieReview. Now, i can just optimize this view a bit like i don’t need id to be displayed here, in similar fashion, i can go ahead and delete the details and delete because this is unnecessary here. so, the same view could rephrased as



Now, i need to render this partial view from my index view as shown below.



Now, i need to make one more small change before building the app and run the same, i need to add virtual keyword in the Movies Entity, the reason being is when my query goes to load reviews associated with movie deferred query execution comes into picture, so with that virtual keyword in place it will go to db and fetch the associated review for me.




Now, let’s create a review. now, for creating a review i need to explicitly send the Movie Id from my index view so that, it will create a review for that movie as shown below.



then, i need in the reviews controller one action method which will respond to this one.


Now, i need a view for same as well like shown below. So, this time i’ll pickup the Create template with the below mentioned options.



Now, here it created me the view for Creating Reviews, however i modified the same a bit by deleting the id part from the view as this is redundant.




so, now this should be ok, to render the new Review page as shown below


But, in order to save the same, i need to have one more controller with Post action so that it will save the changes in db itself.


Now, what this will do it will respond to a POST request by taking MovieReview as a parameter, so that’s where the default Model binder in the MVC will come into picture, then it will instantiate an instance of the type and then look through all the properties to see and then push the same. Now, inside the create action, the 1st thing which we typically do is check to see if model state is valid or not, if IsValid flag returns false, then something went wrong with the model binding. so thing is if something went wrong, then in that case 90thwe won’t save the things in the database, we’ll return the create view again to the user, so that user can fix the things up for me. so, if any thing is wrong, then in that case HTML.validation message will show the validation error messages for me. so, now if build and click on add button to save the review then it should add the same.

Now, let’s see edit scenario. so, all we need here is one action method which will respond to the Edit Action as shown below.



so, what the above snippet will do, it will take the id parameter, look up in the db and then it will return the associated view for the same. so, we need the view, so will create the same based on the below options



This is also very much similar what we had in Create view, only thing which is different here, we do have hidden input for id value, which will allow us to track the id of the review thats being edited. Now, for submit action we need to have one action method to do the same.


Now, what this method will do here, it will again take the model object and everything is valid then, it will tell EF that here is a review that i want you to start tracking whenever this gets changed, but since this is not a new review, so it doesn’t need to be inserted in the database rather it needs to be updated with the new data inside, that’s the purpose of entitystate.modified. and now when i build and refresh i can see that reviews are updating properly.

However, there is one concern associated with this, like in edit scenario i could go and edit submitter name also, which is obviously you really want users to do that, so in order to restrict that what we could do here is we can use Bind attribute to exclude the values which we don’t want model binder to expose in like shown below.



also, from the view i have removed the values for submitter, so it won’t show now these values. but why i used Bind attribute is because i just wanted to make sure that users should not be inserting the same from the query string.

Now, In the last section of this module, let’s talk about a bit of data validation, we can do the same by applying certain annotation rules on our model classes as shown below. so, let’s suppose when am submitting any review i want this to be submitted in a range of 1 to 5. so for restricting the user for putting any other value than this, we can use Range annotation. Also, i would like to make it a required field, so i could use Required as shown below. In addition to these properties there are ton of validation properties. you can refer the same in MSDN link. for me i think this thing should be sufficient.



Now, when i build and refresh the page i got the below yellow screen of death and there is a reason for that, because EF has detected that your model definition has changed, so same thing has to be applied in the db first, so in order to sync the db with latest changes, we just need to apply migrations again, this time forceful migrations as shown below.



now, when i refresh the page it will back to normal state. now, let’s see validations in action, these validations are obviously client side validation, so even user click on submit it won’t go to server as shown below.


Now, as soon as you put valid input in there these error messages will go out. so, with this i would like to wrap this model now. so till then stay tuned and happy coding.


1,404 total views, 1 views today

Getting started with data setup 2

Hi Friends,

This is the continuation of the last section, where i began to setup real time db for our’s movie site. so, let’s get started with the migrations part. However, in the last section we have not configured anything like db connection string, so we didn’t tell explicitly where to make db, what name it should be etc, obviously we can override these things and we can configure these things by using base class constructor as shown below.





so, in the constructor i have said to load the default connection which is being tweaked by me for my convenience. This way i can derive how and where exactly with what name my db will be created. so, with this setting if i build my solution and refresh the page, obviously i’ll loose the data, never mind will push data again.


Now, the next thing which i need to do is use migrations to configure database schemas, seed database and then track for changes in the entity classes. and whenever, these classes will get changed then accordingly database will get updated so that it will keep the database and entity classes in sync. so, the way i’ll be using migrations will be with package manager console window. Basically i launch package manager console window from quick launch section as shown below, and in that window i’ll be typing powershell command to start with the migrations.


47th 48th




so, above is the screen shot of controlling code first migrations. so, basically it gave a skeleton code to get started or to seed values in the db. so, the first thing is AutomaticMigrationsEnabled = False, which means EF won’t make any changes in your db, unless you explicitly instruct EF to do so. But, what i usually do during development, I usually keep it marked as True, because i have been changing my entities so often.



so, what it will basically do, it will go into the database, and see if there is any movie exists with the name, if yes then it will update the same or it will add the same into db.

now, in order to update the db with the above said values, we just need to run the below command in the powershell “Update-database -Verbose”. so, what verbose do basically, it will do force update if there is any data already exists in the db.



so, when i refresh the page, i should be able to see the change with newly seeded values as shown below.



Now, let’s consider a scenario that you are changing the entity and then again you need to update the database, since we have already set AutomaticMigrationsEnabled = true, so don’t need to bother about that, EF will take care about that, so let’s add one more column in the Review class as shown below.

53rd 54th 55th


Now, when i refer the db, it has taken the effect with new value as well. Now, let’s improvise the query a bit as shown below, but before i need to create one View Model, so that i can query against my anonymous type quite significantly in a strongly typed fashion in my view, so ViewModels are again a model which is meant for views. so, suppose you have a complex data model to query against then obviously you could use View Models against that.




Then, when i build and refresh, then page would like some thing like that



Now, in the above query i have added one search criteria to filter the records, now let’s implement that search criteria, so that user can filter records. i have used extension methods in the query so that i can use paging or filtering easily like below:-



so, the above query says that if there is any filtering criteria, then search based on that otherwise return top 10 results based on the average rating.



so, with this i would like to wrap this session. In the next session, we’ll see more about working with data and views together. So, till then stay tuned and happy coding.

Happy Coding

1,320 total views, no views today

Getting started with Data

Hi Friends,

In today’s discussion, we’ll see more about working with data in case of building Movie Review site. so, the focus of this is to build real time database. so, in this we’ll be working with Entity Framework. so, let’s get started.

so, the 1st step is to get up and running Entity Framework, Entity Framework is the part Framework, and we already have a reference in our project for the same. EF allows me to access relational database using strongly typed c# code. so, when am working with classes, they talk to EF, i don’t have to worry about Sql connections/commands/parameters/data readers.with EF i can work with C# code, and i can issue query using LINQ. There’s few different ways to get started with Entity Framework. They are,

Schema First or Database First:-
Model First:-
Code First:-

so, all of these above mentioned approaches have been exclusively explained in Entity framework category in my blog. you can refer those. In this case, i would be using the last one Code First Approach. so far in the application we were doing all the stuffs with in memory data based out on the below mentioned class.


now, i’ll separate these classes in order to build relationships between the two( Movie and reviews)



so, in the above case i made a separate movie class with all the required parameters in there, apart from that, it also has one ICollection property which holds the collection of all associated Reviews of that movie. now, let me change a bit in the Review Class as well.


so, now my two classes are ready, so these are going to be objects which i would instantiate and save it in database and retrieve the same. Now, let me also add a class to add and persist data, we’ll call it MoviesDb. Now, this class needs to be derived from an entity framework class known as Dbcontext. Now, in the Dbcontext, we can have properties of Dbset that represents the entities that you want to query and persist.



Now, let me show that how easy to use the same in our controller. Let’s use the same in one controller. Now, since it’s a disposable resource, so i should also do some cleanup activity by overriding dispose method simply, when my job is done like shown below




so, now what above line of code will do, that it will go into sql server find where it stored all the movies, retrieve all and put them in the list. Now, with the above code in place i need to change a bit in my view. Now, since this view is already created, so i’ll add a model directive manually since the view is already created, so this is going to be strongly typed against the IEnumerable<Movie>. Now, let’s write the movies out.



Now, let me build the solution, now the thing is for building the same i have commented out in memory database which i have written in the Reviews Controller and when ran the same i got the blank screen,


but i didn’t get any error, which means Entity Framework behind the scenes worked with few database, but where is that database. To answer the question, we need to see the database explorer and add a connection as shown below





so, this was the db which is created by entity framework for me behind the scenes. hence, it didn’t gave me error when i ran the app. However, currently the tables are empty. So, let me go ahead and add few records manually in the db.



so, now when i refresh the page, it will give me that list.



so, with this i would like to wrap this. Now, in the next section, we’ll see more about db migrations and using LINQ queries. Till then stay tuned and happy coding.

Happy coding

1,377 total views, 1 views today