Category: asp.net


ViewState in ASP.NET

Introduction

Microsoft ASP.NET Web Forms pages are capable of maintaining their own state across multiple client round trips. When a property is set for a control, the ASP.NET saves the property value as part of the control’s state. To the application, this makes it appear that the page’s lifetime spans multiple client requests. This page-level state is known as the view state of the page. In Web Forms pages, their view state is sent by the server as a hidden variable in a form, as part of every response to the client, and is returned to the server by the client as part of a postback. In this article we will see how View State is implemented in ASP.NET for state management and we will also see how effectively you can use this object in your web form.

Problems with ViewState

Viewstate has lots of advantages and as well as disadvantages, so you need to weigh carefully before making the decision to use it. As I told you early, view state doesnt require any server resources for its operation. It is passed to the client during every postback as an hidden element. Since it is added with every page, it adds few Kbytes to the page. This effects the loading of the page in the client. Other main problem with Viewstate is, since it is passed as plain text to the client. Anybody can tamper this value, because of this you shouldnt store any important data in the viewstate. View state is one of the most important features of ASP.NET, not so much because of its technical relevance, but more because it makes the magic of the Web Forms model possible. However, if used carelessly, view state can easily become a burden. Although ViewState is freely accessible in a hidden field called __VIEWSTATE, the view state information is not clear text. By default, a machine-specific authentication code is calculated on the data and appended to the view state string. The resulting text is then Base64 encoded only, but not encrypted. In order to make the view state more secure, the ASP.NET @Page directive supports an attribute called EnableViewStateMac whose only purpose is detecting any possible attempt at corrupting original data.

Implementation of ViewState

StateBag implements the view state and manages the information that ASP.NET pages and embedded controls persist across successive posts of the same page instance. The class works like a dictionary object and implements the IStateManager interface. The Page and the Control base classes expose the view state through the ViewState property. So you can add or remove items from StateBag as you would with any dictionary object:

ViewState(“FontSize”) = value

You should start writing to the view state only after the Init event is fired for a page request. You can read from the view state during any stage of the page lifecycle, but not after the page enters rendering mode—that is, after the PreRender event is fired.
The contents of the StateBag collection are first serialized to a string, then Base64 encoded, and finally assigned to a hidden field in the page that is served to the client. The view state for the page is a cumulative property that results from the contents of the ViewState property of the page plus the view state of all the controls hosted in the page.

Decision on ViewState Usage

As We ‘ve discussed here, the view state represents the state of the page and its controls just before the page is rendered in HTML. When the page posts back, the view state is recovered from the hidden field, deserialized, and used to initialize the server controls in the page and the page itself. However, this is only half the story.

After loading the view state, the page reads client-side information through the Request object and uses those values to override most of the settings for the server controls. In general, the two operations are neatly separated and take place independently. In particular, though, the second operation—reading from Request.Form—in many situations ends up just overriding the settings read out of the view state. In this particular case the view state is only an extra overhead. For example consider the following case, we have one textbox in the page and a link button. If you are typing the some  values in to the textbox and the posting the page using linkbutton. After postback, value in the textbox is retained though you enable or disable the viewstate. In this case you shouldnt enable viewstate for this textbox. Viewstate value is overridden by request.form values, since loadpostdata fires after loadviewstate view event in the Page lifecycle.

But if you consider that readonly property of textbox  is set to False by default. Then in the Page_Load if you are trying to change its readonly property to true based on certain condition. So after setting readonly property in Page_Load and if it is posted back by clicking linkbutton. To retain its readonly property across postback, we need to enable viewstate for this property. Otherwise this property wont be retained across postback.

Viewstate in DataGrid

