SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block

Why MVC?
The purpose of many computer systems is to retrieve data from a data store and display it for the user. After the
user changes the data, the system stores the updates in the data. One problem is that the user interface tends to
change much more frequently than the data storage system. Another problem with coupling the data and user
interface pieces is that business applications tend to incorporate business logic that goes far beyond data
transmission.



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.




What is Microsoft Data Access Application Block?
It consist of single .Net based assembly, which contains all of the functionalities necessary to perform the most
common data access task against Microsoft SQL SERVER 7/2000 database.

Specifically the data access application block helps us in following:
    1. Calls stored procedure or SQL text command
    2. Specify parameter detail
    3. Return SqlDataReader, DataSet, XMLDataReader objects or single values
In general Data Access Application block is designed to encapsulate Microsoft's recommended best practices for
data access.
What you can achieve with the use of Microsoft Data Access Application Block?
    •   Minimize the data access code you need to write often to single line.
    •   Ensures that your data access logic is implemented in an efficient and effective manner.
Mainly it has got SqlHelper class provides set of static methods which you can use to execute a variety of
different command types against the database.
To have more data detail information on Microsoft Data Access Application please refer to following URL

http://www.microsoft.com/downloads/details.aspx?FamilyID=f63d1f0a-9877-4a7b-88ec-
0426b48df275&DisplayLang=en
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block

Database work :
-- Database Creation
start >> All Programs >> Microsoft SQL Server 2008 >> SQL Server Management Studio >> Connect to Server
>> New Query >> Type the following :
CREATE DATABASE DB_Customer
Press Execute/F5
-- Table Creation

CREATE TABLE Customer
(
CustomerCode INT PRIMARY KEY IDENTITY(1,1),
FirstName VARCHAR(50),
LastName VARCHAR(50),
ContactNo VARCHAR(50),
Email VARCHAR(50)
)


-- Stored Procedure Creation for Inserting Customer
CREATE PROCEDURE USP_InsertCustomer
(
@FirstName VARCHAR(50),
@LastName VARCHAR(50),
@ContactNo VARCHAR(50),
@Email VARCHAR(50)
)
AS
INSERT INTO Customer
(
FirstName,
LastName,
ContactNo,
Email
)
VALUES
(
@FirstName,
@LastName,
@ContactNo,
@Email
)
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block
-- Stored Procedure Creation for selecting all Customers

CREATE PROCEDURE USP_GetCustomers
AS
SELECT * FROM Customer
-- exec usps_proInsMember 'Munir','Shaikh','23423423','munnamax@rediffmail.com'
-- SELECT * FROM tbl_Member

Let us start with actual topic as how to implement MVC Architecture with ASP.Net and C#.

I will assume that you have installed Microsoft Data Access Block For .Net on your machine you can download
form Microsoft site.
Follow the steps as

start >> All Programs >> Microsoft Visual Studio 2008 >> Microsoft Visual Studio 2008 >>
From Menu bar select >>
File >> New Project >> New Project Window opens >> Project types (from left pane) >> Other Project Types >>
Visual Studio Solutions >> Templates (from right pane) >> Blank Solution >>
Name >> Give a proper name to your Solution (in this case we have set the name - “MyMvcArchitecture”) >>
Location >> Set a path where this Solution will reside (in this case we have it is “D:Examples”)
>> OK >>
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block

Now you will see a Solution with the name MyMvcArchitecture in Solution Explorer :




Right click on Solution name from your Solution explorer window >> Add >> New Item... >> Add New Items –
Solution Items window apprears >> Templates (right pane) >> select any of the Visual Studio installed templates
(we have selected Text File) >> Add >> TextFile1.txt is add in your solution under Solution Items folder.
Again, right click Solution name >> Add >> New Project... >>
Select Class Library under Visual C# project. Give Library Name as: AbstractLayer
Similarly you need to follow above steps for "BusinessLayer" and "DataLayer".
In short we have added three different libraries to MVC project, each these libraries themself are acting as single
project.


