. NET web application framework construction mode

Source: Internet
Author: User
[Introduction]

This document corresponds to the Web representation mode cluster,ArticleThe first half of this section describes the architecture, design, and ASP of the MVC model. in a more complex system, page controller (page Controller) and Front Controller (front-end Controller) were proposed as supplements to MVC implementation. Finally, this article briefly introduces the other two modes of the Web representation mode cluster: Intercepting Filter and page cache.

"The first piece of architecture designer is often concise and clean. He knows that he doesn't know what he is doing, so he designs it with caution. When designing the first work, he will perform multiple modifications and colors. These will be reserved for "Next" use ...... The second system was the most dangerous one he had designed ...... The general trend is that when designing the second system, all ideas and modifications that are carefully shelved on one side in the first work will be used, leading to the design being over the head ."
-Frederick P. Brooks, Jr. was published on the Mythical Man Month (Mythical man-month) in December 1972 ).

The first system created on the web is a static html page that is simply linked together to share documents between scattered groups. As the usage of users increases, dynamic web pages that can respond to user input become increasingly common. Early dynamic pages were generally written in the form of a general Gateway Interface (CGI) script. These CGI scripts not only contain the business logic used to determine what content should be displayed in response to user input, but also generate HTML representation. As the demand for more complex logic increases, the demand for richer and more vivid representations also increases. This increased complexity poses a challenge to the CGI programming model.

Soon, page-based development methods (such as ASP and JSP) emerged. These new methods allow developers to embed scripts directly into the HTML to simplify the programming model. When these embedded script applicationsProgramWhen it becomes more complex, developers want to separate the business logic from the presentation logic at the page level. To meet this requirement, a Helper Object andCodeHide the tag library of the page policy. Then, there is a fine-grained framework that provides dynamic configuration of site navigation and command scheduling programs, but all of this is at the cost of increasing complexity. Assuming there are a large number of Web representation options, how do I design a policy for your application?

Is there a design strategy that can adapt to all situations? Unfortunately, in software design, eliminating excessive redundancy and excessive complexity is a competitive requirement and it is difficult to truly balance the two. You can design a simple page containing embedded scripts, but the business logic will soon repeat in various files, making the system difficult to maintain and expand. By moving the logic to a group of collaboration components, redundancy can be eliminated, but this increases the complexity of the solution. On the other hand, your design work can start with the framework designed to provide the tag library, dynamic configuration, and command scheduling program, although this can eliminate redundant code, but it will greatly increase the complexity of the system, which is usually unnecessary.

But how can we consider various needs and propose a web representation policy that best fits our application? This requires a choice between a complex solution (supporting situations that may change in the future) and a simple solution (meeting current requirements). In principle, it is advisable to increase costs appropriately, it is not advisable to increase the cost too much. Let's start with "simple.

MVC (Model-View-Control)

Many computer systems retrieve data from data storage and display it to users. After the user changes the data, the system then stores the updated content in the data storage. Because key information flows occur between data storage and user interfaces, you may want to tie these two parts together to reduce the amount of encoding and improve application performance. However, this seemingly natural method has some major problems. One problem is that user interface changes are often more frequent than data storage systems. Another problem arising from the coupling of data and user interfaces is that business applications are often integrated into other business logic that is far more than the data transmission function. How to modularize the user interface functions of Web applications so that you can easily modify each part separately?

Model-View-controller is such a pattern that separates functional modules from display modules, making applications more maintainable, scalable, portable, and reusable, it was initially the framework [fowler03] developed by Trygve reenskaug for the Smalltalk platform at the end of 1970s. So far, it has formed a very mature model.

MVC Solution

Model-View-controller (MVC) mode based on user input, Domain Modeling, display, and operations are divided into three independent classes [burbeck92]:

Model. The model is used to manage the behavior and data of an application domain and respond to requests sent to obtain its state information (usually from a view, the command to change the status is also returned (usually from the Controller ).

View. View is used to display management information.

Controller. The controller is used to interpret users' mouse and keyboard input to notify the model and/or view for corresponding changes.


Figure 1 describes the structural relationship between the three objects

Both views and controllers depend on models. However, the model neither depends on the view nor the controller. This is one of the main advantages of separation. Such separation allows the model to be created and tested independently of the visual representation function. In many fat client applications, the separation of views and controllers is secondary. In fact, many user interface frameworks implement roles as an object. In Web applications, the separation of views (browsers) and controllers (server components that process HTTP requests) is well defined.

Model-View-controller is a basic design mode used to separate the user interface logic from the business logic. Unfortunately, the popularity of this model has led to many incorrect descriptions. Especially in different contexts, the term "controller" has been used to indicate different things. Fortunately, the emergence of Web applications has helped eliminate some ambiguity, because the separation of views and controllers is so obvious.

MVC variants

In application programming in Smalltalk-80: How to Use Model-View-controller (MVC) [burbeck92], Steve burbeck describes two variants of MVC: passive model and active model.

When a controller operates the model exclusively, the passive model is used. The Controller will modify the model and then notify the view that the model has been changed and should be refreshed (see figure 2 ). In this case, the model is completely independent from the view and controller, which means that the model cannot report its status changes. HTTP protocol is an example of this solution. The browser does not have a simple method to obtain 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. Only when you explicitly request a refresh will you be asked if the server has changed.


Figure 2 passive model behavior

The active model is used when the model changes the status and does not involve controllers. This may happen when other resources are changing data and the changes must be reflected in the view. Take the display of the stock quote machine as an example. You receive stock data from external sources and want to update the view when stock data changes (for example, the quotation machine data zone and warning window ). Because only the internal status changes detected by the model (when these changes occur), the model must notify the view to refresh the display.

However, one purpose of using the MVC mode is to make the model independent from the view. If the model must change the Notification View, the dependency you want to avoid is re-introduced. Fortunately, the observer mode [gamma95] provides a mechanism to remind other objects to pay attention to state changes without causing dependency on these objects. Each view implements the observer interface and registers it with the model. The model tracks a list of all the observers that subscribe to changes. When the model changes, the model traverses all registered observers and notifies them of the changes. This method is usually called "publish-subscribe ". The model never needs specific information about any view. In fact, when you need to notify the controller of model changes (for example, enable or disable the menu options), the controller must implement the observer interface and subscribe to model changes. When there are many views, it is meaningful to define multiple subjects. Each of them describes model changes of specific types. Then, each view can only subscribe to view-related changes. Figure 3 shows the structure of active MVC using observer and how the observer isolates the model from the directly referenced view.


Figure 3. Use the observer in the active model to separate the model from the View

Figure 4 shows how the observer notifies the view when the model changes. Unfortunately, in a Unified Modeling Language (UML) sequence diagram, there is no good way to demonstrate the separation between the model and the view, because the diagram represents the instance of the object rather than the class and interface.


Figure 4. Active model behavior

ASP. NET Implementation of MVC

To explain how.. Net implements the Model-View-controller mode, and describes the advantages of Separating Models, views, and controller roles in the software, the following example refactor a single page solution without separating all three roles into a solution for separating these three roles. The sample application is a Web page with a drop-down list (as shown in the column), which displays records stored in the database.


Figure 5

Using the code hiding function of the 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 call methods from a web page in a separate class. This mechanism is provided through Visual Studio. NET and has many advantages, such as Microsoft intelliisense (r) technology. When you use the code hiding function to implement a webpage, you can use intelliisense to display the list of available methods of the objects used in the code after the webpage. Intelliisense does not apply to. aspx pages. At the same time, in order to display the separation of model-controller, databasegateway is extracted for database operations, thus realizing the complete separation of the three.

View

<% @ page Language =" C # "codebehind =" solution. aspx. CS "
autoeventwireup =" false "inherits =" solution "%>


solution



recording


select recording:


enableviewstate = "false"/>


backcolor = "# ccccff" bordercolor = "black" showfooter = "false"
cellpadding = "3" cellspacing = "0" font-name = "verdana" font-size = "8pt"
headerstyle-backcolor = "# aaaadd" enableviewstate = "false"/>


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); database = 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); database = 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 by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content 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 briefly describes ASP. net MVC implementation, in actual projects, the business logic is far more than this, but the above Code shows a basic model, it also brings obvious benefits, such as reduced module dependencies, reduced code duplication, separation of duties and problems, and code testability.

