Sunday, August 18, 2013

EF Migration Commands

www.dotnetstory.com

Entity Framework Commands:-
1. Install Entity Framework any ver. 4.0 to 5.0

1.Install-Package EntityFramework
 
2. Enable Migration in project

2.Enable-Migrations

3. Enable Migration in particular Context in project

3.Enable-Migrations -ContextTypeName ProjectName.Models.DbContextName 

4. Fire command after enable migration

4.Add-Migration AddPostAbstract

5. Update Database

5. Update Database

6.Add-Migration

7.Update-Database –Verbose

8. In case changed colunm length then fire this command

add-migration MaxLengthOnNames
update-database


9.In case you changed colunm name then fire this command

add-migration ColumnFirstName
update-database


10.Add-Migration RowVersion
   Update-Database





 

Monday, August 12, 2013

How to use LINQ To Entities with Examples

1.Method-Based Query Syntax Examples: Projection


The examples in this topic demonstrate how to use the Select and SelectMany methodsto query the AdventureWorks Sales Model using method-based query syntax. The AdventureWorks Sales Model used in these examples is built from the Contact, Address, Product, SalesOrderHeader, and SalesOrderDetail tables in the AdventureWorks sample database.
The examples in this topic use the following using/Imports statements:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;
    

Select

Example

The following example uses the Select method to project the Product.Name and Product.ProductID properties into a sequence of anonymous types.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
var query = context.Products
.Select(product => new
{
ProductId = product.ProductID,
ProductName = product.Name
});

Console.WriteLine("Product Info:");
foreach (var productInfo in query)
{
Console.WriteLine("Product Id: {0} Product name: {1} ",
productInfo.ProductId, productInfo.ProductName);
}
}
    

Example

The following example uses the Select method to return a sequence of only product names.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
IQueryable<string> productNames = context.Products
.Select(p => p.Name);

Console.WriteLine("Product Names:");
foreach (String productName in productNames)
{
Console.WriteLine(productName);
}
}
    

SelectMany

Example

The following example uses the SelectMany method to select all orders where TotalDue is less than 500.00.

decimal totalDue = 500.00M;
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
ObjectSet<Contact> contacts = context.Contacts;
ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;

var query =
contacts.SelectMany(
contact => orders.Where(order =>
(contact.ContactID == order.Contact.ContactID)
&& order.TotalDue < totalDue)
.Select(order => new
{
ContactID = contact.ContactID,
LastName = contact.LastName,
FirstName = contact.FirstName,
OrderID = order.SalesOrderID,
Total = order.TotalDue
}));

foreach (var smallOrder in query)
{
Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Total Due: ${4} ",
smallOrder.ContactID, smallOrder.LastName, smallOrder.FirstName,
smallOrder.OrderID, smallOrder.Total);
}
}
    

Example

The following example uses the SelectMany method to select all orders where the order was made on October 1, 2002 or later.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
ObjectSet<Contact> contacts = context.Contacts;
ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;

var query =
contacts.SelectMany(
contact => orders.Where(order =>
(contact.ContactID == order.Contact.ContactID)
&& order.OrderDate >= new DateTime(2002, 10, 1))
.Select(order => new
{
ContactID = contact.ContactID,
LastName = contact.LastName,
FirstName = contact.FirstName,
OrderID = order.SalesOrderID,
OrderDate = order.OrderDate
}));

foreach (var order in query)
{
Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Order date: {4:d} ",
order.ContactID, order.LastName, order.FirstName,
order.OrderID, order.OrderDate);
}
} 
 

2.Method-Based Query Syntax Examples: Filtering


The examples in this topic demonstrate how to use the Where and Where…Contains methods to query the AdventureWorks Sales Model using method-based query syntax. Note, Where…Contains cannot be used as a part of a compiled query.
The AdventureWorks Sales model used in these examples is built from the Contact, Address, Product, SalesOrderHeader, and SalesOrderDetail tables in the AdventureWorks sample database.
The examples in this topic use the following using/Imports statements:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;
    

Where

Example

The following example returns all online orders.
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
var onlineOrders = context.SalesOrderHeaders
.Where(order => order.OnlineOrderFlag == true)
.Select(s => new { s.SalesOrderID, s.OrderDate, s.SalesOrderNumber });