Now let us follow steps to add references of these class libraries
>>Right click on Business Layer
>>Add References
>>Under Project Tab
>>Select Abstract Layer and Select Data Layer
Click on OK, and references get added to the selected library.
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block

>>Right click on Data Layer
>>Add References
>>Under Project Tab
>>Select Abstract Layer
Click on OK, and references get added to the selected library.




STEPI:
Let us discuss what is "AbstractLayer" in our project?
In this project as we are dealing with the Member's basic functionalities like
    1. InsertCustomer
    2. GetCustomers
In short we will call "ExecuteNonQuery" and "ExecuteDataset" methods from Microsoft Data Access
Application block for .net
So all the getter and setter methods will be there in this which we can derive from the class and use it while
passing to object. So let us add class to AbstractLayer called as "Customer.cs" which will hold all the getter and
setter methods. As this class is acting as abstract so we need access above method by deriving this class in the
"DataLayer"


Customer.cs Class in Abstract Layer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractLayer
{
  public abstract class Customer
  {
    public int CutomerCode { get; set; }
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
    public string ContactNo{ get; set; }
    public string Email{ get; set; }
  }
}

Just a minute :
What is Abstract Class?
What are get and set properties?
What is a namespace?
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block

STEPII:
Let us discuss what is "DataLayer" in our project?


Copy SqlHelper.cs from above path and add under "DataLayer" in our project. We will add class called as
"IdataAccess.cs" in "DataLayer" is basically acting as an interface code goes as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using AbstractLayer;

namespace DataLayer
{
  public interface IdataAccess
  {
    string InsertCustomer(AbstractLayer.Customer objCustomer);
    DataSet GetCustomers();
  }
}



which will hold all the signatures to implement this interface signature we have to have another class so we will
add common class "SqlDataAccess.cs" under the same layer. Code goes as below :
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using Microsoft.ApplicationBlocks.Data;
using System.Data.SqlClient;


namespace DataLayer
{
  public partial class SqlDataAccess : IdataAccess
  {
    string strConnString = "";

     public SqlDataAccess()
     {
       strConnString = getConnString();
     }
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block
        public string getConnString()
        {
          return ConfigurationSettings.AppSettings["Customer"].ToString();
        }
        public SqlDataAccess(string strConn)
        {
          strConnString = strConn;
        }
        public SqlConnection setConnection()
        {
          SqlConnection objConn = new SqlConnection(getConnString());
          return objConn;
        }
    }
}



CustomerData.cs
Change the logical name of the class to SqlDataAccess

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using System.Data;

namespace DataLayer
{
   public partial class SqlDataAccess
   {
     #region IdataAccess Members
     public string InsertCustomer(AbstractLayer.Customer objCustomer)
     {
        SqlTransaction objTrans = null;
        SqlConnection myConnection = new SqlConnection(strConnString);
        try
        {
            myConnection.Open();
            objTrans = myConnection.BeginTransaction();
            SqlParameter[] arrParam = new SqlParameter[4];
            arrParam[0] = new SqlParameter("@FirstName", objCustomer.FirstName);
            arrParam[1] = new SqlParameter("@LastName", objCustomer.LastName);
            arrParam[2] = new SqlParameter("@ContactNo", objCustomer.ContactNo);
            arrParam[3] = new SqlParameter("@Email", objCustomer.Email);
            SqlHelper.ExecuteNonQuery(strConnString, CommandType.StoredProcedure, "USP_InsertCustomer",
arrParam);
        }
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block
       catch (Exception Ex)
       {
          objTrans.Rollback();
          string sError = Ex.Message.ToString();
          return "Error";
       }
       finally
       {
          myConnection.Close();
       }
       return "Success";
    }
    public DataSet GetCustomers()
    {
      DataSet ds = SqlHelper.ExecuteDataset(strConnString, CommandType.StoredProcedure,
"USP_GetCustomers");
      return ds;
    }
    #endregion
  }
}