If you have Set EnableViewState to true for a DataGrid which is having thousands of record. Then you will end up having viewstate size more than 10 KBytes. But if you disable viewstate, you will not be able to fire any events in DataGrid. Postback and acting on postback relies on Viewstate. So if it is readonly datagrid and if you are not going to use paging and sorting provided by datagrid, then you can disable viewstate. But if you want use above mentioned feature of DataGrid, then you can not disable ViewState in DataGrid. So to avoid excessive load on client machine because of viewstate . You can disable viewstate for each item in DataGrid. Disabling can be done in two ways, one way is disabling each itemtemplate columns viewstate to false.

<asp:TemplateColumn headertext=”ProductID”>
<ItemTemplate>
<asp:TextBox id=”ProductID” runat=”server”  EnableViewState=”False” >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>

Other way is by disabling viewstate for each datagrid item in Pre-Render event handler.

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles
MyBase.PreRender
Dim dgi As DataGridItem
For Each dgi In DataGrid1.Items
dgi.EnableViewState = False
Next
End Sub

Conclusion

The view state is a key element of an ASP.NET page because it is the primary means to persist the state of the Web server controls. Whenever the page posts back, the state is restored, updated using the current form parameters, then used to run the postback event handler. Normally, the view state is a hashed string encoded as Base64 and stored in a hidden field called __VIEWSTATE. In this way, the view state is not cached on the client, but simply transported back and forth with potential issues both for security and performance. Since it is performance overhead, you need to decide properly when and where you should use viewstate in your webform.

