Asp.net2.0+sql Server2005 to build multilayer applications

Source: Internet
Author: User
Tags contains getdate header new features management studio sql server management sql server management studio visual studio
Asp.net|server

With the release of. NET 2.0, Web applications built with ASP.net 2.0来 will be made easier. With ASP.net 2.0 and SQL Server 2005, it will be easier to build a multi-tier architecture Web application than asp.net 1.1. In this article, you will build an example of a simple multi-tier application using asp.net 2.0 and SQL Server (. NET) using the April CTP version using Visual Studio 2,sql Server 2005. Some of the new features in NET 2.0 and SQL Server 2005, such as Objectdatasource,master pages,clr stored procedures, TableAdapter wizards, and so on.

Introduction to Multilayer Applications

What is the application of multi-tier architecture? The traditional CLR pattern is a typical example of a two-tier application, the client/server model. This mode is only a two-tier architecture, the client issues a request to the server, the server will handle a large number of requests from the client, after business logic operation and processing, and then return to the client. The two-tier architecture model clearly does not meet the modern internet-trend enterprise computing processing requirements, because of its deployment, load balancing processing is very cumbersome, so there are three-tier architecture and even multi-layer architecture appears. The core idea of multi-layer architecture is that the whole business application is divided into presentation layer-business layer-data access Layer-database, which divides the client's presentation layer, business logic access, data access and database access clearly, which is beneficial to the development, maintenance, deployment and extension of the system. Here's a typical example of how to build a multi-tier application using asp.net 2.0 and SQL Server 2005来.

Our example is simple enough to illustrate the problem. Our application has only two pages, the first page will call the author table of the pubs database in the SQL Server 2005 database, list all the authors, and then click on each author's link to show which books the author has written.

The following figure illustrates our architecture for this multi-tier application under the ASP.net 2.0 architecture:


As we can see from the above illustration, we will build this multi-tier application in this way. First of all, looking at the top of the graph, the blue part is the presentation layer, the appearance of our web application, the layer directly dealing with users, such as processing input and output, in ASP.net 2.0, we can use the Master page template technology, To build a page that is consistent in its appearance style (which is mentioned below). Next is the business logic layer, which typically handles business logic and related calculations directly in the layer, and in asp.net 2.0 we can easily handle the business logic layer by using the ObjectDataSource control.

The business logic layer then deals with the data access layer (layer). The role of the data access layer is to separate all the related process business of database operation, when the structure of the database changes, only need to modify the code of the data access layer, no need to modify other places, it will be convenient and different database to deal with. In ASP.net 2.0, by using the TableAdapter Data Wizard, you can quickly generate data access layer code from existing databases, and basically do not need to write any code.

Finally, we create a stored procedure by using the new SQL Server 2005 feature: The CLR stored procedure (CLR stored procedure). In SQL Server 2005, you can use the familiar. NET language to create a stored procedure.

   CLR stored procedures using SQL Server 2005

One of the features of SQL Server 2005 is the integration of the. NET CLR. The advantage of consolidating the. NET CLR is that it makes it easy for developers to create stored procedures, triggers, custom functions, and so on, using their familiar. NET language. In this article, you will create a stored procedure in C #. Why not use T-SQL to create a stored procedure? Because T-SQL has been developed for a long time, it has its limitations in some cases, such as T-SQL is not object-oriented, some syntax is too complex. If you use object-oriented. NET language to write data objects such as stored procedures, you can write more robust and excellent stored procedures because of the powerful nature of the. NET language. Note that using SQL Server 2005. NET writes the stored procedure, all is and uses. NET language to write a general application of the same program, are managed code. In addition, the CLR programming language provides rich constructs (such as arrays and lists) that are not in T-SQL. The CLR programming language has better performance than T-SQL, which is an interpreted language, because managed code is compiled. For operations involving arithmetic calculations, string processing, conditional logic, and so on, managed code may perform better than T-SQL at an order of magnitude. In this article, although you can write a stored procedure with T-SQL, you write a stored procedure in C # to illustrate the problem. The steps are as follows:

First, open Visual Studio 2, select the C # language, and create a new database project named Sqlproject1. At this point, Visual Studio's Beta 2 will ask you what database you want to associate with. Because we are using the pubs database, so we choose the machine name is the local machine, set up a good way to verify the SQL, select the pubs database, you can. (Note that in SQL Server 2005, the pubs and Northwind databases are no longer a self-contained database of SQL Server 2005 and need to be downloaded by http://go.microsoft.com/fwlink/?LinkId=31995.) Then, after the project is established, select the new item, select the store procedure stored procedure, and name the Authors.cs, then press OK and enter the following code:

Using System;
Using System.Data;
Using SYSTEM.DATA.SQL;
Using System.Data.SqlTypes;
Using Microsoft.SqlServer.Server;
Using System.Data.SqlClient;

public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]

public static void GetAuthors ()
{
SqlPipe sp = sqlcontext.pipe;
using (SqlConnection conn = new SqlConnection ("Context connection=true"))
{
Conn. Open ();
SqlCommand cmd = new SqlCommand ();
Cmd.commandtype = CommandType.Text;
Cmd. Connection = conn;
Cmd.commandtext = "Select DatePart (Second, GetDate ())" + "as timestamp,* from authors";
SqlDataReader rdr = cmd. ExecuteReader ();
Sp. Send (RDR);
}
}

[SqlProcedure]

public static void Gettitlesbyauthor (String authorid)
{
String sql = "Select T.title, T.price, T.type," + "t.pubdate from authors A" +
"INNER JOIN titleauthor TA on a.au_id = ta.au_id" +
"INNER JOIN titles T on ta.title_id = t.title_id" +
"Where a.au_id = '" + @authorID + "'";
using (SqlConnection conn = new SqlConnection ("Context connection=true"))
{
Conn. Open ();
SqlPipe sp = sqlcontext.pipe;
SqlCommand cmd = new SqlCommand ();
Cmd.commandtype = CommandType.Text;
Cmd. Connection = conn;
Cmd.commandtext = SQL;
SqlParameter Paramauthorid = new SqlParameter ("@authorID", SqlDbType.VarChar, 11);
Paramauthorid.direction = ParameterDirection.Input;
Paramauthorid.value = Authorid;
Cmd. Parameters.Add (Paramauthorid);
SqlDataReader rdr = cmd. ExecuteReader ();
Sp. Send (RDR);
}
}
}


Let's look at the code above. First, the authors class is declared and the system.data.sql;,system.data.sqltypes;,microsoft.sqlserver.server is introduced; System.Data.SqlClient namespace. Of these, there are two very important classes in the Microsoft.SqlServer.Server namespace:

· SqlContext: A SqlContext class contains methods that can obtain a database instance connection, a command, a transaction, and so on.

· Sqlpine: The user implementation sends the query result and the message to the client, and ado.net inside response class has many similarities.

The authors class contains two static methods, GetAuthors and Gettitlesbyauthor respectively. Where the GetAuthors method returns all the data for the authors table in the pubs database, and Gettitlesbyauthor returns the book written by the specified author.

In the GetAuthors method, you first reference the Sqlpine object by calling the pipe property of the SqlContext class:

SqlPipe sp = sqlcontext.pipe;


Next, use the SqlConnection object to connect to the database. Note that in the string connected to the database, "Context=true" is used to indicate that the user logged in to the database is logged on:

using (SqlConnection conn = new SqlConnection ("Context connection=true"))
Conn. Open ();


Then create an instance of the SqlCommand object and set its properties:

SqlCommand cmd = new SqlCommand ();
Cmd.commandtype = CommandType.Text;
Cmd. Connection = conn;
Cmd.commandtext = "Select DatePart (Second, GetDate ())" + "as timestamp,* from authors";


Executes the SQL statement by calling the ExecuteReader method of the SqlCommand object.

SqlDataReader rdr = cmd. ExecuteReader ();


Finally, the result set is returned to the client using the SqlPipe object. This can be accomplished using the Send method

Sp. Send (RDR);