foreach (var onlineOrder in onlineOrders)
{
Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}",
onlineOrder.SalesOrderID,
onlineOrder.OrderDate,
onlineOrder.SalesOrderNumber);
}
}
    

Example

The following example returns the orders where the order quantity is greater than 2 and less than 6.

int orderQtyMin = 2;
int orderQtyMax = 6;
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
var query = context.SalesOrderDetails
.Where(order => order.OrderQty > orderQtyMin && order.OrderQty < orderQtyMax)
.Select(s => new { s.SalesOrderID, s.OrderQty });

foreach (var order in query)
{
Console.WriteLine("Order ID: {0} Order quantity: {1}",
order.SalesOrderID, order.OrderQty);
}
}
    

Example

The following example returns all red colored products.

String color = "Red";
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
var query = context.Products
.Where(product => product.Color == color)
.Select(p => new { p.Name, p.ProductNumber, p.ListPrice });

foreach (var product in query)
{
Console.WriteLine("Name: {0}", product.Name);
Console.WriteLine("Product number: {0}", product.ProductNumber);
Console.WriteLine("List price: ${0}", product.ListPrice);
Console.WriteLine("");
}
}
    

Example

The following example uses the Where method to find orders that were made after December 1, 2003 and then uses the order.SalesOrderDetail navigation property to get the details for each order.
 
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
IQueryable<SalesOrderHeader> query = context.SalesOrderHeaders
.Where(order => order.OrderDate >= new DateTime(2003, 12, 1));

Console.WriteLine("Orders that were made after December 1, 2003:");
foreach (SalesOrderHeader order in query)
{
Console.WriteLine("OrderID {0} Order date: {1:d} ",
order.SalesOrderID, order.OrderDate);
foreach (SalesOrderDetail orderDetail in order.SalesOrderDetails)
{
Console.WriteLine("  Product ID: {0} Unit Price {1}",
orderDetail.ProductID, orderDetail.UnitPrice);
}
}
}
    

Where…Contains

Example

The following example uses an array as part of a Where…Contains clause to find all products that have a ProductModelID that matches a value in the array.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
int?[] productModelIds = { 19, 26, 118 };
var products = AWEntities.Products.
Where(p => productModelIds.Contains(p.ProductModelID));

foreach (var product in products)
{
Console.WriteLine("{0}: {1}", product.ProductModelID, product.ProductID);
}
}
    
noteNote:
As part of the predicate in a Where…Contains clause, you can use an Array, a List, or a collection of any type that implements the IEnumerable interface. You can also declare and initialize a collection within a LINQ to Entities query. See the next example for more information.

Example

The following example declares and initializes arrays in a Where…Contains clause to find all products that have a ProductModelID or a Size that matches a value in the arrays.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
var products = AWEntities.Products.
Where(p => (new int?[] { 19, 26, 18 }).Contains(p.ProductModelID) ||
(new string[] { "L", "XL" }).Contains(p.Size));

foreach (var product in products)
{
Console.WriteLine("{0}: {1}, {2}", product.ProductID,
product.ProductModelID,
product.Size);
}
} 
 

3.Method-Based Query Syntax Examples: Ordering

1 out of 1 rated this helpful - Rate this topic

The examples in this topic demonstrate how to use the ThenBy method to query the AdventureWorks Sales Model using method-based query syntax. The AdventureWorks Sales Model used in these examples is built from the Contact, Address, Product, SalesOrderHeader, and SalesOrderDetail tables in the AdventureWorks sample database.
The examples in this topic use the following using/Imports statements:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;
    

ThenBy

Example

The following example in method-based query syntax uses OrderBy and ThenBy to return a list of contacts ordered by last name and then by first name.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
IQueryable<Contact> sortedContacts = context.Contacts
.OrderBy(c => c.LastName)
.ThenBy(c => c.FirstName);

Console.WriteLine("The list of contacts sorted by last name then by first name:");
foreach (Contact sortedContact in sortedContacts)
{
Console.WriteLine(sortedContact.LastName + ", " + sortedContact.FirstName);
}
}    

ThenByDescending

Example