(The above notes has been referred from the site http://www.extremeexperts.com)

          When problems occur with a SharePoint Portal Server, your first instinct is probably to look at the Event Viewer. While the Event Viewer can certainly provide some useful information, you might be surprised to learn that another good source of troubleshooting information is the Performance Monitor. Microsoft has included several Performance Monitor counters that are specific to SharePoint. In this article, I’ll review a few of the many SharePoint performance Monitor counters that are useful in troubleshooting situations.

 

Microsoft GathererHeartbeats

This service displays the number of heartbeats that have occurred since the SharePoint services were started. By default, a heartbeat occurs every ten seconds.  If you see that the heartbeats aren’t increasing, it means that the SharePoint services have either stopped or are unresponsive.

 

Microsoft GathererReason To Back Off

 Check this counter to see if its value is higher than zero. A non zero number means that document crawling has been paused because of insufficient system resources. Usually a non zero value indicates that the system is low on memory or that the current disk IO is too high to process requests.

 

Microsoft Search Indexer CatalogsNumber of Documents

 Another useful counter is the Number of Documents counter. The Number of Documents counter reports the number of documents in the catalogue. This is useful for seeing how heavily the SharePoint server is being used. For example, you can tell over time if the number of indexed documents remains fairly static, goes up, or even goes down. This is a really good counter to check out if you start having disk space problems.

 

Microsoft Search Indexer CatalogsIndex Size

 This counter reports the size of the document index in megabytes. If you watch this counter over time, you can track the rate at which the index is growing, and can use that information to predict how quickly your server may run out of hard disk space.

 

Microsoft GathererDocuments Delayed Retry

 This counter displays a value. Normally, the value should be zero, but a non zero value means that SharePoint is having problems accessing the Web storage system. These failed access attempts will keep retrying until successful. Therefore, if the Documents Delayed Retry value momentarily goes above zero and then goes back down, it means that the system was simply busy at the time of the original request, but later was able to catch up with the demand being placed on it. If however, the number continues to steadily rise, then it indicates a Web storage system failure.

 

Microsoft GathererActive Queue Length

This counter indicates the number of documents that are waiting for a robot thread to process them. Normally, this number should be zero. If this number is not zero, it means that the server is falling behind, although this may be a temporary condition caused by an especially busy period. If this number is anything other than zero, then all available threads should be filtering. If the number is above zero, but all possible threads aren’t filtering, it usually means that the SharePoint services need to be stopped and restarted.

 

          Monitoring performance regularly, organizations can recognize trends as they develop and prevent performance problems. This will also help to decide when to upgrade the hardware and whether upgrades are improving the server’s performance.

 

 

General Server Performance Counters

 

Following is a list of general performance counters that should be monitored for all SharePoint Portal Server based servers.

 

Performance Object

Counter

Threshold

Description

Processor

Percent processor time_total

80 to 85 percent averaged over three intervals

The total percentage of processor usage for a server.

Network interface

Bytes total per second_network interface

50 percent of the available network interface bandwidth — for example, a 100-MB network interface running at 50,000 KB per second

The rate at which bytes are sent and received over each network adapter.

Logical disk

Percent idle time_ (drives C:,D:, and so on)

20 percent over idle time_.

Reports the percentage of time during the sample interval that the disk was idle. If this value is very low, the logical disk is very busy.

Paging file

Percent usage

Above 70 percent

Review this value in conjunction with memory — available megabytes and page faults per second — to understand paging activity on the server.

Memory

Available MBs

128 MB — assuming 2 GB of RAM as prescribed on servers

The amount of physical memory, in MBs, immediately available for allocation to a process or for system use on the server.

Memory

Page faults per second

20

A high rate of page faults indicates a lack of physical memory.

System

Processor queue length

The number of CPUs + 1

Exceeding the threshold indicates that the processors are not fast.

ASP.NET applications

Requests per second_total

Through ongoing monitoring, trends begin to emerge that equate requests per second with CPU consumption

The number of requests executed per second; this roughly equates to the number of HTTP pages per second.

Table 1: General Windows Server 2003 Performance Counters

 

 

SharePoint Portal Server Counters

 

A SharePoint Portal Server supports many topologies that allow organizations to set up different server farm environments from small server farms to larger load balance server farm environments according to an organization’s requirements. This will introduce various numbers of Web Servers, Search Server and Index Servers in to the SharePoint farm environment. Some server farms can contain more than one SharePoint component bundled up together. For example, Web and Search components together in a single server.

The following table contains a list of performance counters that are relevant for all of the SharePoint components.

Object

Counter

Threshold

Description

Processor

Percent processor time_total

80 to 85 percent averaged over three intervals

The total percentage of processor usage for a server.

ASP.NET applications

Requests per second_total

Through ongoing monitoring, trends begin to emerge that equate requests per second with CPU consumption

The number of requests executed per second; this roughly equates to the number of HTTP pages per second.

Web service

Get requests per second_total, individual portal, or IIS Virtual root

Through ongoing monitoring, trends begin to emerge that equate get requests per second with CPU consumption

Generally speaking, this is the rate at which clients are requesting information from the front-end Web servers.

Search

Query rate

10 per second

The number of queries posted to the server per second; keep in mind that in the medium server farm configuration, the front-end servers are doing much more than searching.

Search

Succeeded queries

This counter should be used mostly for troubleshooting search problems

The number of queries that produce successful searches. Monitor this counter along with the failed queries counter if you need to troubleshoot search problems.

Search catalogs

Number of documents

Microsoft has tested up to 5 million documents per content index

The total number of documents in the catalog.

Search catalogs

Queries rate_(index names or all instances)

Indicates which catalogues are searched most often by users

The number of queries posted to indexes per second; in conjunction with other performance data, this can help determine if your index configuration can be optimized.

Table 2: SharePoint Portal Server Performance counters

 

 

Front End Web Servers in a Server Farm

 

The Processor, ASP.NET application and Web Service performance objects determine when to add a new dedicated Front End Web server to the farm environment. When above three performance objects counters continuously approach or exceed any of the thresholds; organizations should consider adding additional Front End Web servers to the server farm. At the same time make sure you check the general counters in Table 1 to better understand the Windows Server 2003 server performance.

The “percent processor time” counter is the main indicator of Front End Web server performance. The organization should gather this information every 15 minutes to determine the health of the Front End Web server. If the organization is having high performance expectations, this counter should record a lower average threshold.

Having a heavily used Windows SharePoint Services Site can add extensive performance impact on Front End Web servers. Organizations should identify these kinds of WSS sites and consider scaling out one or more those sites to a separate server farm to reduce the performance impact on Front End Web servers.

 

Front End Web / Search Servers in a Server Farm

Table 2 lists the important performance counter for a Front End Web server with SharePoint Search component in a server farm. If the “search catalog” size exceeds 5 million, Microsoft recommends adding an additional Front End / Searching server to the server farm or separating the indexing by moving the Indexing server to a dedicated Indexing server. This will reduce the propagation and crawling time.

The amount of CPU time taken for the search operations is another key factor of monitoring the health of the server farm. When the “query rate” counter exceeds the recommended threshold and search operations consumes more than 40 to 50 percent of the overall server capacity, organizations should consider scaling out toward a Larger Server Farm. If percent processor time is exceeding the threshold but the query rate is below the threshold and front end web traffic is bringing the server to its maximum capacity, the organization should consider adding an additional Front End Web/Search server to the Server Farm.

 

Index Servers

The main performance thresholds for index servers are 80 to 85 percent processor time and 85 percent memory availability. Adding additional indexing servers to a farm environment is not totally done looking at performance counters. It is more determined by the function of indexing and propagation time. When it take few hours for an incremental crawl and propagation, and the organization needs this to be done in half hour, consider adding another indexing server.

Performance of an indexing server also depends on the location of the crawled content and the processing power of the indexing server. Crawl time may depend on content location, network performance, type of documents in the index, frequency and type of content index updates.

Microsoft recommends no more than four index servers per large server farm.

 

Microsoft SQL Server

The present processor time counter is the leading indicator for Microsoft SQL Server performance. Examine percent processor time in conjunction with overall memory capacity, network traffic and input/output subsystem capacity will provide an accurate health report on your dedicated SQL Server on the SharePoint farm.

 

Internet Information Services (IIS) Logs

IIS logs include detailed information such as who has visited sites and what was viewed, in terms of total visits, page views and trends over time. Careful analysis of IIS logging data will help organizations to discover how much traffic is going to portal sites, how much is going to WSS sites and search operations.

It will also help organizations to identify bottlenecks and performance issues. Most importantly this will help to identify the most used Windows SharePoint Services Sites in the portal and its impact on the Front End Web server. According to this information, organizations can decide when to move one or more site collections to a dedicated Windows SharePoint Services server farm to reduce the performance impact on the Front End Web server.

 

Setting Up IIS Log Files

Set up logs files to be created daily for each virtual server. It is good practice to locate these logs separate from the drive that holds the operating system data. The local administrators group and the IIS_WPG group should have access to the log file directory.

IIS logging is enabled by default for each virtual server. The user can check whether IIS logging is enabled by following these steps.

 

·         Click Start -> Run

·         Then in the Run window type “inetmgr” to open the Internet Information Services (IIS) Manager

·         Select the virtual directory, right click and select the Properties menu option

 

The recommended log file format for IIS logs is the W3C format. This is the default log file format and enables you to select the fields you want to include in the log file. By limiting the number of fields you can simplify the process of identifying the data and save server resources, CPU usage. User can follow these steps to select the logging properties for their virtual server.

 

·         In the Properties window of the virtual server select the Properties button next to “Active log format”

·         The Logging Properties window will open as displayed in Figure 4

·         This window enables the user to select the appropriate schedule that will suit their organization (daily is recommended)

·         This screen also displays the log file directory and file name.

·         Select the Advanced (or Extended Properties) option from the top tab section

 

The following window will open allowing you to select from all the available fields:

IIS logs files can also be logged in a database that complies with Open Database Connectivity (ODBC), such as Microsoft SQL Server database as displayed in figure 6.

The information being logged to the SQL Server then can be reviewed by generating reports using the SQL Server Query Analyser.

 

 

Conclusion

 

Organizations can use the Windows 2003 System Monitor, Performance logs and alerts to monitor their SharePoint Portal Server environment. The performance counter details were taken from Microsoft SharePoint Products and Technologies Resource Kit.

 

Follow

Get every new post delivered to your Inbox.