ASP.Net MVC5 beginners…

The best tutorials for beginners

For Code First Approach:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

For Database First Approach:

http://www.asp.net/mvc/tutorials/mvc-5/database-first-development/setting-up-database

If you wish to use the default database of ASP.net MVC 5 identity and want to connect with SQL server, then do the following:

  • make sure that your Entity Framework version in webconfig file matches the one installed in your project.
  • If adding migration/updating database commands give any problem, uninstall the Entity Framework and Asp.NetIdentityEntityFramework (right click your project in solution explorer>>manage nuget packages>>installed) 

clean solution and then exit visual studio

open the project again

now install the two packages (Entity Framework and Asp.NetIdentityEntityFramework) again.

build solution

in package manager console execute the following command:

Enable-migrations

if all goes well, update-database

  • in web config file (in the root of the project), make changes in the entityframework tag, change the defaultConnectionFactory tag and the parameter value

and it should look like this

<entityFramework>
<defaultConnectionFactory type=”System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework”>
<parameters>
<parameter value=”Data Source=AJ; Integrated Security=True; MultipleActiveResultSets=True” />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName=”System.Data.SqlClient” type=”System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer” />
</providers>
</entityFramework>

make changes in the connection string and it should look like this:

<connectionStrings>
<add name=”CodeFirst4” connectionString=”Data Source=AJ;Initial Catalog=CodeFirst4;Integrated Security=True”
providerName=”System.Data.SqlClient” />
</connectionStrings>

[add name=CodeFirst4 is the name of the connection, AJ is the name of the server, Catalog=CodeFirst4 is the name of the database]

your ApplicationDbContext class must look like this:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(): base(“CodeFirst4“)
{
}

[this CodeFirst4 must be the same name as that of the connection]


//THE PART BELOW IS OPTIONAL

in webconfig, in entity framework add contexts tag

<contexts>
<context type=”CodeFirst4.Models.ApplicationDbContext, CodeFirst4″>
<databaseInitializer type=”CodeFirst4.Models.SchoolInitializer, CodeFirst4″ />
</context>
</contexts>

in applicationdbcontext class add this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);

modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
}

Add Seed Data as told by ASP.net tutorials. (i created an intializer class in the models folder)

public class SchoolInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{

 

Modifying the database…error “Consider using Code First Migrations to update the database”

Before I forget … ( and I gotta read this later Scott Gu’s Blog)

“The model backing the ‘ApplicationDbContext’ context has changed since the database was created. Consider using Code First Migrations to update the database”

Put this line in your Global.asax in Application_Start() and the error will go away…

Database.SetInitializer<YourDbContext>(null);

How to clear all pending migrations

Error:

“Cannot find the object “dbo.AspNetUsers” because it does not exist or you do not have permissions”

“Unable to generate an explicit migration because the following explicit migrations are pending: [*******]. Apply the pending explicit migrations before attempting to generate a new explicit migration.”

System.InvalidOperationException: Migrations is enabled for context ‘ApplicationDbContext’ but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the ‘Update-Database’ command from the Package Manager Console.”

These kind of errors occur when you run your project before adding migrations, if you have modified the database (in my case, i made changes in the connection string). In order to get rid of this error, do the following:

  • Just delete the “Migrations” folder in your project.
  • Clean the solution.
  • Then in the Package Manager Console, execute the following commands one by one:
    • Enable-migrations
    • Add-migration “initial”
    • update-database

Now Build your project and go check in SQL Server Management Studio, there it will be…your new database.

mig

A Brief Intro to Everything…ASP.Net, MVC,…

Most of you would be really confused where to start from…ok you must have heard asp.net but what’s .net? Shoots!! I don’t even know about asp let alone be .net…So before jumping on to anything else, let’s just make things clear in the first instance.

ASP – Active Server Pages & ASP.Net

ASP (same as ASP classic) is actually what makes your web content dynamic and interactive. It’s Microsoft’s first server side script engine. Active Server Pages, the name says it all…No Server No active pages. This means that the browser cannot run the asp pages directly. There must be some supporting Web Server, a web server that supports ASP. The sever introduced by Microsoft known as Internet Information Services (IIS) is what the ASP runs inside.

Then came ASP.Net, obviously better than the classic ASP. The main difference between the two is the dot! Asp is written in scripting languages like VBScript, Java Script, etc. ASP.Net makes use of the .Net Framewok, any language that comes in the .Net circle, like C#, VB.Net, etc.
Performance wise, ASP.Net is much faster than the classic ASP plus lines of code is less in an application written in ASP.Net rather ASP. Also debugging is way much easier than the classic version.
ASP uses .asp extension while ASP.Net uses .aspx extension

What is MVC?

Model View Controller (MVC) is a framework that separates the code into three classes for easy understanding. The Model class contains all the properties, the attributes, etc. The View Class has all the code for designing the User Interface. The Controller class is where your logic sits in.

If we consider an example of some application a person’s bio data. The model class can have stuff like the name of the person, his date of birth, his father’s name etc. each attribute will be having the data type as well, so these things will be entertained in the model class.
The View class will be having a the buttons and the text boxes, and anything that you would like to see at the user end.
Controller Class will have all the conditions and the programming logics required to run your application smoothly and sensibly.

ASP.Net MVC 5

The latest versions of ASP.Net MVC have Razor implemented for the View code, and the default designing layout is that of Bootstrap which makes your app responsive.

ASP.Net Identity (which has replaced the older versions “ASP.Net Membership” & “Simple Membership”) is the thing that makes your web applications more authenticated and secure with cool built in features such as Login and Signup, Remember me, and Change Password. The “Forgot My Password” will be available in the next release. It has also got the options from which you can login to an application with your existing gmail/facebook/twitter id.

Packages for ASP.Net Identity:

-Microsoft.AspNet.Identity.EntityFramework
-Microsoft.AspNet.Identity.Core
-Microsoft.AspNet.Identity.OWIN

One ASP.Net, is the concept of having one and only one web application that can make use of everything as you wish. When you go to the File Menu for a New Project and select Visual C#, you must have noticed that for the web application you have got just one choice “ASP.Net Web Application”, when you proceed further, there you can see the various templates including MVC, Web Forms, Web API, etc.

OWIN –  The latest versions using OWIN do not support System.Web. Even for generating cookies, OWIN CookieAuthentication is used instead of FormsAuthentication.

Nuget is a built in package in the latest releases now. It’s easier to download updates as well as integrate various packages with nuget.

Entity Framework (EF) – This is Microsoft’s recommended data access technology for relational databases.

In short Visual Studio 2013+ASP.Net Identity MVC5 has made life a lot easier!

For further reading, do visit the following links:

http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

http://msdn.microsoft.com/en-us/library/ms973813.aspx

http://www.w3schools.com/asp/asp_intro.asp

http://www.webwiz.co.uk/kb/asp-tutorials/what-is-asp.htm

 

How To Check The Version Of MVC in Visual Studio

Tools/Technology/Framework used:

  • Microsoft Visual Studio 2013
  • ASP.Net 4.5.1 MVC5

The first thing is to check out which version of MVC is installed in your system.

Make a simple project

File>>New>>Project>>Installed>>Visual C#>>Web>>ASP.Net Web Application>>name it and Ok. Select MVC as template. Put a Check on MVC. Ok.

In the Solution Explorer at the right (press Ctl+Alt+L if it’s not there), select References and  there in the list find out System.Web.MVC. Click on it to open the property sheet (press F4 if it’s not there) and you will find there a property called “Version” which shows the version of MVC that you have.

Creating a Database in SQL Server with Visual Studio

Tools/Language/Framework used:

  • Microsoft SQL Server Management Studio 2012
  • Microsoft Visual Studio 2013
  • ASP.Net 4.5.1 MVC5

The name of my project is “HowToMakeDB”

ServerName is “AJ”

Create a new project, go to WebConfig in Solution Explorer and find out he connectionSrings tag,

<connectionStrings>
<add name=”DefaultConnection” connectionString=”Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-HowToMakeDB-20140721113407.mdf;Initial Catalog=aspnet-HowToMakeDB-20140721113407;Integrated Security=True”
providerName=”System.Data.SqlClient” />
</connectionStrings>

The above stated <connectionStrings> is the default one.

We will change this as per our requirement

 

  • “DefaultConnection” This will be the name of the connectionstring,
  • “Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-HowToMakeDB-20140721113407.mdf”  This will replace be replaced by the name of our Server (as in SQL).
  • Initial Catalog=aspnet-HowToMakeDB-20140721113407;Integrated Security=True”  This will be replaced by the name of our database.

and the new connection string becomes this:

<connectionStrings>
<add name=”DefaultConnection” connectionString=”Data Source=AJ;Initial Catalog=MyVeryOwnDb;Integrated Security=True”
providerName=”System.Data.SqlClient” />
</connectionStrings>

Note that name=”DefaultConnection” should remain as it is.

Build your solution.

Now open Package Manager Console [Tools>>Library Package Manager>>Package Manager Console ] and run the following command:

update-database

Now Save your project, build and run.

Open SQL Server, and you will see a new database has been created with the name that you gave in InitialCatalog, here MyVeryOwnDb

[  If you don’t see you DB in SQL server, try executing the following commands in Package Manager Console one by one

Enable-migrations

Add-Migration “newtable”

update-database

and then build and run the project, then open SQL and look for the DB]

Command Copy Exited with Code 1

Tools/Technology/Framework used:

  • Microsoft Visual Studio 2013
  • ASP.Net 4.5.1 MVC5

This is a very lame error of visual studio

Command Copy Exited with Code 1

just go to Project>>Properties>>Build Events>>

check out if it contains the word “copy” in it, in my case it did in the ‘Post build event command line’. Just remove the word “copy” and build the solution, that is it …build successful!