Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts
Tuesday, July 5, 2011

CRUD Operation with ASP.NET MVC and EFCodeFirst Part-1

I have been playing with EFCodeFirst now and I found it very interesting with that you could write your application fast and easily. So I have decided to write series of blog posts for CRUD Operations using ASP.NET MVC 3 and EFCodeFirstCTP5.0 . You can very easily create CRUD within some minutes of code. So let’s start first thing is to create an ASP.NET MVC 3 application like following.

ASP.NETMVCApplication

Once you click OK. It will ask for the which type of View your are going to use. I have used Razor and HTML5 Semantic like following.

RazorView

Now once we have create a application Now its time to add EFCodeFirst reference via NuGet. So Go to the Library Package Manager –> Manage Nuget Package Manager. It will open up a dialog like following. Search EFCodeFirst and then it will fine EFCodeFirst package like following.

EFCodeFirst

Once you click Install it will add reference to your ASP.NET MVC Application like following.

EntityFrameworkRerence

So now all the things are set Its time to code now. So first I have Create my Table which is very simple table called Customer like I have used in previous post. For your reference I am putting the create table script below.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
   [CustomerId] [int] IDENTITY(1,1) NOT NULL,
   [FirstName] [nvarchar](50) NULL,
   [LastName] [nvarchar](50) NULL,
   [Address] [nvarchar](256) NULL,
   [City] [nvarchar](50) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
   [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY

Now let's create our entity class called customer like following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CodeSimplified.Models
{
   public class Customer
   {
       public int CustomerId { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Address { get; set; }
       public string City { get; set; }
   }
}

Now Its time to create a our datacontext class So I have created MyDataContext class inherited from the DBContextClass . In that I have defined my customer dbset and Also I override the default plural behaviour in ModelCreating Table. DBSet will tell datacontext which table we need to refer. So following is code for that.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;

namespace CodeSimplified.Models
{
   public class MyDataContext:DbContext
   {
       public DbSet<Customer> Customer { get; set; }

       protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
       {
           modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
       }
   }
}

Now our database access stuff is ready now It’s time to create controller. So I have clicked controller folder and click on add new controller so add controller dialog box will appear like following.

AddController

It will create a controller class like following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CodeSimplified.Controllers
{
   public class CustomerController : Controller
   {
       //
       // GET: /Customer/

       public ActionResult Index()
       {
           return View();
       }

       //
       // GET: /Customer/Details/5

       public ActionResult Details(int id)
       {
           return View();
       }

       //
       // GET: /Customer/Create

       public ActionResult Create()
       {
           return View();
       }

       //
       // POST: /Customer/Create

       [HttpPost]
       public ActionResult Create(FormCollection collection)
       {
           try
           {
               // TODO: Add insert logic here

               return RedirectToAction("Index");
           }
           catch
           {
               return View();
           }
       }
      
       //
       // GET: /Customer/Edit/5

       public ActionResult Edit(int id)
       {
           return View();
       }

       //
       // POST: /Customer/Edit/5

       [HttpPost]
       public ActionResult Edit(int id, FormCollection collection)
       {
           try
           {
               // TODO: Add update logic here

               return RedirectToAction("Index");
           }
           catch
           {
               return View();
           }
       }

       //
       // GET: /Customer/Delete/5

       public ActionResult Delete(int id)
       {
           return View();
       }

       //
       // POST: /Customer/Delete/5

       [HttpPost]
       public ActionResult Delete(int id, FormCollection collection)
       {
           try
           {
               // TODO: Add delete logic here

               return RedirectToAction("Index");
           }
           catch
           {
               return View();
           }
       }
   }
}

Now once our controller is ready now its time to write some code for Index Action Result which we are going to have a list of customer. So I have changed Index Action Result like following to return customer view.

public ActionResult Index()
{
   using (var databaseContext=new Models.MyDataContext())
   {
       return View(databaseContext.Customer.ToList());
   }
}

Now let create a view from the controller. So Selected a view in right click Add View from Index Action Result. Here I have selected strongly typed view with Customer Model and selected list Template like following.

AddView

That’s it we are done with listing of the customer. Now its time to run our application and following is the output as expected.

Output

Hoped you like this…Stay tuned for more.. Till that happy programming.

Shout it

kick it on DotNetKicks.com
Share:
Friday, June 24, 2011

PetaPoco with parameterised stored procedure and Asp.Net MVC

I have been playing with Micro ORMs as this is very interesting things that are happening in developer communities and I already liked the concept of it. It’s tiny easy to use and can do performance tweaks. PetaPoco is also one of them I have written few blog post about this. In this blog post I have explained How we can use the PetaPoco with stored procedure which are having parameters. I am going to use same Customer table which I have used in my previous posts. For those who have not read my previous post following is the link for that.

Get started with ASP.NET MVC and PetaPoco
PetaPoco with stored procedures

Now our customer table is ready. So let’s Create a simple process which will fetch a single customer via CustomerId. Following is a code for that.

CREATE PROCEDURE mysp_GetCustomer
 @CustomerId as INT
AS
SELECT * FROM [dbo].Customer where  CustomerId=@CustomerId

Now we are ready with our stored procedures. Now lets create code in CustomerDB class to retrieve single customer like following.

using System.Collections.Generic;

namespace CodeSimplified.Models
{
  public class CustomerDB
  {
      public IEnumerable<Customer> GetCustomers()
      {
          var databaseContext = new PetaPoco.Database("MyConnectionString");
          databaseContext.EnableAutoSelect = false;
          return databaseContext.Query<Customer>("exec mysp_GetCustomers");

      }
      public Customer GetCustomer(int customerId)
      {
          var databaseContext = new PetaPoco.Database("MyConnectionString");
          databaseContext.EnableAutoSelect = false;
          var customer= databaseContext.SingleOrDefault<Customer>("exec mysp_GetCustomer @customerId",new {customerId});
          return customer;
      }
  }
}

Here in above code you can see that I have created a new method call GetCustomer which is having customerId as parameter and then I have written to code to use stored procedure which we have created to fetch customer Information. Here I have set EnableAutoSelect=false because I don’t want to create Select statement automatically I want to use my stored procedure for that. Now Our Customer DB class is ready and now lets create a ActionResult Detail in our controller like following

using System.Web.Mvc;

namespace CodeSimplified.Controllers
{
  public class HomeController : Controller
  {
      public ActionResult Index()
      {
          ViewBag.Message = "Welcome to ASP.NET MVC!";

          return View();
      }

      public ActionResult About()
      {
          return View();
      }

      public ActionResult Customer()
      {
          var customerDb = new Models.CustomerDB();
          return View(customerDb.GetCustomers());
      }
      public ActionResult Details(int id)
      {
          var customerDb = new Models.CustomerDB();
          return View(customerDb.GetCustomer(id));
      }
  }
}

Now Let’s create view based on that ActionResult Details method like following.

AddView

Now everything is ready let’s test it in browser. So lets first goto customer list like following.

CustomerList

Now I am clicking on details for first customer and Let’s see how we can use the stored procedure with parameter to fetch the customer details and below is the output.

CustomerDetails

So that’s it. It’s very easy. Hope you liked it. Stay tuned for more..Happy Programming.

Shout it

kick it on DotNetKicks.com
Share:
Friday, June 17, 2011

Get started with ASP.NET MVC and PetaPoco

Micro ORM are having their pro and cons and right now its a buzz in the Microsoft.NET developers buzz. I personally like a Micro ORM Concept and I already posted some blog posts with asp.net mvc and dapper Micro ORM. Today I am going to explain how we can use PetaPoco in asp.net mvc application. First lets get little bit introduction about PetaPoco.

PetaPoco is developed by Top Ten software and It’s Micro ORM inspired by Masive and Dapper. Following is link where you can get more information about that.
http://www.toptensoftware.com/petapoco/.

To install PetaPoco in our application first we need to add a library reference as Its already available there. so Let’s add library reference like following.

AddlibraryReference

Once click on add library reference a dialog box appears to find the the library package like following. I have written PetaPoco in search box and it will be appear in list like following.

PetaPocoNugetPackage

Select first one then click Install and It will install the PetaPoco in your application. Once installation done you will have one t4 teamplte and one PetaPoco.cs file in your model section of ASP.NET application like following.

SolutionExplorer

Now we are ready use the PetaPoco in our application. Now let’s use same DB which we have use for dapper demonstration let’s take same customer table like following.Following is a script to create table.

/****** Object:  Table [dbo].[Customer]    Script Date: 06/17/2011 02:27:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
   [CustomerId] [int] IDENTITY(1,1) NOT NULL,
   [FirstName] [nvarchar](50) NULL,
   [LastName] [nvarchar](50) NULL,
   [Address] [nvarchar](256) NULL,
   [City] [nvarchar](50) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
   [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now I have inserted some sample data in the table and now its ready to use. Now I have added a Model Entity class which contains same properties as Table columns. Just like following.
namespace CodeSimplified.Models
{
   public class Customer
   {
       public int CustomerId { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Address { get; set; }
       public string City { get; set; }
   }
}

Now we are ready with our class I have create a new class called CustomerDB to fetch customer from the database. In that class I have created method called GetCustomers which will fetch all the customer from database. Here I have created a database object of PetaPoco and then I have using Its query method to query database. Following is a code for that.
using System.Collections.Generic;

namespace CodeSimplified.Models
{
   public class CustomerDB
   {
       public IEnumerable<Customer> GetCustomers()
       {
           var databaseContext = new PetaPoco.Database("MyConnectionString");
           return databaseContext.Query<Customer>("Select * from Customer");
       }
   }
}

Now as this is for demo purpose only lets create a method in Home Controller class to get customers like following.
using System.Web.Mvc;

namespace CodeSimplified.Controllers
{
   public class HomeController : Controller
   {
       public ActionResult Index()
       {
           ViewBag.Message = "Welcome to ASP.NET MVC!";

           return View();
       }

       public ActionResult About()
       {
           return View();
       }

       public ActionResult Customer()
       {
           var customerDb = new Models.CustomerDB();
           return View(customerDb.GetCustomers());
       }
   }
}

Now once done we with Customer Method in Home Controller let’s create view for that. Here I have created a strongly typed view like following for customers.

View

Now we are done with our view also So let’s run the project and let’s see output in browser. You can see output in browser as expected like following.

Output

So it’s very easy to use PetaPoco with ASP.NET MVC. Hope you liked it. Stay tuned for more..

Shout it

kick it on DotNetKicks.com
Share:
Saturday, May 21, 2011

Delete with Dapper ORM and ASP.NET MVC 3

I have been writing few posts about Dapper ORM and ASP.NET MVC3 for data manipulation. In this post I am going to explain how we can delete the data with Dapper ORM. For your reference following are the links my previous posts.

Playing with dapper Micro ORM and ASP.NET MVC 3.0
Insert with Dapper Micro ORM and ASP.NET MVC 3
Edit/Update with dapper ORM and ASP.NET MVC 3

So to delete customer we need to have delete method in Our CustomerDB class so I have delete method into the CustomerDB class like following.

public bool Delete(int customerId)
{
try
{
    using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
    {
        sqlConnection.Open();
        string sqlQuery = "DELETE FROM [dbo].[Customer] WHERE CustomerId=@CustomerId";
        sqlConnection.Execute(sqlQuery, new {customerId});
        sqlConnection.Close();

    }
    return true;
}
catch (Exception exception)
{
    return false;
}
}
Now our delete method is ready It’s time to add ActionResult for Delete in Customer Controller like following. I have added two Action Result first will load simple delete with view and other action result will delete the data.
public ActionResult Delete(int id)
{
var customerEntities = new CustomerDB();
return View(customerEntities.GetCustomerByID(id));
}

//
// POST: /Customer/Delete/5

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
    var customerEntities = new CustomerDB();
    customerEntities.Delete(id);
    return RedirectToAction("Index");


}
catch
{
    return View();
}
}
Now It’s time to add delete view. So I have added strongly typed view like following.

DeleteView

Now everything is ready with code. So it’s time to check functionality let’s run application with Ctrl + F5. It will load browser like following.

ViewBeforeDelete

Now I am clicking on delete it will load following screen to confirm deletion.

DeleteConfirmation

Once you clicked delete button it will redirect back to customer list and record is delete as you can see in below screen.

ViewAfterDelete

So that’s it. Its very easy.. Hope you liked it.. Stay tuned for more..

Shout it
kick it on DotNetKicks.com
Share:
Friday, May 20, 2011

Edit/Update with dapper ORM and ASP.NET MVC 3

In last two post I have already written about Getting data and adding data with Dapper Micro ORM. In this post I will explain how we can use the dapper ORM for data update. For reference following is the two post links for the Dapper ORM Series.
Playing with dapper Micro ORM and ASP.NET MVC 3.0
Insert with Dapper Micro ORM and ASP.NET MVC 3
Now as you we have already created CustomerDB Class. In this database operation class we will add two more methods GetCustomerById and Update to get Customer based on CustomerId passed and another one is for updating data. Following is modified Customer DB Code.
public class CustomerDB
{
  public string Connectionstring = @"Data Source=DotNetJalps\SQLExpress;Initial Catalog=CodeBase;Integrated Security=True";

  public IEnumerable<Customer> GetCustomers()
  {
      using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
      {
          sqlConnection.Open();
          var customer = sqlConnection.Query<Customer>("Select * from Customer");
          return customer;

      }
  }

  public Customer GetCustomerByID(int customerId)
  {
      using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
      {
          sqlConnection.Open();
          string strQuery = string.Format("Select * from Customer where CustomerId={0}", customerId);
          var customer = sqlConnection.Query<Customer>(strQuery).Single<Customer>();
          return customer;

      }
  }
  public bool Update( Customer customerEntity)
  {
      try
      {
          using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
          {
              sqlConnection.Open();
              string sqlQuery = "UPDATE [dbo].[Customer] SET [FirstName] =@FirstName, [LastName] =@LastName,[Address] =@Address,[City] = @City WHERE CustomerId=@CustomerId";
              sqlConnection.Execute(sqlQuery, new {
                                                      customerEntity.FirstName, customerEntity.LastName, customerEntity.Address, customerEntity.City, customerEntity.CustomerId
                                          });
              sqlConnection.Close();

          }
          return true;
      }
      catch (Exception exception)
      {
          return false;
      }
  }
  public string  Create(Customer customerEntity)
  {
      try
      {
          using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
          {
              sqlConnection.Open();
           
              string sqlQuery = "INSERT INTO [dbo].[Customer]([FirstName],[LastName],[Address],[City]) VALUES (@FirstName,@LastName,@Address,@City)";
              sqlConnection.Execute(sqlQuery,
                                    new
                                        {
                                            customerEntity.FirstName,
                                            customerEntity.LastName,
                                            customerEntity.Address,
                                            customerEntity.City
                                        });

             
              sqlConnection.Close();

          }
          return "Created";
      }
      catch (Exception ex)
      {
          return ex.Message;
      }

  }

}


Now It’s time to modify Customer Controller. I have added two more Action Result Result like following. One for fetching data and populating view and then another one for the updating data and redirecting it to Index action result. Just like following.
public ActionResult Edit(int id)
{

 var customerEntities = new CustomerDB();
 return View(customerEntities.GetCustomerByID(id));
}

//
// POST: /Customer/Edit/5

[HttpPost]
public ActionResult Edit( Customer customer)
{
 try
 {
     // TODO: Add update logic here
     var customerEntities = new CustomerDB();
     customerEntities.Update(customer);
     return RedirectToAction("Index");
 }
 catch
 {
     return View();
 }
}
So now our ActionResult is also ready now let’s add time to add Edit View for displaying current edit data. So go edit action result and right click->Add View-> Popup will appear for that. Now let’s create a strongly typed view like following.

EditView
So now we have created view and all other stuff its time to run our application. Let’s run it and go to Customer View like following.

View
Now I am going to click edit and above data will filled in Edit View.

Edit
Now After modifying data I have clicked save and as you can see in below screen data is modified.

ModifiedView
So that’s it. It’s very easy. Stay tuned for more.. Hope you liked it..

kick it on DotNetKicks.com
Shout it
Share:
Monday, March 28, 2011

Three new Action Result Type in ASP.NET MVC 3

In ASP.NET MVC incoming browser request mapped to a controller’s action method and that action method returns type of ActionResult in response to the browsers request. I was playing bit with ASP.NET MVC3 to check out new features of ASP.NET MVC 3 and I have found three great new ActionResult Type. Below is details explanation of each one.

  1. HttpNotFound: This return type returns a error 404 on client. This action result type can be very useful when we have resources that are not found and so we can notify the client with 404 error.
  2. RedirectResult:This returns a temporary redirect code 302 or permanent redirect code 302 depending upon a Boolean flag. This kind of redirection is very important for Search Engine optimization. I have already discussed this feature with asp.net 4.0 here.
  3. HttpStatusCodeResult: Returns a user specified code so developer have choice to return specific error code.

Here are code example of Action ResultType how we can use that in code.

public ActionResult SpecificResult()
{
return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
return HttpNotFound();
}

public ActionResult PermanentRedidrect()
{
return new RedirectResult("http://jalpesh.blogspot.com");
}
Hope you liked it.. Stat tuned for more..Happy Programming
Technorati Tags: ,
Shout it
kick it on DotNetKicks.com
Share:
Friday, December 3, 2010

Output caching with ASP.NET MVC Razor

Caching data greatly increase the website performance as its not going to do server round trip. I have already mentioned how you can use Output caching in web forms in earlier blog post here. Let’s see how we can do same thing with asp.net mvc. For this example I have used asp.net mvc razor. In asp.net mvc you can use OutputCache attribute to cache the output. Just like below.

[OutputCache(VaryByParam="none",Duration=60)]
public ActionResult Index()
{
ViewModel.Message = DateTime.Now.ToString();
return View();
}
Here it will cache the view for 60 second and will not go for server round trip. Let’s see How it will look into the browser.

Temp

You can also set the output caching in web.config and and create output cache profile which you can use any where like following.
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<clear/>
<add
name="MyOuputCacheProfile"
duration="60"
varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
Here how you can use that profile.

[OutputCache(CacheProfile = "MyOuputCacheProfile")]
public ActionResult Index()
{
ViewModel.Message = DateTime.Now.ToString();
return View();
}
It support four type of settings for output caching. VaryByContentEncoding, VaryByParam, VaryByCustom,VaryByHeader. Hope this will help you!! happy Programming.

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews