Based on. Web application framework construction model of net

Source: Internet
Author: User
Tags html page http post implement modify valid versions visual studio
web| architecture [Introduction]
This article corresponds to the Web representation pattern cluster, the first half of the article describes the architecture, design and asp.net implementation of the MVC pattern, and in more complex systems, the page Controller (paging controller) and front Controller ( Front-End controller) as a complement to the MVC implementation, and finally, briefly introduces two other modes of the Web representation pattern cluster: Intercepting filter (filter) and page cache mode.

"The first works of architecture designers tend to be more concise and clean." He knew he didn't know what he was doing, so he carefully designed it. When he designed his first work, he would make many modifications and touches. These will be left to the "next" use ... This second system is the most dangerous system he has ever designed ... The general trend is that when designing a second system, it will use all the ideas and modifications that are carefully placed on one side of the first work, leading to the design being too late. ”
-frederick p. Brooks, Jr. Published in 1972, The Mythical Man Month (Human-moon myth).

The first system built on the Web is a static HTML page that is simply linked together to share documents among dispersed teams. As users increase their usage, Dynamic Web pages that respond to user input are becoming more common. Early dynamic pages are typically written in the form of Common Gateway Interface (CGI) scripts. These CGI scripts not only contain business logic to determine what should be displayed in response to user input, but also generate presentation HTML. As demand for more complex logic increases, so does the need for richer, more vivid representations. This increased complexity poses a challenge to the CGI programming model.
Soon, page-based development tools such as ASP and JSP appear. These new methods simplify the programming model by allowing developers to embed scripts directly into the HTML surface. As these embedded scripting applications become more complex, developers want to separate business logic from presentation logic at the page level. To accommodate this requirement, a tag library with helper objects and code-behind page policies appears. Then there is a fine framework for dynamically configuring site navigation and command Scheduler, but all of this is at the expense of increasing complexity. Suppose you have a large number of Web presentation options now, how do you choose the appropriate Web presentation design strategy for your application?

Is there really a design strategy that adapts to all situations? Unfortunately, in software design, the elimination of excessive redundancy and excessive complexity is a competitive requirement, it is difficult to really achieve the balance between the two. You can start the design work from a simple page that contains embedded scripts, but soon the business logic repeats itself in each file, causing the system to be difficult to maintain and extend. You can eliminate redundancy by moving this logic into a set of collaboration components, but doing so increases the complexity of the solution. On the other hand, your design work can start with a framework designed to provide tag libraries, dynamic configuration, and command scheduler, but it can eliminate redundant code, but it can greatly increase the complexity of the system, which is often unnecessary.
And how to consider the needs of various aspects, and put forward a most suitable for our application of the Web presentation strategy? This requires a choice between complex solutions (supporting scenarios that may change in the future) and simple solutions (to meet current requirements), and in principle it is desirable to increase costs appropriately, but it is undesirable to increase costs too much. So cut the crap and let's start with "simplicity."

MVC (Model-View-control)
Many computer systems are used to retrieve data from the data store and display it to the user. After the user changes the data, the system stores the updated content in the data store again. Because the critical flow of information occurs between the data store and the user interface, you may be tempted to tie the two parts together to reduce the amount of coding and improve application performance. But there are some big problems with this seemingly natural approach. One problem is that user interface changes tend to be much more frequent than changes in the data storage system. Another problem with coupling data with the two parts of the user interface is that business applications tend to incorporate other business logic that is far more than the data transfer capabilities. How do you modularize the user interface features of your Web application so that you can easily modify each part individually?
Model-view-controller is the pattern that enables the separation of functional and display modules, making applications more maintainable, extensible, portable, and reusable, initially Trygve Reenskaug in the late 1970s for the Smalltalk platform development Framework [FOWLER03], and development so far, has formed a very mature model.

MVC Solution
The Model-view-controller (MVC) pattern divides the modeling, display, and operation of a domain into three separate classes [Burbeck92] based on user input:
Q model. Models are used to manage the behavior and data of an application domain and respond to requests for their state information, usually from views, and also to respond to instructions for changing states (usually from controllers).
Q View. Views are used to manage the display of information.
Q Controller. The controller is used to interpret the user's mouse and keyboard input to inform the model and/or view to make the appropriate changes.
Both the view and the controller depend on the model. However, the model is neither dependent on the view nor on the controller. This is one of the main advantages of separation. Such a separation allows the model to be established and tested independently of the visual representation function. In many rich client applications, the separation of views from the controller is secondary, and in fact many user interface frameworks implement the role as an object. On the other hand, in a Web application, the separation of the view (browser) and the controller (the server-side component that handles HTTP requests) is well defined.
Model-view-controller is a basic design pattern for separating user-interface logic from business logic. Unfortunately, the popularity of this pattern has led to many false descriptions. Especially in different contexts, the term "controller" has been used to mean different things. Fortunately, the advent of Web applications has helped eliminate some of the uncertainty, because the separation of views and controllers is so obvious.

Variant of MVC
In application programming into Smalltalk-80:how to use Model-view-controller (MVC) [Burbeck92], Steve Burbeck describes two variants of MVC: the passive model and the active model.
The passive model is used when a controller operates the model exclusively. The controller modifies the model and then notifies the view that the model has changed and should be refreshed (see Figure 2). The model in this case is completely independent of the view and the controller, which means that the model cannot report its state changes. The HTTP protocol is an example of this scenario. The browser does not have an easy way to get asynchronous updates from the server. The browser displays the view and responds to user input, but it does not detect data changes on the server. The server is queried for changes only if the user explicitly requests a refresh.
The active model is used when the model changes state without involving the controller. This can occur when other resources are changing the data and the changes must be reflected in the view. Take the stock ticker display as an example. You receive stock data from an external source, and you want to update the view when the stock data changes (for example, the quotation data area and the warning window). Because only the model detects changes to its internal state (when these changes occur), the model must notify the view to refresh the display.
However, one of the purposes of using the MVC pattern is to make the model independent of the view. If the model must notify the view of changes, it will bring back the dependencies that you want to avoid. Fortunately, the observer mode [GAMMA95] provides a mechanism for reminding other objects to note state changes without causing dependencies on those objects. Each view implements the observer interface and registers with the model. The model will track the list of all observers that are changed by the subscription. When the model changes, the model traverses all registered observers and notifies them of the changes. This method is often referred to as "publish-subscribe." The model does not need specific information about any views. In fact, when you need to notify the controller of model changes (for example, enabling or disabling menu options), all the controller must do is implement the Observer interface and subscribe to the model changes. For situations where there are many views, it is meaningful to define multiple principals, each of which describes a particular type of model change. Each view can then only subscribe to the type of changes that are related to the view. Figure 3 shows the structure of active MVC using observer, and how the observer isolates the model from the direct reference view.
Figure 4 shows how observer notifies the view when the model changes. Unfortunately, in the Unified Modeling Language (UML) sequence diagram, there is no good way to demonstrate the separation of the model from the view, because the diagram represents an instance of an object rather than a class and an interface.
asp.net implementation of MVC
To explain how to implement the Model-view-controller pattern in asp.net, and to illustrate the benefits of separating the model, view, and controller roles in software, the following example reconstructs a single page solution that does not detach all three roles into a solution that separates the three roles. The sample application is a page with a drop-down list, as shown in the following illustration, that shows the records stored in the database.
Take advantage of Microsoft Visual Studio (R). NET development system, you can easily separate the presentation (view) code from the Model-controller code. Each asp.net page has a mechanism that allows you to implement a method called from a Web page in a separate class. The mechanism is through visual Studio. NET provides, it has many advantages, such as Microsoft IntelliSense (r) technology. When you use the code-behind feature to implement a Web page, you can use IntelliSense to display a list of available methods for the objects that are used in the code behind the page. IntelliSense does not apply to. aspx pages. At the same time, in order to show the separation of Model-controller, the Databasegateway is extracted from the database operation, thus the complete separation of the three is realized.
View
<%@ Page language= "C #" codebehind= "Solution.aspx.cs"
Autoeventwireup= "false" inherits= "Solution"%>
<title> Solutions </title>
<body>
<form id= "Solution" method= "POST" runat= "Server" >
Select Recording:<br/>
<asp:dropdownlist id= "Recordingselect" runat= "Server"/>
<asp:button id= "Submit" runat= "Server" text= "Submit"
enableviewstate= "False"/>
<p/>
<asp:datagrid id= "Mydatagrid" runat= "Server" width= "700"
Backcolor= "#ccccff" bordercolor= "Black" showfooter= "false"
cellpadding= "3" cellspacing= "0" font-name= "Verdana" font-size= "8pt"
Headerstyle-backcolor= "#aaaadd" enableviewstate= "false"/>
</form>
</body>

Model
Using System;
Using System.Collections;
Using System.Data;
Using System.Data.SqlClient;
public class Databasegateway
{
public static DataSet Getrecordings ()
{
String selectcmd = "SELECT * from Recording";

SqlConnection myconnection =
New SqlConnection (
"Server= (local);d atabase=recordings; Trusted_connection=yes ");
SqlDataAdapter mycommand = new SqlDataAdapter (Selectcmd, MyConnection);

DataSet ds = new DataSet ();
Mycommand.fill (ds, "Recording");
return DS;
}

public static DataSet Gettracks (String recordingid)
{
String Selectcmd =
String.Format (
"SELECT * from Track where RecordingID = {0} ORDER by id",
RecordingID);

SqlConnection myconnection =
New SqlConnection (
"Server= (local);d atabase=recordings; Trusted_connection=yes ");
SqlDataAdapter mycommand = new SqlDataAdapter (Selectcmd, MyConnection);

DataSet ds = new DataSet ();
Mycommand.fill (ds, "Track");
return DS;
}

Control
Using System;
Using System.Data;
Using System.Collections;
Using System.Web.UI.WebControls;

public class Solution:System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button submit;
protected System.Web.UI.WebControls.DataGrid Mydatagrid;
protected System.Web.UI.WebControls.DropDownList Recordingselect;

private void Page_Load (object sender, System.EventArgs e)
{
if (! IsPostBack)
{
DataSet ds = Databasegateway.getrecordings ();
Recordingselect.datasource = ds;
Recordingselect.datatextfield = "title";
Recordingselect.datavaluefield = "id";
Recordingselect.databind ();
}
}

void SubmitBtn_Click (Object sender, EventArgs e)
{
DataSet ds =
Databasegateway.gettracks (
(string) recordingSelect.SelectedItem.Value);

Mydatagrid.datasource = ds;
Mydatagrid.databind ();
}

#region Web Form Designer generated code
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Required methods for designer support-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This.submit.Click + = new System.EventHandler (this. SubmitBtn_Click);
This. Load + = new System.EventHandler (this. Page_Load);

}
#endregion
}

The above example simply illustrates the MVC implementation of ASP.net, business logic is much more than that in a real-world project, but the code above shows a basic model that increases code and complexity with obvious benefits, such as reduced module dependencies, reduced code duplication, Separation of responsibilities and issues, testability of code, and so on.
Now that you have decided to use the Model-view-controller (MVC) pattern to separate the user interface components of a dynamic Web application from the business logic, the application being built will dynamically construct the Web page, but the current page navigation is based on static navigation.
In more complex application systems, how to consider avoiding the duplication of navigation code as much as possible, and even considering the dynamic determination of page navigation based on configurable rules, then page controller and Front controller are, in a sense, optimized for the MVC pattern in more complex systems.

Medium-Complexity optimized-page Controller (Page Controller)
Use page Controller mode to accept input from page requests, invoke requests to perform operations on the model, and determine the correct view to apply to the results page. Separates the dispatch logic from all view-related code. If appropriate, create common base classes for all page controllers to avoid code duplication and improve consistency and testability. Figure 5 shows the relationship between the page controller and the model and view.
The page controller can receive page requests, extract all relevant data, invoke all updates to the model, and forward requests to the view. The view then retrieves the data to be displayed based on the model. Defining a stand-alone page controller separates the model from the details of the Web request (such as session management, or by using a query string or hiding form fields to pass parameters to the page). In this basic form, you create a controller for each link in your Web application. The controller will thus become very simple, since only one operation must be considered at a time.
Creating a stand-alone controller for each Web page (or operation) can cause a lot of code duplication. Therefore, you should create a Basecontroller class to incorporate common functions such as the validation parameters (see Figure 6). Each stand-alone page controller can inherit this common functionality from Basecontroller. In addition to inheriting from a common base class, you can define a set of helper classes that the controller can invoke to perform common functions.
In most cases, the page controller depends on the specifics of the HTTP-based Web request. Therefore, the page controller code typically contains references to HTTP headers, query strings, form fields, multiple form requests, and so on. It is therefore difficult to test the controller code outside of the Web application framework. The only way to do this is to test the controller by simulating HTTP requests and parsing the results. This type of testing is time-consuming and error-prone. Therefore, to improve testability, you can put web-dependent code and web-independent code into two separate classes (see Figure 7), which is the variant implementation of page controller.
Page controller is the default implementation of most dynamic Web applications, it is simple, the Web application framework built-in, scalability and the separation of the responsibilities of its developers, etc., so that it is widely used in web development, but one controller per page, Deeper inheritance trees and dependencies on web frameworks are also more obvious limitations.

Highly complex optimization
-front Controller (Front Controller)
Front Controller solves the problem of decentralization in page controller by having a single controller transfer all requests. The controller itself is typically implemented in two parts: Handlers and command hierarchies (see Figure 8).
A handler has the following two responsibilities:
1) Retrieving parameters. The handler receives an HTTP POST or get request from the Web server and retrieves the relevant parameters from the request.
2) Select the command. The handler first selects the correct command using the parameters in the request, and then transfers control to the command to perform processing.
In a front-end controller, all requests are routed through a single (usually two-part) controller. The first part of the controller is the handler, and the second part is the hierarchy of the commands (command) [Gof95]. The command itself is part of the controller and represents specific actions that the controller triggers. After you perform this operation, the command selects which view to use to render the page. Typically, this controller framework is built using a configuration file to map requests to operations, so it is easy to change after construction. The downside, of course, is the complexity inherent in the design.

