Wednesday, October 1, 2014

Complete CRUD Operations in MVC 4 using Entity Framework 5 Without Writing a Single Line of Code

Introduction

In this article, I’ll describe how to perform basic CRUD operations in an MVC4 application with the help of Entity Framework 5 without writing a single line of code. EF and MVC had advanced themselves to the level that we don’t have to put effort in doing extra work.

I) MVC

Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the model into a form of interaction.
Controller: Handles a request from a view and updates the model that results a change in Model’s state.
To implement MVC in .NET, we need mainly three classes (ViewController and the Model).

II) Entity Framework

Let’s have a look at the standard definition of Entity Framework given by Microsoft:
“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.”
In a simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.
Hope this gives a glimpse of an ORM and EntityFramework.

III) MVC Application

Step 1: Create a database named LearningKO and add a table named student to it, script of the table is as follows:
USE [LearningKO]
GO
/****** Object:  Table [dbo].[Student]    Script Date: 12/04/2013 23:58:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student](
 [StudentId] [nvarchar](10) NOT NULL,
 [FirstName] [nvarchar](50) NULL,
 [LastName] [nvarchar](50) NULL,
 [Age] [int] NULL,
 [Gender] [nvarchar](50) NULL,
 [Batch] [nvarchar](50) NULL,
 [Address] [nvarchar](50) NULL,
 [Class] [nvarchar](50) NULL,
 [School] [nvarchar](50) NULL,
 [Domicile] [nvarchar](50) NULL,
 CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED 
(
 [StudentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'1', N'Akhil', N'Mittal', 28, N'Male', N'2006', N'Noida', N'Tenth', N'LFS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'2', N'Parveen', N'Arora', 25, N'Male', N'2007', N'Noida', N'8th', N'DPS', N'Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'3', N'Neeraj', N'Kumar', 38, N'Male', _
N'2011', N'Noida', N'10th', N'MIT', N'Outside Delhi')
INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age], _
[Gender], [Batch], [Address], [Class], [School], [Domicile]) _
VALUES (N'4', N'Ekta', N'Mittal', 25, N'Female', N'2005', N' Noida', N'12th', N'LFS', N'Delhi')
Step 2: Open your Visual Studio (Visual Studio Version should be greater than or equal to 12) and add an MVC Internet application.
I have given it a name “KnockoutWithMVC4”.
Step 3: You’ll get a full structured MVC application with default Home controller in the Controller folder. By default, entity framework is downloaded as a package inside application folder but if not, you can add entity framework package by right clicking the project, select manage nugget packages and search and install Entity Framework.
Step 4: Right click project file, select add new item and add ADO.NET entity data model, follow the steps in the wizard as shown below:
Generate model from database, select your server and LearningKO database name, the connection string will automatically be added to your Web.Config, name that connection string as LearningKOEntities.
Select tables to be added to the model. In our case, it’s Student Table.
Step 5: Now add a new controller to the Controller folder, right click controller folder and add a controller namedStudent. Since we have already created our Datamodel, we can choose for an option where CRUD actions are created by chosen Entity Framework Datamodel:
  • Name your controller as StudentController.
  • From Scaffolding Options, select “MVC controller with read/write actions and views, using Entity Framework”.
  • Select Model class as Student, that lies in our solution.
  • Select Data context class as LearningKOEntities that is added to our solution when we added EF data model.
  • Select Razor as rendering engine for views.
  • Click Advanced options, select Layout or master page and select _Layout.cshtml from the shared folder.
Step 6: We see our student controller prepared with all the CRUD operation actions as shown below:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace KnockoutWithMVC4.Controllers
{
    public class StudentController : Controller
    {
        private LearningKOEntities db = new LearningKOEntities();
 
        //
        // GET: /Student/
 
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }
 
        //
        // GET: /Student/Details/5
 
        public ActionResult Details(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
 
        //
        // GET: /Student/Create

        public ActionResult Create()
        {
            return View();
        }
 
        //
        // POST: /Student/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
 
            return View(student);
        }
 
        //
        // GET: /Student/Edit/5
 
        public ActionResult Edit(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
 
        //
        // POST: /Student/Edit/5
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }
 
        //
        // GET: /Student/Delete/5

        public ActionResult Delete(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                 return HttpNotFound();
            }
            return View(student);
        }
 
        //
        // POST: /Student/Delete/5
 
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
 
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
Step 7: Open App_Start folder and, change the name of controller from Home to Student.
The code will become as:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Student", 
        action = "Index", id = UrlParameter.Optional }
    );
}
Step 8: Now press F5 to run the application, and you’ll see the list of all students we added into table Studentwhile creating it is displayed. Since the CRUD operations are automatically written, we have action results for display list and other Edit, Delete and Create operations. Note that views for all the operations are created inViews Folder under Student Folder name.
Now you can perform all the operations on this list.
Since I have not provided any validation checks on model or creating an existing student id, the code may break, so I am calling Edit Action in create when we find that id already exists.
Now create new student.
We see that the student is created successfully and added to the list.
In database:
Similarly for Edit:
Change any field and press save. The change will be reflected in the list and database:
For Delete:
Student deleted.
And in database:
Not a single line of code is written till now.

Conclusion

In this tutorial, we learnt to setup environment for MVC and Entity Framework 5 and perform CRUD operations on Student model without writing a single line of code. You can expand the application by adding multiple Controllers, Models and Views.

Referance:
http://www.codeproject.com/Articles/695850/Complete-CRUD-Operations-in-MVC

Friday, September 19, 2014

The data type comparison chart below

 
.NET Framework Type
ADO.NET Database Type
SQL Data Type
String
Varchar
Varchar()
String
Nvarchar
Nvarchar()
String
NChar
Nchar()
String
NText
NText
String
Text
Text
Double
BigInt
Float
DateTime
DateTime
Datetime
DateTime
SmallDateTime
Smalldatetime
Int
Int
Int
Int64
BigInt
Bigint
Int16
SmallInt
smallint
Byte[]
Binary
Binary()
Byte[]
Image
Image
Byte[]
VarBinary
Varbinary()
Byte
TinyInt
Tinyint
Bool
Bit
Bit
Decimal
Decimal
Decimal
Decimal
Money
Money
Decimal
SmallMoney
SmallMoney
Float
Float
Float
Guid
UniqueIdentifier
Uniqueidentifier
Real
Real
Real

Tuesday, September 16, 2014

Logging In Using External Sites in an ASP.NET Web Pages

This article explains how to log in to your ASP.NET Web Pages (Razor) site using Facebook, Google, Twitter, Yahoo, and other sites — that is, how to support OAuth and OpenID in your site.
What you'll learn:
  • How to enable login from other sites when you use the WebMatrix Starter Site template.
This is the ASP.NET feature introduced in the article:
  • The OAuthWebSecurity helper.

Software versions used in the tutorial

ASP.NET Web Pages includes support for OAuth and OpenID providers. Using these providers, you can let users log into your site using their existing credentials from Facebook, Twitter, Microsoft, and Google. For example, to log in using a Facebook account, users can just choose a Facebook icon, which redirects them to the Facebook login page where they enter their user information. They can then associate the Facebook login with their account on your site. A related enhancement to the Web Pages membership features is that users can associate multiple logins (including logins from social networking sites) with a single account on your website.
This image shows the Login page from the Starter Site template, where a user can choose a Facebook, Twitter, Google or Microsoft icon to enable logging in with an external account:
external providers
You can enable OAuth and OpenID membership by uncommenting a few lines of code in the Starter Site template. The methods and properties you use to work with the OAuth and OpenID providers are in theWebMatrix.Security.OAuthWebSecurity class. The Starter Site template includes a full membership infrastructure, complete with a login page, a membership database, and all the code you need to let users log into your site using either local credentials or those from another site.
This section provides an example of how to let users log in from external sites to a site that's based on the Starter Site template. After creating a starter site, you do this (details follow):
  • For the sites that use an OAuth provider (Facebook, Twitter, and Microsoft), you create an application on the external site. This gives you application keys that you'll need in order to invoke the login feature for those sites.
  • For sites that use an OpenID provider (Google), you do not have to create an application. For all of these sites, you must have an account in order to log in and to create developer applications.
    Note   Microsoft applications only accept a live URL for a working website, so you cannot use a local website URL for testing logins.
  • Edit a few files in your website in order to specify the appropriate authentication provider and to submit a login to the site you want to use.
This article provides separate instructions for the following tasks:

Enabling Google Logins

  1. Create or open an ASP.NET Web Pages site that's based on the WebMatrix Starter Site template.
  2. Open the _AppStart.cshtml page and uncomment the following line of code.
    OAuthWebSecurity.RegisterGoogleClient();

Testing Google login

  1. Run the default.cshtml page of your site and choose the Log in button.
  2. On the Login page, in the Use another service to log in section, choose either the Google or Yahoo submit button. This example uses the Google login.
    The web page redirects the request to the Google login page.
    Google sign in
  3. Enter credentials for an existing Google account.
  4. If Google asks you whether you want to allow Localhost to use information from the account, click Allow.
    The code uses the Google token to authenticate the user, and then returns to this page on your website. This page lets users associate their Google login with an existing account on your website, or they can register a new account on your site to associate the external login with.
    oauth-5
  5. Choose the Associate button. The browser returns to your application's home page.

Enabling Facebook Logins

  1. Go to the Facebook developers site (log in if you're not already logged in).
  2. Choose the Create New App button, and then follow the prompts to name and create the new application.
  3. In the section Select how your app will integrate with Facebook, choose the Website section.
  4. Fill in the Site URL field with the URL of your site (for example, http://www.example.com). The Domain field is optional; you can use this to provide authentication for an entire domain (such as example.com).
    Note   If you are running a site on your local computer with a URL likehttp://localhost:12345 (where the number is a local port number), you can add this value to the Site URL field for testing your site. However, any time the port number of your local site changes, you will need to update the Site URL field of your application.
  5. Choose the Save Changes button.
  6. Choose the Apps tab again, and then view the start page for your application.
  7. Copy the App ID and App Secret values for your application and paste them into a temporary text file. You will pass these values to the Facebook provider in your website code.
  8. Exit the Facebook developer site.
Now you make changes to two pages in your website so that users will able to log into the site using their Facebook accounts.
  1. Create or open an ASP.NET Web Pages site that's based on the WebMatrix Starter Site template.
  2. Open the _AppStart.cshtml page and uncomment the code for the Facebook OAuth provider. The uncommented code block looks like the following:
    OAuthWebSecurity.RegisterFacebookClient(
            appId: "",
            appSecret: "");
  3. Copy the App ID value from the Facebook application as the value of the appId parameter (inside the quotation marks).
  4. Copy App Secret value from the Facebook application as the appSecret parameter value.
  5. Save and close the file.

Testing Facebook login

  1. Run the site's default.cshtml page and choose the Login button.
  2. On the Login page, in the Use another service to log in section, choose the Facebook icon.
    The web page redirects the request to the Facebook login page.
    oauth-2
  3. Log into a Facebook account.
    The code uses the Facebook token to authenticate you and then returns to a page where you can associate your Facebook login with your site's login. Your user name or email address is filled into the Email field on the form.
    oauth-5
  4. Choose the Associate button.
    The browser returns to the home page and you are logged in.

Enabling Twitter Logins

  1. Browse to the Twitter developers site.
  2. Choose the Create an App link and then log into the site.
  3. On the Create an Application form, fill in the Name and Description fields.
  4. In the WebSite field, enter the URL of your site (for example, http://www.example.com).
    Note   If you're testing your site locally (using a URL like http://localhost:12345), Twitter might not accept the URL. However, you might be able to use the local loopback IP address (for example http://127.0.0.1:12345). This simplifies the process of testing your application locally. However, every time the port number of your local site changes, you'll need to update the WebSite field of your application.
  5. In the Callback URL field, enter a URL for the page in your website that you want users to return to after logging into Twitter. For example, to send users to the home page of the Starter Site (which will recognize their logged-in status), enter the same URL that you entered in the WebSite field.
  6. Accept the terms and choose the Create your Twitter application button.
  7. On the My Applications landing page, choose the application you created.
  8. On the Details tab, scroll to the bottom and choose the Create My Access Token button.
  9. On the Details tab, copy the Consumer Key and Consumer Secret values for your application and paste them into a temporary text file. You'll pass these values to the Twitter provider in your website code.
  10. Exit the Twitter site.
Now you make changes to two pages in your website so that users will be able to log into the site using their Twitter accounts.
  1. Create or open an ASP.NET Web Pages site that's based on the WebMatrix Starter Site template.
  2. Open the _AppStart.cshtml page and uncomment the code for the Twitter OAuth provider. The uncommented code block looks like this:
    OAuthWebSecurity.RegisterTwitterClient(
            consumerKey: "",
            consumerSecret: "");
  3. Copy the Consumer Key value from the Twitter application as the value of the consumerKey parameter (inside the quotation marks).
  4. Copy the Consumer Secret value from the Twitter application as the value of the consumerSecret parameter.
  5. Save and close the file.

Testing Twitter login

  1. Run the default.cshtml page of your site and choose the Login button.
  2. On the Login page, in the Use another service to log in section, choose the Twitter icon.
    The web page redirects the request to a Twitter login page for the application you created.
    oauth-4
  3. Log into a Twitter account.
  4. The code uses the Twitter token to authenticate the user and then returns you to a page where you can associate your login with your website account. Your name or email address is filled into the Email field on the form.
    oauth-5
  5. Choose the Associate button.
    The browser returns to the home page and you are logged in.

Additional Resources




Source:http://www.asp.net/web-pages/tutorials/security/enabling-login-from-external-sites-in-an-aspnet-web-pages-site#To_enable_Facebook_logins