STEPIII:
BusinessLayer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using AbstractLayer;
using DataLayer;
namespace BusinessLayer
{
  public class CustomerMember : AbstractLayer.Customer
  {
    DataLayer.SqlDataAccess objSqlDataAccess = new SqlDataAccess();
    public DataSet GetCustomers()
    {
       IdataAccess objIdataAccess = new SqlDataAccess(objSqlDataAccess.getConnString());
       return objIdataAccess.GetCustomers();
    }
    public string InsertCustomer(AbstractLayer.Customer objCustomer)
    {
       IdataAccess objIdataAccess = new SqlDataAccess(objSqlDataAccess.getConnString());
       return objIdataAccess.InsertCustomer(objCustomer);
    }
  }
}
Now that you are done with all the three layers, you will now create a Website in the same path(not mandatory).
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block

Now let us follow steps to add references of a class libraries to our WebSite
>>Right click on WebSite
>>Add References
>>Under Project Tab
>>Select Business Layer
Click on OK, and references get added to the WebSite.


When you add the reference, you can see the DLL files in the Bin folder of the WebSite.


Add a for to your WebSite and name it as Customer.aspx. Make following changes :


Add connection string in web.config
<appSettings>
    <add key="Customer" value="Data Source=BizServer;Initial Catalog=DB_Customer;Integrated
Security=True"/>
  </appSettings>

Code for Customer.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomerInsert.aspx.cs"
Inherits="_CustomerInsert" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Customer Master</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
      <fieldset>
         <legend>Insert Customer Details</legend>
         <table width="600px">
            <tr>
               <td width="150px">
                  First Name :
               </td>
               <td width="450px">
                  <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
               </td>
            </tr>
            <tr>
               <td>
                  Last Name :
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block
              </td>
              <td>
                 <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 Contact No. :
              </td>
              <td>
                 <asp:TextBox ID="txtContactNo" runat="server"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td>
                 Email :
              </td>
              <td>
                 <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
              </td>
           </tr>
           <tr>
              <td colspan="2" align="left">
                 <asp:Button ID="btnSubmit" runat="server" Text="Submit"
                   onclick="btnSubmit_Click" />
              &nbsp;<asp:Button ID="btnList" runat="server" onclick="btnList_Click" Text="List" />
&nbsp;<asp:Button ID="btnRefresh" runat="server" onclick="btnRefresh_Click" Text="Refresh" />
              </td>
           </tr>
           <tr>
              <td colspan="2" align="left">
                 <asp:Label ID="lblMessage" runat="server"></asp:Label>
              </td>
           </tr>
           <tr>
              <td colspan="2" align="left">
                 <asp:GridView ID="GridView1" runat="server">
                 </asp:GridView>
              </td>
           </tr>
        </table>
     </fieldset>
  </div>
  </form>
</body>
</html>
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block

Code for Customer.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer;
using System.Data;

public partial class _CustomerInsert : System.Web.UI.Page
{
  BusinessLayer.CustomerMember objCustomer = new CustomerMember();
  string strErrorMsg = string.Empty;
  string strReturnVal = string.Empty;
  protected void Page_Load(object sender, EventArgs e)
  {
     if (!Page.IsPostBack)
     {
         txtFirstName.Focus();
     }
  }
  protected void btnSubmit_Click(object sender, EventArgs e)
  {
     InsertCustomer();
  }

  private void InsertCustomer()
  {
     try
     {
         objCustomer.FirstName = txtFirstName.Text.Trim();
         objCustomer.LastName = txtLastName.Text.Trim();
         objCustomer.ContactNo = txtContactNo.Text.Trim();
         objCustomer.Email = txtEmail.Text.Trim();
         strReturnVal = objCustomer.InsertCustomer(objCustomer);


  if (strReturnVal == "Success")
        {
           lblMessage.Text = "Record saved successfully";
           Clear();
           GetCustomers();
        }
        else
        {
           lblMessage.Text = "An error has occured while processing your request.";
        }
     }
     catch (Exception ex)
     {
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block
         strErrorMsg = ex.Message;
     }
 }

