SlideShare a Scribd company logo
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

More Related Content

PDF
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
PDF
ASPNET_MVC_Tutorial_06_CS
DOCX
Simple ado program by visual studio
DOCX
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
PDF
Data Binding and Data Grid View Classes
DOCX
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
PPTX
Ch 7 data binding
PPTX
Grid View Control CS
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ASPNET_MVC_Tutorial_06_CS
Simple ado program by visual studio
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Data Binding and Data Grid View Classes
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ch 7 data binding
Grid View Control CS

What's hot (17)

PDF
Mvc interview questions – deep dive jinal desai
PPT
PPT
Ado.net
PPT
ADO.NET
PPT
ASP.NET 08 - Data Binding And Representation
PPTX
Ch06 ado.net fundamentals
PPT
Dealing with SQL Security from ADO.NET
PDF
Data Binding
PPTX
ADO.NET by ASP.NET Development Company in india
PPT
SQL Server 2005 CLR Integration
DOCX
Android sql examples
PDF
ajax_pdf
PPTX
PPT
Diving in the Flex Data Binding Waters
PDF
Mvc4 crud operations.-kemuning senja
PDF
Time-Based Blind SQL Injection Using Heavy Queries
PDF
Step by Step Asp.Net GridView Tutorials
Mvc interview questions – deep dive jinal desai
Ado.net
ADO.NET
ASP.NET 08 - Data Binding And Representation
Ch06 ado.net fundamentals
Dealing with SQL Security from ADO.NET
Data Binding
ADO.NET by ASP.NET Development Company in india
SQL Server 2005 CLR Integration
Android sql examples
ajax_pdf
Diving in the Flex Data Binding Waters
Mvc4 crud operations.-kemuning senja
Time-Based Blind SQL Injection Using Heavy Queries
Step by Step Asp.Net GridView Tutorials
Ad

Viewers also liked (14)

PDF
Cmms3 presentation (Rev Apr2015)
PPTX
Chris Brown and Rihanna Podcast Presentation
PDF
Nabi muhammad keliru terima wahyu
PPTX
Chris Brown & Rihanna Podcast Presentation
PPTX
Storyboard
PDF
RAMCUBE - CODE3 software
PDF
Removals Gloucester
PPTX
Presentation1tush bday
PPTX
Presentacion manuelatrejo
PDF
Sejarah pra islam
PDF
RAMCUBE - engineering services
PDF
Nabi muhammad keliru terima wahyu
PPT
Storyboard
PDF
Cmms3 presentation (Rev Apr2015)
Chris Brown and Rihanna Podcast Presentation
Nabi muhammad keliru terima wahyu
Chris Brown & Rihanna Podcast Presentation
Storyboard
RAMCUBE - CODE3 software
Removals Gloucester
Presentation1tush bday
Presentacion manuelatrejo
Sejarah pra islam
RAMCUBE - engineering services
Nabi muhammad keliru terima wahyu
Storyboard
Ad

Similar to Mvc acchitecture (20)

PPTX
Getting started with entity framework
DOCX
SetFocus Portfolio
PPTX
C# Code Samples
PPTX
Mi 09 N4 Theodore Columbus Portfolio
PPTX
ASP.NET Lecture 4
PPT
2006 DDD4: Data access layers - Convenience vs. Control and Performance?
DOCX
Framework 4
PPTX
ASP.NET MVC as the next step in web development
PPTX
Jornadas tecnologicas2012mvvm
PPTX
Common ASP.NET Design Patterns - Telerik India DevCon 2013
PPTX
Web-Dev Portfolio
DOC
10265 developing data access solutions with microsoft visual studio 2010
PDF
C# .NET Developer Portfolio
PPT
Visual Studio.NET
PPT
Visual studio.net
DOCX
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
PPTX
Hidden Facts of .NET Language Gems
PPTX
C# and ASP.NET Code and Data-Access Security
PPSX
06 asp.net session08
PPTX
PATTERNS07 - Data Representation in C#
Getting started with entity framework
SetFocus Portfolio
C# Code Samples
Mi 09 N4 Theodore Columbus Portfolio
ASP.NET Lecture 4
2006 DDD4: Data access layers - Convenience vs. Control and Performance?
Framework 4
ASP.NET MVC as the next step in web development
Jornadas tecnologicas2012mvvm
Common ASP.NET Design Patterns - Telerik India DevCon 2013
Web-Dev Portfolio
10265 developing data access solutions with microsoft visual studio 2010
C# .NET Developer Portfolio
Visual Studio.NET
Visual studio.net
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
Hidden Facts of .NET Language Gems
C# and ASP.NET Code and Data-Access Security
06 asp.net session08
PATTERNS07 - Data Representation in C#

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