Now, have you decided to use the Model-View-controller (MVC) mode to separate the user interface components of Dynamic Web applications from the business logic, the application to be built will construct the webpage dynamically, but the current page navigation is based on static navigation.
In a more complex application system, how can we avoid duplication of Navigation Code as much as possible, or even dynamically determine page navigation based on configurable rules, in a sense, page controller and Front Controller optimize the MVC mode in more complex systems.

Medium complexity Optimization-page controller (page Controller)

Use the page controller mode to accept the input from the page request, call the request to perform operations on the model, and determine the correct view applied to the result page. Separate the scheduling logic and all view-related code. If appropriate, create a public base class 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.


Figure 6. Use basecontroller to eliminate code duplication

The page controller can receive page requests, extract all relevant data, call all updates to the model, and forward requests to the view. The view retrieves the data to be displayed based on the model. Defining an independent page controller separates model and Web request details (for example, session management, or passing parameters to the page using query strings or hiding form fields ). Create a controller for each link in the Web application in this basic form. The Controller becomes very simple because only one operation is required at a time.

Creating an independent controller for each webpage (or operation) may result in a large number of code duplicates. Therefore, you should create a basecontroller class to merge common functions such as verification parameters (see figure 6. Each Independent page controller can inherit this public function from basecontroller. In addition to inheriting from the public base class, a set of helper classes can also be defined. controllers can call these classes to execute public functions.

In most cases, the page controller depends on the details of HTTP-based Web requests. Therefore, the page controller Code usually contains references to HTTP headers, query strings, form fields, and multiple form requests. Therefore, it is very difficult to test the Controller code outside the Web application framework. The only method is to test the controller by simulating HTTP requests and analysis results. This type of test is time-consuming and error-prone. Therefore, to improve testability, you can put the code that depends on the web and the code that does not rely on the Web into two separate classes (see figure 7). This is a variant Implementation of page controller.


Figure 7. Separate Web-dependent code and web-independent code

Page controller is the default Implementation Method for most dynamic Web applications. It is simple and has the advantages of built-in Web Application Frameworks, scalability, and separation of developers' responsibilities. It is widely used in Web development, however, each page has a controller, a deep inheritance tree, And a dependency on the Web framework.

Highly complex optimization

-Front Controller (front-end Controller)

By allowing a single controller to transmit all requests, front controller solves the problem of decentralization in page controller. The controller itself is generally implemented in the following two parts: the processor and command hierarchy (see figure 8 ).


Figure 8. Front Controller Structure

The handler has the following two responsibilities:

1) search parameters. The handler receives an http post or GET request from the Web server and retrieves relevant parameters from the request.

2) Select a command. The handler first selects the correct command using the parameters in the request, and then transfers control to the command for execution.


Figure 9. Typical solution of Front Controller