 private void Clear()
 {
    txtFirstName.Text = string.Empty;
    txtLastName.Text = string.Empty;
    txtContactNo.Text = "";
    txtEmail.Text = "";
    txtFirstName.Focus();
 }

 protected void btnList_Click(object sender, EventArgs e)
 {
   GetCustomers();
 }

 private void GetCustomers()
 {
    DataSet ds = objCustomer.GetCustomers();
    GridView1.DataSource = ds;
    GridView1.DataBind();
 }
 protected void btnRefresh_Click(object sender, EventArgs e)
 {
    Clear();
    lblMessage.Text = string.Empty;
    GridView1.DataSource = null;
    GridView1.DataBind();
 }
}
OUTPUT :
MVC Architecture in ASP. Net using C# and Microsoft
Data Access Application block
And that's all.

As normal developer you will always think that this is very big and vast procedure, but remember
the benefits.
Advantages:
    1. Code will be separated from the Data layer due to which it will be very easy to maintain for the long
       run of the project, as every system keep on going under modification / enhancement so at that time
       you will have to just go on adding view files and signature in the interface and its implementation.
    2. Easy to understand and code transfer. i.e. when want to implement at client's server you just need
       to upload view files and DLL fields.
    3. It increases the system performance as there is no need to do connection pooling etc.
    4. Easy to maintain documentation
We at Biz Technologies Private Limited have implemented above MVC Architecture for some of our
biggest system and working much better than normal way.


Things you learn after completion of this chapter:
   1. MVC Architecture
   2. Why MVC Architecture?
   3. Microsoft Data Access Application Block
   4. Abstract Class and when to use it?
   5. Interface
   6. Get Set Properties
   7. Partial Class and its use
   8. Fetching and Inserting records using MVC (3 Tier) Architecture
   9. Namespace
   10. Assemblies
   11. Class Libraries
   12. DLLs
   13. SQL Server Stored Procedures

Contenu connexe

Tendances

Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETFernando G. Guerrero
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integrationwebhostingguy
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Watersmichael.labriola
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaalifha12
 
Time-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesTime-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesChema Alonso
 
Step by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsStep by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsNilesh kumar Jadav
 

Tendances (17)

Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
AJAX
AJAXAJAX
AJAX
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NET
 
Data Binding
Data BindingData Binding
Data Binding
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
5.C#
5.C#5.C#
5.C#
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
 
Time-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesTime-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy Queries
 
Step by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsStep by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView Tutorials
 

En vedette

Cmms3 presentation (Rev Apr2015)
Cmms3 presentation (Rev Apr2015)Cmms3 presentation (Rev Apr2015)
Cmms3 presentation (Rev Apr2015)lt1968
 
Chris Brown and Rihanna Podcast Presentation
Chris Brown and Rihanna Podcast PresentationChris Brown and Rihanna Podcast Presentation
Chris Brown and Rihanna Podcast PresentationJessica Joanna Lindley
 
Chris Brown & Rihanna Podcast Presentation
Chris Brown & Rihanna Podcast PresentationChris Brown & Rihanna Podcast Presentation
Chris Brown & Rihanna Podcast PresentationJessica Joanna Lindley
 
Storyboard
StoryboardStoryboard
Storyboardalgator
 
RAMCUBE - CODE3 software
RAMCUBE - CODE3 softwareRAMCUBE - CODE3 software
RAMCUBE - CODE3 softwarelt1968
 
Presentacion manuelatrejo
Presentacion manuelatrejoPresentacion manuelatrejo
Presentacion manuelatrejoIvanFerragni
 
RAMCUBE - engineering services
RAMCUBE - engineering servicesRAMCUBE - engineering services
RAMCUBE - engineering serviceslt1968
 
Storyboard
StoryboardStoryboard
Storyboardalgator
 