After the omission of the supplement
So far, the implementation architecture of MVC in the Web presentation pattern has been fully demonstrated, while the technical approach of page controller and front controller as an optimization tool for medium complex and highly complex situations, in building web-represented applications, has given a relatively complete solution, the careful reader has found, is not a little bit what? In building a Web application, in addition to building a "well-formed" system (which is manifested in the separation of MVC and the scalability of the system), we also need to consider the security and performance of the application, so we chose interceptiing Filter and page Cache as a supplemental content of the Web presentation pattern.

Intercepting Filter (filter)
How do I implement common preprocessing and post processing steps around Web page requests? This is the problem that filters need to solve, and in this mode, you create a string of combinations of filters to implement common preprocessing and reprocessing tasks during Web page requests.
Filters form a series of stand-alone modules that can be linked together to perform a common set of processing steps before a page request is passed to a controller object. Because each filter implements the exact same interface, there is no explicit dependency between them. Therefore, you can add new filters without affecting existing filters. You can even add filters at deployment time by instantiating them dynamically based on the configuration file.
The design of individual filters should be as far as possible so that they do not make any assumptions about whether there are other filters. This preserves the ability to add, remove, or rearrange filters. In addition, some frameworks that implement the intercepting filter pattern do not guarantee the order in which the filters are executed. If you find that there is a strong interdependence between multiple filters, it is a good idea to take the normal method of calling helper classes, as this ensures that the constraint information in the filter sequence is preserved. The direct implementation of intercepting filter is a filter chain that can be used to traverse a list of all filters. The Web request handler executes the filter chain first before passing control to the application logic.
When a Web server receives a page request, the request handler first passes control to the Filterchain (filter chain) object. This object maintains a list that contains all the filters, and calls each filter sequentially. Filterchain can read the filter order from the configuration file to achieve the scalability of deployment. Each filter has the opportunity to modify an incoming request. For example, it can modify the URL, or add the header field that the application will use. After all the filters have been executed, the request handler passes control to the controller, which performs the application functionality (see Figure 12).
Because intercepting filters are often required to process Web requests, most Web frameworks provide an application developer with the mechanism to attach an interception filter to the request-response process.

Page cache (paged)]
If dynamically generated Web pages are frequently requested and are built to consume a large amount of system resources, how can you improve the response time for such pages? Page caching increases the throughput of request responses by caching content generated from dynamic Web pages. By default, page caching is supported in asp.net, but output from any given response is not cached unless a valid expiration policy is defined. To define expiration policies, you can use low-level OutputCache APIs or advanced @outputcache directives.
The basic structure of page caching is relatively simple. The Web server maintains a local data store that contains pre-generated pages (see Figure 13).
The following sequence diagram illustrates why the page cache can improve performance. The first sequence diagram (see Figure 2) describes the initial state of the desired page that has not been cached (that is, the so-called cache misses). In this case, the Web server must access the database, generate an HTML page, store it in the cache, and then return it to the client browser. Note that this procedure is slightly slower than not being cached because it performs the following additional steps:
1. Determine if the page is cached
2. Convert the page to HTML code and store it in the cache

Any of these steps should not take a long time compared to database access and HTML generation. However, because additional processing is required in this case, you must ensure that the cache is hit more than once after the system completes the steps associated with the cache misses (as shown in Figure 14).
In the cache hit scenario shown in Figure 15, the page is already in the cache. Cache hits save loops by skipping database access, page generation, and page storage.
The following three modes can be used in asp.net to implement caching policies:
1. Insert an instruction such as <%@ OutputCache duration= varybyparam= "None"%> into each page to be cached. instruction specifies the refresh interval, in seconds. The refresh interval does not depend on external events, and the cache cannot be refreshed entirely.
2. Vary-by-parameter Caching. This pattern uses the absolute expiration variant, which enables developers to specify parameters that affect the content of the page. As a result, the cache stores multiple versions of the page and indexes the page versions by parameter values.
3. Sliding expiration Caching. This pattern is similar to absolute expiration (absolute expiration) in that the page is valid for a specified period of time. However, the refresh interval is reset on each request. For example, you might use sliding expiration caching to cache a page for a maximum of 10 minutes. As long as the request for the page is issued within 10 minutes, the expiration time is extended by another 10 minutes.

Conclusion
Since then, we have fully introduced the various patterns associated with the Web presentation cluster, the use of the Observer pattern in the MVC pattern, which we will introduce in a special space, some of the references mentioned in the text can be http://www.microsoft.com/ China/msdn/architecture/patterns/espbiblio find a relatively detailed list, of course, the network is your best resource.



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.