In the front-end controller, all requests are sent through a single (usually two parts) controller. The first component of the controller is the processing program, and the second component is the level of commands (command) [gof95. The command itself is a part of the controller, representing a specific operation triggered by the Controller. After executing this operation, select the view to use to display the page. Generally, the constructed controller framework maps requests to operations using the configuration file, so it is easy to change after building. Of course, its disadvantage lies in the inherent complexity of this design.

Supplement after Omission

So far, the MVC implementation architecture in the Web representation mode has been fully demonstrated, at the same time, this technology puts forward page controller and Front Controller as optimization methods for medium and high complexity situations, in the construction of Web representation applications, a relatively complete solution has been provided. Do you find that there is nothing missing? When building a web application, in addition to building a "good structure" system (this 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 the supplementary content of the web representation mode.

Intercepting Filter)

How does one implement common pre-processing and post-processing steps around web page requests? This is a problem that needs to be solved by the filter. In this mode, you create a series of filters that can be combined to implement common preprocessing and post-processing tasks during web page requests.


Figure 10. A string of composite filters

Filters constitute a series of independent modules that can be linked together to perform a set of common processing steps before passing page requests to Controller objects. Because each filter implements the same interface, there is no explicit dependency between them. Therefore, you can add a new filter without affecting the existing filter. You can even add filters during deployment by dynamically instantiating them based on the configuration file.

The design of each filter should try to prevent them from making any assumptions about whether other filters exist. In this way, the combination can be maintained, that is, the ability to add, delete, or rearrange filters. In addition, some frameworks that implement the Intercepting Filter mode do not guarantee the execution sequence of the filter. If you find that multiple filters are highly dependent on each other, it is best to call the common method of the helper class, because this ensures that the constraint information in the filter sequence is retained. The direct implementation of Intercepting Filter is a filter chain, which can be used to traverse a list composed of all filters. The Web request processing program executes the filter chain before passing control to the application logic.


Figure 11 Intercepting Filter class diagram

When the Web server receives a page request, the request handler first passes control to the filterchain object. This object maintains a list of all filters and calls each filter in sequence. Filterchain can read the filter order from the configuration file to realize the combination during deployment. Each filter has the opportunity to modify the incoming request. For example, it can modify the URL or add the header field to be used by the application. After all the filters are executed, the request handler passes control to the Controller, which executes the application function (see figure 12 ).


Figure 12 Intercepting Filter sequence diagram

Because intercepting filters are often required when processing Web requests, most web frameworks provide a mechanism for application developers to link intercepting filters to request-response processes.

Page cache (page cache)

If a dynamically generated web page is frequently requested and requires a large amount of system resources during construction, how can we improve the response time of such web pages? The page cache improves the Request Response throughput by caching the content generated from a dynamic page. By default, page caching is supported in ASP. NET, but the output from any given response is not cached unless a valid expiration policy is defined. To define an expiration policy, you can use the low-level outputcache API or the advanced @ outputcache command.

The basic structure of page cache is relatively simple. The Web server maintains local data storage containing pre-generated pages (see figure 13 ).


Figure 13 basic page cache Configuration

The following sequence diagram illustrates why page cache can improve performance. The first sequence diagram (see figure 2) describes the initial status of pages not cached (that is, cache miss ). 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 process is a little slower than not cached because it performs the following additional steps:

1. Check whether the page is cached.

2. Convert the page to HTML code and store it in the cache.

Compared with database access and HTML generation, any of these steps should not take a long time. However, because additional processing is required in this case, you must ensure that the cache is hit multiple times after the system completes the steps associated with the cache miss (14 shown ).


Figure 14 cache miss sequence (when the page is not cached)

As shown in Figure 15, the page is already in the cache. By skipping database access, page generation, and page storage, cache hits save loops.


Figure 15 cache hit sequence (when the page is in cache)

In ASP. NET, the following three modes can be used to implement cache policies:

1. Insert commands such as <% @ outputcache duration = "60" varybyparam = "NONE" %> into each page to be cached. Specifies the Refresh Interval (in seconds ). The refresh interval does not depend on external events, and the cache cannot be completely refreshed.

2. Vary-by-parameter caching. This mode uses the absolute expiration variant, which allows developers to specify parameters that affect page content. Therefore, the cache stores multiple versions of the page and indexes these page versions based on their parameter values.

3. Sliding expiration caching. This mode is similar to absolute expiration (absolute expiration), where the page is valid within the specified time. However, the refresh interval is reset during each request. For example, you may use the sliding expiration cache to cache a page for up to 10 minutes. As long as the page request is sent within 10 minutes, the expiration time will be extended by 10 minutes.

Conclusion

since then, we have fully introduced the various modes related to the web representation cluster and the usage of the observer (observer) mode in the MVC mode, we will use a dedicated space to introduce some references mentioned in the text can find a relatively detailed list in the http://www.microsoft.com/china/msdn/architecture/patterns/EspBiblio, 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.