En vedette (14)

Cmms3 presentation (Rev Apr2015)
Cmms3 presentation (Rev Apr2015)Cmms3 presentation (Rev Apr2015)
Cmms3 presentation (Rev Apr2015)
 
Chris Brown and Rihanna Podcast Presentation
Chris Brown and Rihanna Podcast PresentationChris Brown and Rihanna Podcast Presentation
Chris Brown and Rihanna Podcast Presentation
 
Nabi muhammad keliru terima wahyu
Nabi muhammad keliru terima wahyuNabi muhammad keliru terima wahyu
Nabi muhammad keliru terima wahyu
 
Chris Brown & Rihanna Podcast Presentation
Chris Brown & Rihanna Podcast PresentationChris Brown & Rihanna Podcast Presentation
Chris Brown & Rihanna Podcast Presentation
 
Storyboard
StoryboardStoryboard
Storyboard
 
RAMCUBE - CODE3 software
RAMCUBE - CODE3 softwareRAMCUBE - CODE3 software
RAMCUBE - CODE3 software
 
Removals Gloucester
Removals GloucesterRemovals Gloucester
Removals Gloucester
 
Presentation1tush bday
Presentation1tush bdayPresentation1tush bday
Presentation1tush bday
 
Presentacion manuelatrejo
Presentacion manuelatrejoPresentacion manuelatrejo
Presentacion manuelatrejo
 
Sejarah pra islam
Sejarah pra islamSejarah pra islam
Sejarah pra islam
 
RAMCUBE - engineering services
RAMCUBE - engineering servicesRAMCUBE - engineering services
RAMCUBE - engineering services
 
Nabi muhammad keliru terima wahyu
Nabi muhammad keliru terima wahyuNabi muhammad keliru terima wahyu
Nabi muhammad keliru terima wahyu
 
Storyboard
StoryboardStoryboard
Storyboard
 
99 nama allah
99 nama allah99 nama allah
99 nama allah
 

Similaire à Mvc acchitecture

Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Labs And Walkthroughs
Labs And WalkthroughsLabs And Walkthroughs
Labs And WalkthroughsBryan Tuttle
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamentalldcphuc
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
3 tier architecture in asp.net
3 tier architecture in asp.net3 tier architecture in asp.net
3 tier architecture in asp.netRavi Bansal
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributessonia merchant
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAlfa Gama Omega
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)M Ahsan Khan
 
Web application to keep track of time spent on projects
Web application to keep track of time spent on projectsWeb application to keep track of time spent on projects
Web application to keep track of time spent on projectsravi yadav
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
Adding a view
Adding a viewAdding a view
Adding a viewNhan Do
 

Similaire à Mvc acchitecture (20)

Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Labs And Walkthroughs
Labs And WalkthroughsLabs And Walkthroughs
Labs And Walkthroughs
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
CAD Report
CAD ReportCAD Report
CAD Report
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
3 tier architecture in asp.net
3 tier architecture in asp.net3 tier architecture in asp.net
3 tier architecture in asp.net
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
Web application to keep track of time spent on projects
Web application to keep track of time spent on projectsWeb application to keep track of time spent on projects
Web application to keep track of time spent on projects
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
Adding a view
Adding a viewAdding a view
Adding a view
 

