Understanding and reprinting of Web Design Patterns

Source: Internet
Author: User
Tags http post
Summary

This article introduces how to use the web design pattern to improve webform under the. NET Framework.ProgramSome basic methods and key points of the design.

Keywords

Design pattern, ASP. NET, webform, MVC, page controller, Front Controller, page Cache

Directory

Introduction
Classic webform Architecture
Design Mode
Webform in MVC Mode
Webform in page controller mode
Webform in front controller mode
Webform in page cache Mode

Introduction

I remember when Microsoft launched ASP. NET, the shocking thing was that developing web programs was no longer writing traditional web pages, but building applications. Microsoft called it webform. However, two years later, a considerable number of developers are still using the idea of writing script programs to build one webform after another without making full use of ASP. this article hopes to inspire readers with some new ideas through examples.
Due to limited space, it is impossible for this article to show readers a webform in combination with the design pattern through a complex web application. However, if it is just a small program, there is no need to use the pattern. For ease of understanding, I hope you can think of it as a small module in a large system (ifCodeAs part of a large system, the use mode becomes very important ).
All source programs are provided at the end of this article.
Classic webform Architecture
First, let's look at a simple application. For database design, for example, the portal is the parent table of subject and one-to-many Association is performed through portalid. The program needs to display different subject lists based on portalid.

According to the general habits of webform writing, first drag and drop a dropdownlist, A DataGrid, and a button control on the page:
Interface (webform. aspx ):
<Form ID = "webform" method = "Post" runat = "server">
<Asp: dropdownlist id = "dropdownlist" runat = "server"> </ASP: dropdownlist>
<Asp: button id = "button" runat = "server" text = "button"> </ASP: button>
<Asp: DataGrid id = "DataGrid" runat = "server"> </ASP: DataGrid>
</Form>

