Mvc acchitecture

808 views

Published on

1 Comment
0 Likes
Statistics
Notes
  • Be the first to like this

No Downloads
Views
Total views
808
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
21
Comments
1
Likes
0
Embeds 0
No embeds

No notes for slide

Mvc acchitecture

  1. 1. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application blockWhy MVC?The purpose of many computer systems is to retrieve data from a data store and display it for the user. After theuser changes the data, the system stores the updates in the data. One problem is that the user interface tends tochange much more frequently than the data storage system. Another problem with coupling the data and userinterface pieces is that business applications tend to incorporate business logic that goes far beyond datatransmission.The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and theactions based on user input into three separate classes [Burbeck92]:Model. The model manages the behavior and data of the application domain, responds to requests forinformation about its state (usually from the view), and responds to instructions to change state (usually from thecontroller).View. The view manages the display of information.Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/orthe 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 mostcommon 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 valuesIn general Data Access Application block is designed to encapsulate Microsofts recommended best practices fordata 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 ofdifferent command types against the database.To have more data detail information on Microsoft Data Access Application please refer to following URLhttp://www.microsoft.com/downloads/details.aspx?FamilyID=f63d1f0a-9877-4a7b-88ec-0426b48df275&DisplayLang=en
  2. 2. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application blockDatabase work :-- Database Creationstart >> All Programs >> Microsoft SQL Server 2008 >> SQL Server Management Studio >> Connect to Server>> New Query >> Type the following :CREATE DATABASE DB_CustomerPress Execute/F5-- Table CreationCREATE 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 CustomerCREATE PROCEDURE USP_InsertCustomer(@FirstName VARCHAR(50),@LastName VARCHAR(50),@ContactNo VARCHAR(50),@Email VARCHAR(50))ASINSERT INTO Customer(FirstName,LastName,ContactNo,Email)VALUES(@FirstName,@LastName,@ContactNo,@Email)
  3. 3. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application block-- Stored Procedure Creation for selecting all CustomersCREATE PROCEDURE USP_GetCustomersASSELECT * FROM Customer-- exec usps_proInsMember Munir,Shaikh,23423423,munnamax@rediffmail.com-- SELECT * FROM tbl_MemberLet 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 downloadform Microsoft site.Follow the steps asstart >> 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. 4. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application blockNow 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: AbstractLayerSimilarly 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 singleproject.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 LayerClick on OK, and references get added to the selected library.
  5. 5. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application block>>Right click on Data Layer>>Add References>>Under Project Tab>>Select Abstract LayerClick 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 Members basic functionalities like 1. InsertCustomer 2. GetCustomersIn short we will call "ExecuteNonQuery" and "ExecuteDataset" methods from Microsoft Data AccessApplication block for .netSo all the getter and setter methods will be there in this which we can derive from the class and use it whilepassing to object. So let us add class to AbstractLayer called as "Customer.cs" which will hold all the getter andsetter 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 Layerusing 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. 6. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application blockSTEPII: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 belowusing 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 willadd 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. 7. MVC Architecture in ASP. Net using C# and MicrosoftData 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.csChange the logical name of the class to SqlDataAccessusing 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. 8. MVC Architecture in ASP. Net using C# and MicrosoftData 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:BusinessLayerusing 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. 9. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application blockNow 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 LayerClick 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;IntegratedSecurity=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. 10. MVC Architecture in ASP. Net using C# and MicrosoftData 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. 11. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application blockCode for Customer.aspx.csusing 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. 12. MVC Architecture in ASP. Net using C# and MicrosoftData 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. 13. MVC Architecture in ASP. Net using C# and MicrosoftData Access Application blockAnd thats all.As normal developer you will always think that this is very big and vast procedure, but rememberthe 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 clients 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 documentationWe at Biz Technologies Private Limited have implemented above MVC Architecture for some of ourbiggest 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

×