Mvc acchitecture

  • 1. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block Why MVC? The purpose of many computer systems is to retrieve data from a data store and display it for the user. After the user changes the data, the system stores the updates in the data. One problem is that the user interface tends to change much more frequently than the data storage system. Another problem with coupling the data and user interface pieces is that business applications tend to incorporate business logic that goes far beyond data transmission. 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. What is Microsoft Data Access Application Block? It consist of single .Net based assembly, which contains all of the functionalities necessary to perform the most common data access task against Microsoft SQL SERVER 7/2000 database. Specifically the data access application block helps us in following: 1. Calls stored procedure or SQL text command 2. Specify parameter detail 3. Return SqlDataReader, DataSet, XMLDataReader objects or single values In general Data Access Application block is designed to encapsulate Microsoft's recommended best practices for data access. What you can achieve with the use of Microsoft Data Access Application Block? • Minimize the data access code you need to write often to single line. • Ensures that your data access logic is implemented in an efficient and effective manner. Mainly it has got SqlHelper class provides set of static methods which you can use to execute a variety of different command types against the database. To have more data detail information on Microsoft Data Access Application please refer to following URL http://www.microsoft.com/downloads/details.aspx?FamilyID=f63d1f0a-9877-4a7b-88ec- 0426b48df275&DisplayLang=en
  • 2. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block Database work : -- Database Creation start >> All Programs >> Microsoft SQL Server 2008 >> SQL Server Management Studio >> Connect to Server >> New Query >> Type the following : CREATE DATABASE DB_Customer Press Execute/F5 -- Table Creation CREATE TABLE Customer ( CustomerCode INT PRIMARY KEY IDENTITY(1,1), FirstName VARCHAR(50), LastName VARCHAR(50), ContactNo VARCHAR(50), Email VARCHAR(50) ) -- Stored Procedure Creation for Inserting Customer CREATE PROCEDURE USP_InsertCustomer ( @FirstName VARCHAR(50), @LastName VARCHAR(50), @ContactNo VARCHAR(50), @Email VARCHAR(50) ) AS INSERT INTO Customer ( FirstName, LastName, ContactNo, Email ) VALUES ( @FirstName, @LastName, @ContactNo, @Email )
  • 3. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block -- Stored Procedure Creation for selecting all Customers CREATE PROCEDURE USP_GetCustomers AS SELECT * FROM Customer -- exec usps_proInsMember 'Munir','Shaikh','23423423','munnamax@rediffmail.com' -- SELECT * FROM tbl_Member Let us start with actual topic as how to implement MVC Architecture with ASP.Net and C#. I will assume that you have installed Microsoft Data Access Block For .Net on your machine you can download form Microsoft site. Follow the steps as start >> All Programs >> Microsoft Visual Studio 2008 >> Microsoft Visual Studio 2008 >> From Menu bar select >> File >> New Project >> New Project Window opens >> Project types (from left pane) >> Other Project Types >> Visual Studio Solutions >> Templates (from right pane) >> Blank Solution >> Name >> Give a proper name to your Solution (in this case we have set the name - “MyMvcArchitecture”) >> Location >> Set a path where this Solution will reside (in this case we have it is “D:Examples”) >> OK >>
  • 4. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block Now you will see a Solution with the name MyMvcArchitecture in Solution Explorer : Right click on Solution name from your Solution explorer window >> Add >> New Item... >> Add New Items – Solution Items window apprears >> Templates (right pane) >> select any of the Visual Studio installed templates (we have selected Text File) >> Add >> TextFile1.txt is add in your solution under Solution Items folder. Again, right click Solution name >> Add >> New Project... >> Select Class Library under Visual C# project. Give Library Name as: AbstractLayer Similarly you need to follow above steps for "BusinessLayer" and "DataLayer". In short we have added three different libraries to MVC project, each these libraries themself are acting as single project. Now let us follow steps to add references of these class libraries >>Right click on Business Layer >>Add References >>Under Project Tab >>Select Abstract Layer and Select Data Layer Click on OK, and references get added to the selected library.
  • 5. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block >>Right click on Data Layer >>Add References >>Under Project Tab >>Select Abstract Layer Click on OK, and references get added to the selected library. STEPI: Let us discuss what is "AbstractLayer" in our project? In this project as we are dealing with the Member's basic functionalities like 1. InsertCustomer 2. GetCustomers In short we will call "ExecuteNonQuery" and "ExecuteDataset" methods from Microsoft Data Access Application block for .net So all the getter and setter methods will be there in this which we can derive from the class and use it while passing to object. So let us add class to AbstractLayer called as "Customer.cs" which will hold all the getter and setter methods. As this class is acting as abstract so we need access above method by deriving this class in the "DataLayer" Customer.cs Class in Abstract Layer using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AbstractLayer { public abstract class Customer { public int CutomerCode { get; set; } public string FirstName{ get; set; } public string LastName{ get; set; } public string ContactNo{ get; set; } public string Email{ get; set; } } } Just a minute : What is Abstract Class? What are get and set properties? What is a namespace?
  • 6. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block STEPII: Let us discuss what is "DataLayer" in our project? Copy SqlHelper.cs from above path and add under "DataLayer" in our project. We will add class called as "IdataAccess.cs" in "DataLayer" is basically acting as an interface code goes as below using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using AbstractLayer; namespace DataLayer { public interface IdataAccess { string InsertCustomer(AbstractLayer.Customer objCustomer); DataSet GetCustomers(); } } which will hold all the signatures to implement this interface signature we have to have another class so we will add common class "SqlDataAccess.cs" under the same layer. Code goes as below : using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Configuration; using Microsoft.ApplicationBlocks.Data; using System.Data.SqlClient; namespace DataLayer { public partial class SqlDataAccess : IdataAccess { string strConnString = ""; public SqlDataAccess() { strConnString = getConnString(); }
  • 7. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block public string getConnString() { return ConfigurationSettings.AppSettings["Customer"].ToString(); } public SqlDataAccess(string strConn) { strConnString = strConn; } public SqlConnection setConnection() { SqlConnection objConn = new SqlConnection(getConnString()); return objConn; } } } CustomerData.cs Change the logical name of the class to SqlDataAccess using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Microsoft.ApplicationBlocks.Data; using System.Data; namespace DataLayer { public partial class SqlDataAccess { #region IdataAccess Members public string InsertCustomer(AbstractLayer.Customer objCustomer) { SqlTransaction objTrans = null; SqlConnection myConnection = new SqlConnection(strConnString); try { myConnection.Open(); objTrans = myConnection.BeginTransaction(); SqlParameter[] arrParam = new SqlParameter[4]; arrParam[0] = new SqlParameter("@FirstName", objCustomer.FirstName); arrParam[1] = new SqlParameter("@LastName", objCustomer.LastName); arrParam[2] = new SqlParameter("@ContactNo", objCustomer.ContactNo); arrParam[3] = new SqlParameter("@Email", objCustomer.Email); SqlHelper.ExecuteNonQuery(strConnString, CommandType.StoredProcedure, "USP_InsertCustomer", arrParam); }
  • 8. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block catch (Exception Ex) { objTrans.Rollback(); string sError = Ex.Message.ToString(); return "Error"; } finally { myConnection.Close(); } return "Success"; } public DataSet GetCustomers() { DataSet ds = SqlHelper.ExecuteDataset(strConnString, CommandType.StoredProcedure, "USP_GetCustomers"); return ds; } #endregion } } STEPIII: BusinessLayer using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using AbstractLayer; using DataLayer; namespace BusinessLayer { public class CustomerMember : AbstractLayer.Customer { DataLayer.SqlDataAccess objSqlDataAccess = new SqlDataAccess(); public DataSet GetCustomers() { IdataAccess objIdataAccess = new SqlDataAccess(objSqlDataAccess.getConnString()); return objIdataAccess.GetCustomers(); } public string InsertCustomer(AbstractLayer.Customer objCustomer) { IdataAccess objIdataAccess = new SqlDataAccess(objSqlDataAccess.getConnString()); return objIdataAccess.InsertCustomer(objCustomer); } } } Now that you are done with all the three layers, you will now create a Website in the same path(not mandatory).
  • 9. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block Now let us follow steps to add references of a class libraries to our WebSite >>Right click on WebSite >>Add References >>Under Project Tab >>Select Business Layer Click on OK, and references get added to the WebSite. When you add the reference, you can see the DLL files in the Bin folder of the WebSite. Add a for to your WebSite and name it as Customer.aspx. Make following changes : Add connection string in web.config <appSettings> <add key="Customer" value="Data Source=BizServer;Initial Catalog=DB_Customer;Integrated Security=True"/> </appSettings> Code for Customer.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomerInsert.aspx.cs" Inherits="_CustomerInsert" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Customer Master</title> </head> <body> <form id="form1" runat="server"> <div> <fieldset> <legend>Insert Customer Details</legend> <table width="600px"> <tr> <td width="150px"> First Name : </td> <td width="450px"> <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Last Name :
  • 10. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block </td> <td> <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Contact No. : </td> <td> <asp:TextBox ID="txtContactNo" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Email : </td> <td> <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2" align="left"> <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /> &nbsp;<asp:Button ID="btnList" runat="server" onclick="btnList_Click" Text="List" /> &nbsp;<asp:Button ID="btnRefresh" runat="server" onclick="btnRefresh_Click" Text="Refresh" /> </td> </tr> <tr> <td colspan="2" align="left"> <asp:Label ID="lblMessage" runat="server"></asp:Label> </td> </tr> <tr> <td colspan="2" align="left"> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </td> </tr> </table> </fieldset> </div> </form> </body> </html>
  • 11. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block Code for Customer.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BusinessLayer; using System.Data; public partial class _CustomerInsert : System.Web.UI.Page { BusinessLayer.CustomerMember objCustomer = new CustomerMember(); string strErrorMsg = string.Empty; string strReturnVal = string.Empty; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { txtFirstName.Focus(); } } protected void btnSubmit_Click(object sender, EventArgs e) { InsertCustomer(); } private void InsertCustomer() { try { objCustomer.FirstName = txtFirstName.Text.Trim(); objCustomer.LastName = txtLastName.Text.Trim(); objCustomer.ContactNo = txtContactNo.Text.Trim(); objCustomer.Email = txtEmail.Text.Trim(); strReturnVal = objCustomer.InsertCustomer(objCustomer); if (strReturnVal == "Success") { lblMessage.Text = "Record saved successfully"; Clear(); GetCustomers(); } else { lblMessage.Text = "An error has occured while processing your request."; } } catch (Exception ex) {
  • 12. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block strErrorMsg = ex.Message; } } private void Clear() { txtFirstName.Text = string.Empty; txtLastName.Text = string.Empty; txtContactNo.Text = ""; txtEmail.Text = ""; txtFirstName.Focus(); } protected void btnList_Click(object sender, EventArgs e) { GetCustomers(); } private void GetCustomers() { DataSet ds = objCustomer.GetCustomers(); GridView1.DataSource = ds; GridView1.DataBind(); } protected void btnRefresh_Click(object sender, EventArgs e) { Clear(); lblMessage.Text = string.Empty; GridView1.DataSource = null; GridView1.DataBind(); } } OUTPUT :
  • 13. MVC Architecture in ASP. Net using C# and Microsoft Data Access Application block And that's all. As normal developer you will always think that this is very big and vast procedure, but remember the benefits. Advantages: 1. Code will be separated from the Data layer due to which it will be very easy to maintain for the long run of the project, as every system keep on going under modification / enhancement so at that time you will have to just go on adding view files and signature in the interface and its implementation. 2. Easy to understand and code transfer. i.e. when want to implement at client's server you just need to upload view files and DLL fields. 3. It increases the system performance as there is no need to do connection pooling etc. 4. Easy to maintain documentation We at Biz Technologies Private Limited have implemented above MVC Architecture for some of our biggest system and working much better than normal way. Things you learn after completion of this chapter: 1. MVC Architecture 2. Why MVC Architecture? 3. Microsoft Data Access Application Block 4. Abstract Class and when to use it? 5. Interface 6. Get Set Properties 7. Partial Class and its use 8. Fetching and Inserting records using MVC (3 Tier) Architecture 9. Namespace 10. Assemblies 11. Class Libraries 12. DLLs 13. SQL Server Stored Procedures