The following example uses the OrderBy and ThenByDescending methods to first sort by list price, and then perform a descending sort of the product names.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
IOrderedQueryable<Product> query = context.Products
.OrderBy(product => product.ListPrice)
.ThenByDescending(product => product.Name);

foreach (Product product in query)
{
Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
product.ProductID,
product.Name,
product.ListPrice);
}
}
    
 
 

Sunday, August 11, 2013

User Management in MVC3

User Management in MVC3


What is Entity Framework
Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write. For more see: http://msdn.microsoft.com/en-us/data/ef.aspx
What is MVC?
The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes [Burbeck92].
Model: The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
View: The view manages the display of information.
Controller: The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.
Getting Started
  1. Create a new project; first open Visual Studio 2012 
  2. Then go to "File" => "New" => "Project..." 
  3. Select Web in installed templates 
  4. Select "ASP.NET MVC 4 Web Application"
  5. Enter the name and choose the location 
  6. Click "OK"
Now add a new ADO.NET Entity data Model.
img1.jpg 
Image 1.
To learn how to configure an ADO.NET Entity Data Model please read this article-
So let's proceed without wasting time, here is my data model scenario:
img2.jpg 
Image 2.
This is my model class that is generated when we configure the data model, I just made slight changes.
//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace LoginInMVC4WithEF.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
   
    public partial class Registration
    {
        public int UserId { getset; }
        [Required]
        [EmailAddress]
        [StringLength(150)]
        [Display(Name = "Email Address: ")]
        public string Email { getset; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(150, MinimumLength = 6)]
        [Display(Name = "Password: ")]
        public string Password { getset; }

        public string PasswordSalt { getset; }

        [Required]
        [Display(Name = "First Name: ")]
        public string FirstName { getset; }

        [Required]
        [Display(Name = "Last Name: ")]
        public string LastName { getset; }
        public string UserType { getset; }
        public System.DateTime CreatedDate { getset; }
        public bool IsActive { getset; }
        public string IPAddress { getset; }
   }

 
This is my context class, again this is also generated by data model.
public partial class UserEntities2 : DbContext
{
    public UserEntities2()
        : base("name=UserEntities2")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public DbSet<Registration> Registrations { getset; }
}
 
Now to add a controller.

img3.jpg  
Image 3.
 
Add namespaces in the controller class:
 
using System.Web.Security;
using LoginInMVC4WithEF.Models;

Now add the following functions and methods.
 
//
// GET: /User/
public ActionResult Index()
{
    return View();
}
       
[HttpGet]       
public ActionResult LogIn()
{
    return View();
}
       
[HttpPost]       
public ActionResult LogIn(Models.Registration userr)
{
//if (ModelState.IsValid)
//{
    if (IsValid(userr.Email, userr.Password))
    {
        FormsAuthentication.SetAuthCookie(userr.Email, false);
        return RedirectToAction("Index""Home");
    }
    else
    {
        ModelState.AddModelError("""Login details are wrong.");
    }
    return View(userr);
}
       
[HttpGet]       
public ActionResult Register()
{
    return View();
}

[HttpPost]      
public ActionResult Register(Models.Registration user)
{
    try
    {
        if (ModelState.IsValid)
        {
            using (var db = new LoginInMVC4WithEF.Models.UserEntities2())
            {
                var crypto = new SimpleCrypto.PBKDF2();
                var encrypPass = crypto.Compute(user.Password);
                var newUser = db.Registrations.Create();
                newUser.Email = user.Email;
                newUser.Password = encrypPass;
                newUser.PasswordSalt = crypto.Salt;
                newUser.FirstName = user.FirstName;
                newUser.LastName = user.LastName;
                newUser.UserType = "User";
                newUser.CreatedDate = DateTime.Now;
                newUser.IsActive = true;
                newUser.IPAddress = "642 White Hague Avenue";
                db.Registrations.Add(newUser);
                db.SaveChanges();
                return RedirectToAction("Index""Home");
            }
        }
        else
        {
            ModelState.AddModelError("""Data is not correct");
        }
    }
    catch (DbEntityValidationException e)
    {
        foreach (var eve in e.EntityValidationErrors)
        {
            Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                eve.Entry.Entity.GetType().Name, eve.Entry.State);
            foreach (var ve in eve.ValidationErrors)
            {
                Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                    ve.PropertyName, ve.ErrorMessage);
            }
        }
        throw;
    }
    return View();
}
       