It is important to note that after we create the stored procedure, we must deploy it. We first select the build Sqlproject1 in the Builde menu, and we compile the class we just created. Once the project has been compiled, it can be deployed. Deployment is also very simple, select the Build menu and choose Deploy Sqlproject1, which automatically deploys the newly written stored procedures to SQL Server 2005.

Finally, in SQL Server Management Studio, execute the following statement to ensure that managed code can be executed in SQL Server:

EXEC sp_configure ' clr enabled ', 1;
Reconfigure with OVERRIDE;
Go

  Create a data access Layer with TableAdapter Configuration Wizard

In Visual Studio 2005, TableAdapter Configuration Wizard is added to facilitate the creation of a data access layer. First, we know what TableAdapter is. A TableAdapter connects to a database, executes a query statement or stored procedure, and populates the returned result set into a DataTable. The Tableadapter Configuration Wizard allows you to create edited data sets in a typed DataSet, which is very handy.
  
First, in the C # language, create a Web project named Ntierexample, as shown in the following figure:


To create the data access layer, first right-click the Project menu and select "ADD New Item" in the pop-up menu. In the ADD NEW ITEM dialog box that pops up, select the dataset type. Then in the filename, type "authors.xsd" and click "Add", as shown in the following image:


When you click the "ADD" button, the system prompts you to put the file in the App_Code directory, because in Vs.net 2005, the data access layer's files are typically placed in the folder to facilitate management. We continue to select "OK" and put the XSD file in the App_Code folder. Next, the window of the Tableadpater Setup Wizard appears. First, we want to specify the database string for the connection, and choose to save the connection string to the Web.config file and select "Next" to go to the next step.

In this step, select the command type, as we have just established the stored procedure, so select "Use existing store procedure", as shown in the following figure:


Click Next to go to the next window and ask which stored procedure to use, as shown in the following figure:


Here, we choose to use the "getauthors" stored procedure, then select "Next" to go to the next step, the following figure:


In this case, we want to specify which method of using the GetAuthors stored procedure is used to return the dataset, and we select "Return a DataTable" and specify the GetAuthors method to use, which is returned as a DataTable. Continue to select "Next", the following window appears, the system will automatically generate a data access layer.

When you click the "Finish" button, Visual Studio automatically generates classes, and when these classes are generated, we rename the class to authors, so that the final output is shown in the following illustration:


Next, we follow the steps above, similarly, using the "TableAdapter" wizard, select "Data-add-tableadapter" in the Tools menu bar, add a TableAdapter again, this time by selecting " Gettitlesbyauthor the stored procedure, and the option to return is "Gettitlesbyauthor", the other steps are the same as generating "Getauthos", and finally, the name of the resulting class is changed to "Authortitles", as shown in the following illustration

 Creating a logical layer

Next, we create the logical layer, in this case, the logic layer is very simple, just play the role of illustrative. First, we create a new class Authrobiz class, put it in the App_Code folder, and modify the code for the class as follows:

public class Authorsbiz
{
Public Authorsbiz ()
{}

Public DataTable GetAuthors ()
{
Authorstableadapters.authorstableadapter Authordb = new Authorstableadapters.authorstableadapter ();
return Authordb.getauthors ();
}
Public DataTable getauthortitles (string authorid)
{
Authorstableadapters.authortitlestableadapter Authordb = new Authorstableadapters.authortitlestableadapter ();
Return Authordb.gettitlesbyauthor (Authorid);
}
}

From the above code, you can see that the "authors.xsd" typed dataset class that we just created with the wizard is now in code, and can be invoked by using the Authorstableadapters class, Where Authordb is an instance of the Authorstableadapters class.

   To create a presentation layer

In asp.net 2.0, when creating a presentation layer, you can use the Master-page technology to make it easy to build a page. Mater-page means that you can first build the main frame template structure of a page, and then place a ContentPlaceHolder control in which the contents of other subpages are displayed. In other subpages, you only need to refer to the master page first, and then modify the contents of the ContentPlaceHolder control.

First, add a new "master" type of file to the project, name it Commonmaster, and enter the following code:

<%@ Master language= "C #"%>
<title> Master Page </title>
<body>
<form id= "Form1" runat= "Server"
<table id= "header" style= "width:100%; height:80px "cellspacing=" 1 "cellpadding=" 1 "border=" 1 ">
<tr>
<TD style= "Text-align:center; width:100%; height:74px; "Bgcolor=" Teal "
<asp:label runat= "Server" id= "Header" font-size= "12pt" font-bold= "True"
Authors Information
</asp:label>
</td>
</tr>
</table>
<b/>
<table id= "LeftNav" style= "WIDTH:108PX; height:100% "cellspacing=" 1 "cellpadding=" 1 "border=" 1 ">
<tr>
<TD style= "width:100px"
<table>
<tr>
<td>
<a Href= "Home.aspx" >home </a>
</td>
</tr>
<tr>
<td>
<a Href= "Authors.aspx" >authors List </a>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table id= "mainbody" style= "left:120px; Vertical-align:top; width:848px; Position:absolute; top:94px; height:100% "border=" 1 ">
<tr>
<TD width= "100%" style= "Vertical-align:top"
<asp:contentplaceholder id= "middlecontent" runat= "Server" > </asp:contentplaceholder>
</td>
</tr>
</table>
</form>
</body>

Next, we first create a authors.aspx page that displays the author page, because the page's frame is kept, so you can use the Maser-page technology to introduce the Commonmaster page you just created when you create a new page, as shown in the following figure:


After the Add button, the following figure appears, select the Commonmaster page you just created, as follows:


Then enter the following code:

<%@ Page language= "C #" masterpagefile= "~/commonmaster.master"%>
<asp:content id= "Content1" contentplaceholderid= "middlecontent" runat= "Server"
<asp:objectdatasource runat= "Server" id= "Authorssource" typename= "authorsbiz" selectmethod= "GetAuthors"
</asp:objectdatasource>
<asp:gridview runat= "Server" autogeneratecolumns= "false" id= "Authorsview" datasourceid= "Authorssource"
<alternatingrowstyle backcolor= "Silver" > </alternatingrowstyle>
<Columns>
<asp:hyperlinkfield datatextfield= "au_id" headertext= "Author id" datanavigateurlfields= "au_id"
Datanavigateurlformatstring= "Authortitles.aspx?" Authorid={0} ">
</asp:HyperLinkField>
<asp:boundfield headertext= "Last Name" datafield= "au_lname" > </asp:BoundField>
<asp:boundfield headertext= "Name" datafield= "au_fname" > </asp:BoundField>
<asp:boundfield headertext= "Phone" datafield= "phone" > </asp:BoundField>
<asp:boundfield headertext= "Address" datafield= "address" > </asp:BoundField>
<asp:boundfield headertext= "City" datafield= "City" > </asp:BoundField>
<asp:boundfield headertext= "state" datafield= "state" > </asp:BoundField>
<asp:boundfield headertext= "zip" datafield= "zip" > </asp:BoundField>

</Columns>
</asp:gridview>
</asp:content>

Note that we use the ObjectDataSource control, and in. NET 2.0, with this control, we can easily communicate the presentation and logic layers. The code is as follows:


The TypeName attribute specifies the class Authorsbiz class for the logical layer we created earlier, and in order to obtain the data, the SelectMethod method is used, where the previously established GetAuthors method is specified. Of course, you can also apply the Updatemethod,insertmethod,deletemethod method on other occasions, or you can add parameters, such as the next Authortitle.aspx page to create the following code:

<%@ Page language= "C #" masterpagefile= "~/commonmaster.master"%>







In the code above, the first time a user chooses an author name on the Authors.aspx page, the authortitle.aspx page returns all of the author's writings. So, in the ObjectDataSource control, we used the SelectParameters parameter to specify that the argument passed in to query is Authorid. Finally, bind the GridView to the ObjectDataSource Control.

Finally, run our code, and the results are shown in the following two diagram:




   Summary

In ASP.net 2.0, we take advantage of the power of SQL Server 2005 to create stored procedures in. NET languages and use the TableAdapter Wizard to easily create a data access layer and take advantage of the characteristics of the ObjectDataSource control. The presentation and logic layers can be easily communicated.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.