Asp. NET nine choices for maintaining user status (next)

Source: Internet
Author: User
Tags config current time datetime empty implement sessions tostring
asp.net ASP. The new state container in net

As we mentioned earlier, ASP. NET adds several new ways to save data between user requests. These pathways give you a better grip on how to keep your state information. These technologies can be as narrow as a single request (context object) or wide to all applications on the Web server and on the server (machine.config files). In most cases you have a variety of options for saving specific pieces of data-using each method to describe questions and answers to determine whether an object is appropriate for your needs.

Cache

The cache object is used for a single user, a group of users, or all users. This data is persisted for multiple requests. It can be maintained for a long time, but it cannot exceed the time of application restart, and data termination is based on time or other dependencies. It can keep large or small amounts of data efficiently.

Cache is one of the most "cool" objects in asp.net. It provides incredible flexibility, versatility, and performance, so it's usually better to keep the data than application or sessions in a asp.net application. This article does not describe the use of the cache object in detail, but it can still be said that it is a universal object. Similar to other collection objects, it is a simple name-value collection, but you can cache a specific user's value by using a key value that specifies a particular user. Similarly, you can cache multiple datasets of different related data, such as a few car sets with keys (such as Fordcars, Chevycars, Gmcars). The data in the cache can be given an absolute, variable, or file-based termination time. They also implement a callback function that is invoked when the cached value is extracted from the cache, which is useful because then you can check whether it is the most recent data variable, and if not (or the data source is not available), cache the terminated value.

The syntax for adding and accessing values in the cache is similar to the previous talk. However, the cache provides a complement to the standard indexer method for accessing the contents of the collection, which supports a variety of methods that allow more control over the cached data. The most frequently used method is insert, which supports several overloads that allow you to specify dependencies, timeout values, priorities, and callbacks. Here are some simple examples:


Adding items to the cache
cache["MyKey"] = myvalue;

Reading items from the cache
Response.Write (cache["MyKey"]);

Add the CacheDuration to the cache by adding 10 seconds
Cache.Insert ("MyKey", myvalue, NULL, System.DateTime.Now.AddSeconds (10),
System.Web.Caching.Cache.NoSlidingExpiration);

One of the most powerful features of a cache object is the ability to perform a callback when an item in the cache terminates. It uses a delegate or function pointer, which is not discussed in this article. Fortunately, once you have some examples of how these technologies work, you can use them in your application simply by cutting and pasting, without knowing the complex process of how the delegate works. There are many reasons to use this functionality, most commonly by populating the cache with the current data when the data is terminated, or by restoring the old cached data if the cached data source is not available.

In my example, the current time is simply cached, and when the cache is extended I will add an asterisk (*) to the end of the string in the cache. After time, you can determine how many times the cache has expired by counting the number of asterisks. Figure 9 illustrates the important concepts of callbacks and provides a good template for using caching to create more feature callbacks.


private void Page_Load (object sender, System.EventArgs e)
{
String cachekey = "MyKey";
String data = "";
Check if the data has been cached
if (cache[cachekey]==null)
{
Because the data is in the cache, all the data read
data = System.DateTime.Now.ToString ();

Establish an instance of a callback delegate
CacheItemRemovedCallback callBack =new CacheItemRemovedCallback (onremove);

Label1.Text = "Generated:" + data;

Cache.Insert (Cachekey,data,null,
System.DateTime.Now.AddSeconds (5),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default,
CallBack);
}
Else
{
Label1.Text = "Cached:" + Cache[cachekey]. ToString ();
}
}

private void OnRemove (string key, Object Val,cacheitemremovedreason reason)
{
Establish an instance of a callback delegate
CacheItemRemovedCallback callBack =new CacheItemRemovedCallback (onremove);
Cache.Insert (Key,val. ToString () +
"*", Null,system.datetime.now.addseconds (5), Cache.noslidingexpiration,
System.Web.Caching.CacheItemPriority.Default, CallBack);
}

Code Snippet 5. Cache Callback Example

Note An important feature in the code snippet is the use of patterns (pattern) in Page_Load to determine whether to use the data in the cache. This pattern may also be used when you are working with items in the cache. Use the IF statement to check that the current content of the cache is empty (because a variable is used for the cache key because it is referenced more than once). If it is empty, generate the data from the data source and put it in the cache. If it is not empty, the data is returned from the cache. If the data access logic is complex, you need to put the entire if statement into a separate function that is tasked with retrieving the data.
The cache object has much more functionality than most of the objects we discussed earlier. This is one of the more powerful features of ASP.net, and I definitely recommend reading more about it.

Context

The context object maintains data for a single user, a single request, and the data is persisted only during that request. The context container can maintain a large amount of data, but typically saves small slices of data, because it is often implemented through a processing method in Global.asax for each request.

