The document discusses implementing MVC architecture in ASP.Net using C# and the Microsoft Data Access Application block. It describes creating class libraries for the abstract, business and data layers. The abstract layer defines a customer class. The data layer implements data access interfaces and uses the application block. The business layer calls the data layer. A web application is created that references the business layer and allows inserting and viewing customers by calling its methods. Implementing MVC in this way separates concerns and improves maintainability.
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 :
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