public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Index""Home");
}

private bool IsValid(string email, string password)
{
    var crypto = new SimpleCrypto.PBKDF2();
    bool IsValid = false;

    using (var db = new LoginInMVC4WithEF.Models.UserEntities2())
    {
        var user = db.Registrations.FirstOrDefault(u => u.Email == email);
        if (user != null)
        {
            if (user.Password == crypto.Compute(password, user.PasswordSalt))
            {
                IsValid = true;
            }
        }
    }
    return IsValid;
} 

There I have functions and methods for index page and login, logout, register and isvalid, now let's make some change in "_Layout.vshtml". Add the following div:
 
<div style="width:autobackground-color:aqua">
        @if (Request.IsAuthenticated)
        {
            <strong>@Html.Encode(User.Identity.Name)</strong>
            @Html.ActionLink("Log Out""Logout""User")
        }
        else
        {
            @Html.ActionLink("Register""Register""User")
            <span> | </span>
            @Html.ActionLink("Log In""Login""User")
        }
</div>
 
Now let's add views for presentation.
 
The best way to add a view is to right-click on the controller's method name and then right-click and "Add View" and select the view engine type and select strongly-typed view and use the layout master page and click "Add".

img4.jpg  
Image 4.
 
LogIn.cshtml
 
 
@model LoginInMVC4WithEF.Models.Registration

@{
    ViewBag.Title = "LogIn";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>LogIn</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true"Login Failed, check details");
    <div>
        <fieldset>
            <legend>Login Form</legend>
            <div class="editor-label">@Html.LabelFor(u=> u.Email)</div>
            <div class="editor-field">@Html.TextBoxFor(u=> u.Email)
                @Html.ValidationMessageFor(u=> u.Email)
            </div>
            <div class="editor-label">@Html.LabelFor(u=> u.Password)</div>
            <div  class="editor-field">@Html.PasswordFor(u=> u.Password)
                @Html.ValidationMessageFor(u=> u.Password)
            </div>
            <input type="submit" value="Log In" />
        </fieldset>
    </div>
}

Register.cshtml
 
 
@model LoginInMVC4WithEF.Models.Registration
@{
    ViewBag.Title = "Register";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Register</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true"Registeration Failed, fields.");
    <div>
        <fieldset>
            <legend>Register Form</legend>
            <div class="editor-label">@Html.LabelFor(u => u.Email)</div>
            <div class="editor-field">@Html.TextBoxFor(u => u.Email)
                @Html.ValidationMessageFor(u => u.Email)
            </div>
            <div class="editor-label">@Html.LabelFor(u => u.Password)</div>
            <div class="editor-field">@Html.PasswordFor(u => u.Password)
                @Html.ValidationMessageFor(u => u.Password)
            </div>
            <div class="editor-label">@Html.LabelFor(u => u.FirstName)</div>
            <div class="editor-field">@Html.TextBoxFor(u => u.FirstName)
                @Html.ValidationMessageFor(u => u.FirstName)
            </div>
             <div class="editor-label">@Html.LabelFor(u => u.LastName)</div>
            <div class="editor-field">@Html.TextBoxFor(u => u.LastName)
                @Html.ValidationMessageFor(u => u.LastName)
            </div>

            <input type="submit" value="Register" />
        </fieldset>
    </div>
}
 
LogOut.cshtml
 
 
@{
    ViewBag.Title = "LogOut";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>LogOut</h2>
 
public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Index""Home");
}

 
Now hit F5 to run the application and click on the "Register" button and don't put anything in the TextBoxes and click the "Register" button.
img5.jpg
Image 5.
 
As you can see in the model class, all fields are required so these messages are displayed.
img6.jpg
Image 6.
 
Now if I put a password value less than 6 characters or more than 150 characters then this message will display:
img7.jpg
Image 7.
 
Now insert all values properly, then you will see it will register and data should inserted into the database, now you can login.
img8.jpg
Image 8.
img9.jpg