The core code written using the Vs. Net code hiding function is as follows:
Post Code (webform. aspx. CS ):
// Page initialization event
Private void page_load (Object sender, system. eventargs E)
{
If (! Ispostback)
{
String SQL _select_portal = "select * from portal ";
// Use using to ensure the database connection is released
// The connection string is stored in the web. config file for modification.
Using (sqlconnection conn = new sqlconnection (configurationsettings. etettings ["connectionstring"])
{
Sqldataadapter dataadapter = new sqldataadapter (SQL _select_portal, Conn );
Dataset dataset = new dataset ();
Dataadapter. Fill (Dataset );
// Set the data sources, text fields, and value fields in the drop-down list
Dropdownlist. datasource = dataset;
Dropdownlist. datatextfield = "portalname ";
Dropdownlist. datavaluefield = "portalid ";
Dropdownlist. databind ();
}
}
}
// Click the button event
Private void button_click (Object sender, system. eventargs E)
{
String SQL _select_subject = "select * from subject where portalid = {0 }";
Using (sqlconnection conn = new sqlconnection (configurationsettings. etettings ["connectionstring"])
{
// Replace the undetermined character {0} in the SQL statement with the value selected from the drop-down list}
Sqldataadapter dataadapter = new sqldataadapter (string. Format (SQL _select_subject, dropdownlist. selectedvalue), Conn );
Dataset dataset = new dataset ();
Dataadapter. Fill (Dataset );
DataGrid. datasource = dataset;
DataGrid. databind ();
}
}

In the execution result, the program binds the DataGrid according to the value selected in the drop-down list box. A typical webform architecture reflects the ASP. NET event-driven idea and achieves the separation of the interface and code. However, you can find several problems:

The code for database operations is repeated. Repeated code is an absolute "Bad taste" in software development. For some reason, when you modify a code, but I forgot to change the same code, leaving the program with bugs.

The post-code completely depends on the interface. The changes in the webform lower bound are much greater than those in the data storage structure and access. When the interface changes, you will have to modify the code to adapt to the new page, the entire post code may be overwritten.

The Post Code not only processes user input, but also processes data. If the demand changes, for example, the data processing method needs to be changed, you will almost overwrite the entire post code.
A good design requires every module. Every method focuses only on one thing. Such a structure is clear and easy to modify. After all, the project requirements are constantly changing, "The only thing that remains unchanged is the change itself." A good program must be prepared for the change to avoid "taking the lead". Therefore, we must find a solution to the above problem. Let's take a look at the design pattern.

Design Mode

The design pattern describes a recurring problem and the core solution to the problem. It is a successful architecture, design and implementation solution, and a summary of experience. The concept of design patterns first came from Western architecture, but the most successful case was the "plan" of ancient China ".

Webform in MVC Mode

The MVC pattern is a basic design pattern used to separate the user interface logic from the business logic. It classifies data processing, interface and user behavior control into Model-View-controller.
Model: responsible for data acquisition and change of the current application and related business logic
View: displays information.
Controller: Collects input of conversion users.

Both view and controller depend on the model, but the model neither depends on the view nor controller. This is one of the main advantages of separation, so that the model can be created and tested separately to facilitate code reuse, view and controller only need the model to provide data. They do not know or care about whether the data is stored in SQL Server, Oracle database, or somewhere else.
According to the MVC pattern, the post-code in the above example can be split into model and controller, and a dedicated class can be used to process data. The post-code as controller is only responsible for converting user input, the modified code is as follows:
Model (sqlhelper. CS): encapsulate all database operations.
Private Static string SQL _select_portal = "select * from portal ";
Private Static string SQL _select_subject = "select * from subject where portalid = {0 }";
Private Static string SQL _connection_string = configurationsettings. etettings ["connectionstring"];
Public static dataset getportal ()
{
Return getdataset (SQL _select_portal );
}
Public static dataset getsubject (string portalid)
{
Return getdataset (string. Format (SQL _select_subject, portalid ));
}
Public static dataset getdataset (string SQL)
{
Using (sqlconnection conn = new sqlconnection (SQL _connection_string ))
{
Sqldataadapter dataadapter = new sqldataadapter (SQL, Conn );
Dataset dataset = new dataset ();
Dataadapter. Fill (Dataset );
Return dataset;
}
}

Controller (webform. aspx. CS): responsible for converting user input
Private void page_load (Object sender, system. eventargs E)
{
If (! Ispostback)
{
// Call the model method to obtain the data source
Dropdownlist. datasource = sqlhelper. getportal ();
Dropdownlist. datatextfield = "portalname ";
Dropdownlist. datavaluefield = "portalid ";
Dropdownlist. databind ();
}
}
Private void button_click (Object sender, system. eventargs E)
{
DataGrid. datasource = sqlhelper. getsubject (dropdownlist. selectedvalue );
DataGrid. databind ();
}

The modified code is very clear, the M-V-C of the division of its system, rewrite any module will not cause changes to other modules, similar to the mfc doc/view structure. However, if there are many programs with the same structure, we need to make some unified control, such as user identity judgment and unified interface style; or you want the Controller to be more thoroughly separated from the model, and the model-Layer Code is not involved in the controller. At this time, it seems a little powerless to rely on the MVC mode, so please take a look at the following page controller mode.

Webform in page controller mode

The MVC mode focuses on the separation between model and view, but less on the controller (in the above MVC mode, we only split the model and controller, but in webform-based applications, the view and controller are originally separated (displayed in the client browser ), controller is a server-side application. Different user operations may lead to different controller policies. The application must perform different operations based on the previous page and user-triggered events; in addition, most webforms require a uniform interface style. If this is not handled, duplicate code may be generated. Therefore, it is necessary to divide the Controller more carefully.
The page controller mode uses a common Page Base Class Based on the MVC mode to uniformly process HTTP requests and interface styles,

Traditional webforms generally inherit from the system. Web. UI. Page class, while the implementation idea of page controller is that all webforms inherit the custom page base class,

With the custom page base class, we can receive page requests, extract all relevant data, call all updates to the model, and forward requests to the view in a unified manner to easily implement a unified page style, the Controller logic derived from it will become simpler and more specific.
The following describes the specific implementation of page controller:
Page controller (basepage. CS ):
Public class basepage: system. Web. UI. Page
{
Private string _ title;
Public String title // page title, which is specified by the subclass
{
Get
{
Return _ title;
}
Set
{
_ Title = value;
}
}
Public dataset getportaldatasource ()
{
Return sqlhelper. getportal ();
}
Public dataset getsubjectdatasource (string portalid)
{
Return sqlhelper. getsubject (portalid );
}
Protected override void render (htmltextwriter writer)
{
Writer. Write ("<HTML> Base. Render (writer); // output of the subpage
Writer. Write (@ "<a href =" "http://www.asp.net" "> ASP. NET </a> </body> }
}

Now it encapsulates the model function and implements a unified page title and footer. Subclass only needs to directly call:
The modified controller (webform. aspx. CS ):
Public class webform: basepage // inherit the Page Base Class
{
Private void page_load (Object sender, system. eventargs E)
{
Title = "Hello, world! "; // Specify the page title
If (! Ispostback)
{
Dropdownlist. datasource = getportaldatasource (); // call the method of the base class
Dropdownlist. datatextfield = "portalname ";
Dropdownlist. datavaluefield = "portalid ";
Dropdownlist. databind ();
}
}
Private void button_click (Object sender, system. eventargs E)
{
DataGrid. datasource = getsubjectdatasource (dropdownlist. selectedvalue );
DataGrid. databind ();
}
}

From the above we can see that the bagepage controller takes over most of the work of the original controller, making the Controller simpler and easier to modify (for ease of explanation, I did not place the control in the basepage, but you can do that). However, as the application complexity increases and user requirements change, we can easily divide different page types into different base classes, the inheritance tree is too deep. For example, for a shopping cart program, you need to define the page path. For the Wizard program, the path is dynamic (you do not know your choice beforehand ).
It is not enough to use page controller for the above applications. Let's look at the front controller mode.

Webform in front controller mode

The implementation of page Controller requires the creation of code for the public part of the page in the base class. However, with the passage of time, the demand will change greatly, and sometimes you have to add non-public code, in this way, the base class will keep increasing, and you may create a deeper inheritance hierarchy to delete the conditional logic, which makes it difficult for us to refactor it, therefore, we need to further study page controller.
By controlling and transmitting all requests, front controller solves the problem of decentralized processing in page controller. It consists of two parts: handler and command tree. Handler processes all public logic, receives http post or get requests and related parameters, selects the correct command object based on the input parameters, and passes control to the command object to complete subsequent operations, here we will use the command mode.
In command mode, a request can be converted into an object to make a request to an unspecified application object. This object can be stored and passed like other objects, the key to this mode is an abstract command class, which defines an interface for executing operations. The simplest form is an abstract execute operation, the specific command subclass uses the receiver as an instance variable, implements the execute Operation, and specifies the action taken by the receiver. The receiver has the specific information required to execute the request.

Because the front controller mode is more complex than the preceding two modes, let's take a look at the class diagram of the example:

For more information about handler principles, refer to msdn. Let's look at the specific implementation of the Front Controller mode:

First, define in Web. config:

<〈! -- Specify that the aspx file starting with dummy is handled by Handler -->



<〈! -- Specify the page ing block named frontcontrollermap and submit it to the urlmap class for processing. The program will find the corresponding URL based on the key as the final execution path, you can define multiple key-value pairs with URLs here -->






...

Modify webform. aspx. CS:
Private void button_click (Object sender, system. eventargs E)
{
Response. Redirect ("dummywebform. aspx? Requestparm = "+ dropdownlist. selectedvalue );
}
When the program is executed here, the processrequest event of the handler class will be triggered according to the definition in Web. config:
Handler. CS:
Public class handler: ihttphandler
{
Public void processrequest (httpcontext context)
{
Command command = commandfactory. Make (context. Request. Params );
Command. Execute (context );
}
Public bool isreusable
{
Get
{
Return true;
}
}
}

It will call the make method of commandfactory to process received parameters and return a command object, then it will call the execute method of the command object to submit the processed parameters to the specific processing page.
Public class commandfactory
{
Public static command make (namevaluecollection parms)
{
String requestparm = parms ["requestparm"];
Command command = NULL;
// Get different command objects based on input parameters
Switch (requestparm)
{
Case "1 ":
Command = new firstportal ();
Break;
Case "2 ":
Command = new secondportal ();
Break;
Default:
Command = new firstportal ();
Break;
}
Return command;
}
}
Public interface command
{
Void execute (httpcontext context );
}
Public abstract class redirectcommand: Command
{
// Obtain the key and URL key-value pairs defined in Web. config. For details about the urlmap class, see the code in the downloaded package.
Private urlmap map = urlmap. soleinstance;
Protected abstract void onexecute (httpcontext context );
Public void execute (httpcontext context)
{
Onexecute (context );
// Submit the key-value pairs to the specific processing page
String url = string. Format ("{0 }? {1} ", map. Map [context. Request. url. absolutepath], context. Request. url. query );
Context. server. Transfer (URL );
}
}
Public class firstportal: redirectcommand
{
Protected override void onexecute (httpcontext context)
{
// Add portalid to the input parameters for page processing
Context. items ["portalid"] = "1 ";
}
}
Public class secondportal: redirectcommand
{
Protected override void onexecute (httpcontext context)
{
Context. items ["portalid"] = "2 ";
}
}
Finally, in actwebform. aspx. CS:
DataGrid. datasource = getsubjectdatasource (httpcontext. Current. items ["portalid"]. tostring ());
DataGrid. databind ();

The preceding example shows how to use the Front Controller to centralize and process all requests. It uses commandfactory to determine the specific operation to be executed, regardless of the method and object to be executed, handler only calls the execute method of the command object. You can add additional commands without modifying handler. It allows users to see the actual page. When users enter a URL, the system will. the Config File maps it to a specific URL, which gives programmers more flexibility and obtains an indirect operation layer not included in the page controller implementation.
We use the front controller mode for quite complex web applications. It usually needs to replace the built-in controller of the page with the Custom Handler, in front controllrer mode, we do not even need pages. However, because of its complicated implementation, it may cause some troubles to the implementation of business logic.
The above two controller modes are used to process complicated webform applications. Compared with applications that directly process user input, the complexity is greatly improved and the performance is inevitably reduced, for this reason, we finally look at a mode that can greatly improve program performance: Page cache mode.

Webform in page cache Mode

almost all webforms face applications with frequent access but few changes. For webform visitors, a considerable amount of content is repeated, therefore, we can try to save the webform or some of the same content in the server memory for a period of time to speed up the response of the program.
This mode is easy to implement. You only need to add the following content to the page:
<% @ outputcache duration = "60" varybyparam = "NONE" %>,
This indicates that the page will expire after 60 seconds. That is to say, the content of the page is the same for all visitors within 60 seconds, but the response speed is greatly improved, just like static html pages.
maybe you just want to save part of the content instead of saving the whole page, then we will return to sqlhelper in MVC mode. CS, I made a few changes to it:
Public static dataset getportal ()
{< br> dataset;
If (httpcontext. current. cache ["select_portal_cache"]! = NULL)
{< br> // if the data exists in the cache, It is retrieved directly
dataset = (Dataset) httpcontext. current. cache ["select_portal_cache"];
}< br> else
{< br> // otherwise, it is retrieved from the database and inserted into the cache, set the absolute expiration time to 3 minutes
dataset = getdataset (SQL _select_portal);
httpcontext. current. cache. insert ("select_portal_cache", dataset, null, datetime. now. addminutes (3), timespan. zero);
}< br> return dataset;
}

here, select_portal_cache is used as the cache key and the content retrieved from getdataset (SQL _select_portal) is used as the cache value. In this way, in addition to database operations performed by the Program for 1st calls, database operations are not performed during the cache expiration time, which also greatly improves the response capability of the program.
conclusion
since. the introduction of the Net Framework into the design model has greatly improved its strength in enterprise-level applications. It is no exaggeration to say that it is enterprise-level applications. net has caught up with the pace of Java and has come to the fore. This article uses an example to show the readers in. some basic knowledge required to implement the web design pattern under the. NET Framework.

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.