The context container (accessed from the Page object or using System.Web.HttpContext.Current) is provided to maintain values that need to be passed between different httpmodules and httphandlers. It can also be used to maintain the appropriate information for a complete request. For example, the IBuySpy Portal fills a container with a lot of configuration information in the Application_BeginRequest event procedure in Global.asax. Note that this is only available on the current request, and consider using ViewState if you want to use it in the next request.

The syntax used to set and get data from the context collection is similar to the other collection objects discussed earlier, such as application, sessions, and Cache. Here are two simple examples:


Add an item to the context
context.items["MyKey"] = myvalue;

Reading items from the context
Response.Write (context["MyKey"]);

ViewState

ViewState maintains state information for a single user and holds the duration of the ASPX page working time. The ViewState container can maintain a large amount of data, but must be careful to manage the size of the viewstate because it increases the download (download) size of each request and response.

ViewState is a new container in ASP.net, perhaps you have used it, but you may not understand it. This is because all of the built-in Web controls use ViewState to keep their values between page postbacks (postback). But you have to be careful because it affects the performance of your application. The size of the impact depends on how much viewstate is used between postbacks-a very small number for most Web forms.

The easiest way to determine the number of viewstate used by each control on a page is to open page tracking and check how many viewstate each control loads. If a particular control does not need to persist data between postbacks, close the ViewState of the object by setting EnableViewState to False. You can also determine the total size of a given ASP.net page viewstate by looking at the HTML source in the browser and checking the hidden form field __viewstate. Note that the content is encoded using BASE64 to place accidental viewing and maintenance. ViewState can also be banned throughout the page by adding enableviewstate= "false" to the @page directive.

A typical Web form does not need to maintain viewstate directly. But if you build a custom Web control, you need to understand how it works and implement it for your control so that it works the same way as a Web control that is published with ASP.net. Reading or writing values to ViewState can be accomplished by the syntax of the other collection objects discussed above:


Add items to ViewState
viewstate["MyKey"] = myvalue;

Reading items from the context
Response.Write (viewstate["MyKey"]);

When creating custom Web controls, you may want them to have viewstate benefits. This is simple to implement in the control's property layer. Code Snippet 6 demonstrates how to save a simple custom control's PersonName property into viewstate and use it in the control's Render method.


Namespace MSDN. StateManagement
{
public class HelloPerson:System.Web.UI.Control
{
public string PersonName
{
Get
{
string s = (string) viewstate["PersonName"];
Return ((s = = null)? "": s);
}
Set
{
viewstate["PersonName"] = value;
}
}
protected override void Render (System.Web.UI.HtmlTextWriter writer)
{
Writer. Write ("Hello" + personname);
}
}
}

Code snippet 6. Save data in ViewState

Web.config and Machine.config files

The data in these files is available to all users of an application. The data stored in the Web.config file is available for the entire lifecycle of the application. This data is generally small and is typically used to keep the file location and the string of database connections. Large data slices are best kept in other locations.

As a complement to other diverse collections of objects, ASP. NET introduces a set of XML configuration files to manage many settings for an application or even the entire server. Each asp.net application uses the Web.config file to set many of its properties, and each server has a Machine.config file that is the basis for the application under the System folder. These settings are used as default values, unless overloaded. As a supplement to saving configuration data, these files can hold data that is required by an application (or multiple applications).

Whenever the application starts, the configuration information is read, and the information is buffered. Because they are buffered, applications can quickly read them, so there is no need to consider the application bottleneck because it often executes some integer information for a text file. In addition, Web.config changes to an application will cause the application to restart. This ensures that changes to profile information are immediately reflected in the application.

Database connection information, the default image path, and the XML data file path are the data slices that are typically saved in the Web.config file. The syntax for saving data in Web.config files is as follows, ideally you might want to use integrated SQL authentication:


<configuration>
<!-Application Special Settings-->
<appSettings>
<add key= "connectionString" value= "server=mydbserver;
Uid=myuid;pwd=mypassword;database=mydb "/>
</appSettings>
<system.web>
<!-all the WSB settings-->
</system.web>
</configuration>

In order to access the values in the ASP.net page, you can use the ConfigurationSettings collection, which is in the System.Configuration name space. The following simple example shows how to extract the previous connection string into a local variable:

Using System.Configuration;
Ooo
String strconnstring =
configurationsettings.appsettings["ConnectionString"];

Adding a reference to the System.Configuration namespace reduces the number of code that references these values. Because modifications to Web.config or Machine.config will cause the application to restart immediately, typically these values are only manually modified by the server system administrator. So you can think of these files as a good place to save read-only data rather than modified data in your application.

Conclusion

Effective state management implies a significant difference between the user experience identified, the data error, and the fast page or transaction processing. Although state management is not quite applicable in ASP 3.0, ASP.net takes it to the state object under discussion in this article. Using them carefully will allow you to present the best Web experience to your users.




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.