Search This Blog

Wednesday, February 10, 2010

ASP.NET 4 and Visual Studio 2010 Web Development


Web.config File Minification


The Web.config file that contains the configuration for a Web application has grown considerably over the past few releases of the .NET Framework as new features have been added, such as Ajax, routing, and integration with IIS 7. This has made it harder to configure or start new Web applications without a tool like Visual Studio. In .the NET Framework 4, the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications either to be empty or to contain just the following lines, which specify for Visual Studio what version of the framework the application is targeting:


configuration
         system.web
              compilation targetFramework="4.0" /
        /system.web
/configuration
 
Extensible Output Caching


Since ASP.NET 1.0 was released, output caching has enabled developers to store the generated output of pages, controls, and HTTP responses in memory. On subsequent Web requests, ASP.NET can serve content more quickly by retrieving the generated output from memory instead of regenerating the output from scratch. However, this approach has a limitation — generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.

ASP.NET 4 adds an extensibility point to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. This makes it possible to create custom output-cache providers for diverse persistence mechanisms, which can include local or remote disks, cloud storage, and distributed cache engines.

You create a custom output-cache provider as a class that derives from the new System.Web.Caching.OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element, as shown in the following example:

caching
         outputCache defaultProvider="AspNetInternalProvider"
     
            providers
               add name="DiskCache"
               type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/
           /providers

     /outputCache

/caching


By default in ASP.NET 4, all HTTP responses, rendered pages, and controls use the in-memory output cache, as shown in the previous example, where the defaultProvider attribute is set to AspNetInternalProvider. You can change the default output-cache provider used for a Web application by specifying a different provider name for defaultProvider.

In addition, you can select different output-cache providers per control and per request. The easiest way to choose a different output-cache provider for different Web user controls is to do so declaratively by using the new providerName attribute in a control directive, as shown in the following example:

%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %

Specifying a different output cache provider for an HTTP request requires a little more work. Instead of declaratively specifying the provider, you instead override the new GetOuputCacheProviderName method in the Global.asax file to programmatically specify which provider to use for a specific request. The following example shows how to do this.

public override string GetOutputCacheProviderName(HttpContext context)
{
    if (context.Request.Path.EndsWith("Advanced.aspx"))
       return "DiskCache";
   else
      return base.GetOutputCacheProviderName(context);
}

With the addition of output-cache provider extensibility to ASP.NET 4, you can now pursue more aggressive and more intelligent output-caching strategies for your Web sites. For example, it is now possible to cache the "Top 10" pages of a site in memory, while caching pages that get lower traffic on disk. Alternatively, you can cache every vary-by combination for a rendered page, but use a distributed cache so that the memory consumption is offloaded from front-end Web servers.

 
Auto-Start Web Applications


Some Web applications need to load large amounts of data or perform expensive initialization processing before serving the first request. In earlier versions of ASP.NET, for these situations you had to devise custom approaches to "wake up" an ASP.NET application and then run initialization code during the Application_Load method in the Global.asax file.

A new scalability feature named auto-start that directly addresses this scenario is available when ASP.NET 4 runs on IIS 7.5 on Windows Server 2008 R2. The auto-start feature provides a controlled approach for starting up an application pool, initializing an ASP.NET application, and then accepting HTTP requests.

Permanently Redirecting a Page


It is common practice in Web applications to move pages and other content around over time, which can lead to an accumulation of stale links in search engines. In ASP.NET, developers have traditionally handled requests to old URLs by using by using the Response.Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URLs.

ASP.NET 4 adds a new RedirectPermanent helper method that makes it easy to issue HTTP 301 Moved Permanently responses, as in the following example:

RedirectPermanent("/newpath/foroldcontent.aspx");

Search engines and other user agents that recognize permanent redirects will store the new URL that is associated with the content, which eliminates the unnecessary round trip made by the browser for temporary redirects.

The Incredible Shrinking Session State


ASP.NET provides two default options for storing session state across a Web farm: a session-state provider that invokes an out-of-process session-state server, and a session-state provider that stores data in a Microsoft SQL Server database. Because both options involve storing state information outside a Web application's worker process, session state has to be serialized before it is sent to remote storage. Depending on how much information a developer saves in session state, the size of the serialized data can grow quite large.

ASP.NET 4 introduces a new compression option for both kinds of out-of-process session-state providers. When the compressionEnabled configuration option shown in the following example is set to true, ASP.NET will compress (and decompress) serialized session state by using the .NET Framework System.IO.Compression.GZipStream class.

Web.Config
sessionState mode="SqlServer" sqlConnectionString="data source=dbserver;Initial Catalog=aspnetstate"
 allowCustomSqlDatabase="true" compressionEnabled="true"
With the simple addition of the new attribute to the Web.config file, applications with spare CPU cycles on Web servers can realize substantial reductions in the size of serialized session-state data.




Expanding the Range of Allowable URLs


ASP.NET 4 introduces new options for expanding the size of application URLs. Previous versions of ASP.NET constrained URL path lengths to 260 characters (based on the NTFS file-path limit). In ASP.NET 4, you have the option to increase (or decrease) this limit as appropriate for your applications, using two new httpRuntime configuration attributes. The following example shows these new attributes.

httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048" /

To allow longer or shorter paths (the portion of the URL that does not include protocol, server name, and query string), modify the maxRequestPathLength attribute. To allow longer or shorter query strings, modify the value of the maxQueryStringLength attribute.

ASP.NET 4 also enables you to configure the characters that are used by the URL character check. When ASP.NET finds an invalid character in the path portion of a URL, it rejects the request and issues an HTTP 400 error. In previous versions of ASP.NET, the URL character checks were limited to a fixed set of characters. In ASP.NET 4, you can customize the set of valid characters using the new requestPathInvalidChars attribute of the httpRuntime configuration element, as shown in the following example:

httpRuntime requestPathInvalidChars="<,>,*,%,&,:,\"

By default, the requestPathInvalidChars attribute defines seven characters as invalid. (In the string that is assigned to requestPathInvalidChars by default, the less than (<), greater than (>), and ampersand (&) characters are encoded, because the Web.config file is an XML file.) You can customize the set of invalid characters as needed.

Note: ASP.NET 4 always rejects URL paths that contain characters in the ASCII range of 0x00 to 0x1F, because those are invalid URL characters as defined in RFC 2396 of the IETF (http://www.ietf.org/rfc/rfc2396.txt). On versions of Windows Server that run IIS 6 or higher, the http.sys protocol device driver automatically rejects URLs with these characters.

Other Features :


Starter Project Templates

Multi-targeting

Multiple Monitor Support

New Code Focused Web Profile Option

HTML / ASP.NET / JavaScript Code Snippets

Auto-Start ASP.NET Applications

URL Routing with ASP.NET 4 Web Forms

Searching and Navigating Code in VS 2010

VS 2010 Code Intellisense Improvements
WPF 4

Add Reference Dialog Improvements

SEO Improvements with ASP.NET 4
Output Cache Extensibility with ASP.NET 4
Built-in Charting Controls for ASP.NET and Windows Forms
 
 

Tuesday, February 2, 2010

Sessions, Instancing, and Concurrency in Windows Communication Foundation

A session is a correlation of all messages sent between two endpoints. Instancing refers to controlling the lifetime of user-defined service objects and their related InstanceContext objects. Concurrency is the term given to the control of the number of threads executing in an InstanceContext at the same time.


This topic describes these settings, how to use them, and the various interactions between them.

Sessions
 
When a service contract sets the System.ServiceModel.ServiceContractAttribute.SessionMode property to System.ServiceModel.SessionMode.Required, that contract is saying that all calls (that is, the underlying message exchanges that support the calls) must be part of the same conversation. If a contract specifies that it allows sessions but does not require one, clients can connect and either establish a session or not. If the session ends and a message is sent over the same session-based channel an exception is thrown.


WCF sessions have the following main conceptual features:

• They are explicitly initiated and terminated by the calling application.

• Messages delivered during a session are processed in the order in which they are received.

• Sessions correlate a group of messages into a conversation. The meaning of that correlation is an abstraction. For instance, one session-based channel may correlate messages based on a shared network connection while another session-based channel may correlate messages based on a shared tag in the message body. The features that can be derived from the session depend on the nature of the correlation.

• There is no general data store associated with a WCF session.

If you are familiar with the System.Web.SessionState.HttpSessionState class in ASP.NET applications and the functionality it provides, you might notice the following differences between that kind of session and WCF sessions:

• ASP.NET sessions are always server-initiated.

• ASP.NET sessions are implicitly unordered.

• ASP.NET sessions provide a general data storage mechanism across requests.

Client applications and service applications interact with sessions in different ways. Client applications initiate sessions and then receive and process the messages sent within the session. Service applications can use sessions as an extensibility point to add additional behavior. This is done by working directly with the InstanceContext or implementing a custom instance context provider.

Instancing


The instancing behavior (set by using the System.ServiceModel.ServiceBehaviorAttribute.InstanceContextMode property) controls how the InstanceContext is created in response to incoming messages. By default, each InstanceContext is associated with one user-defined service object, so (in the default case) setting the InstanceContextMode property also controls the instancing of user-defined service objects. The InstanceContextMode enumeration defines the instancing modes.

The following instancing modes are available:

• PerCall: A new InstanceContext (and therefore service object) is created for each client request.

• PerSession: A new InstanceContext (and therefore service object) is created for each new client session and maintained for the lifetime of that session (this requires a binding that supports sessions).

• Single: A single InstanceContext (and therefore service object) handles all client requests for the lifetime of the application.

The following code example shows the default InstanceContextMode value, PerSession being explicitly set on a service class.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class CalculatorService : ICalculatorInstance
{
 …
}

And while the System.ServiceModel.ServiceBehaviorAttribute.InstanceContextMode property controls how often the InstanceContext is released, the System.ServiceModel.OperationBehaviorAttribute.ReleaseInstanceMode and System.ServiceModel.ServiceBehaviorAttribute.ReleaseServiceInstanceOnTransactionComplete properties control when the service object is released.

Well-Known Singleton Services


One variation on single instance service objects is sometimes useful: you can create a service object yourself and create the service host using that object. To do so, you must also set the System.ServiceModel.ServiceBehaviorAttribute.InstanceContextMode property to Single or an exception is thrown when the service host is opened.

Use the System.ServiceModel.ServiceHost.#ctor(System.Object,System.Uri[]) constructor to create such a service. It provides an alternative to implementing a custom System.ServiceModel.Dispatcher.IInstanceContextInitializer when you wish to provide a specific object instance for use by a singleton service. You can use this overload when your service implementation type is difficult to construct (for example, if it does not implement a default parameterless public constructor).

Note that when an object is provided to this constructor, some features related to the Windows Communication Foundation (WCF) instancing behavior work differently. For example, calling System.ServiceModel.InstanceContext.ReleaseServiceInstance has no effect when a singleton object instance is provided. Similarly, any other instance-release mechanism is ignored. The ServiceHost always behaves as if the System.ServiceModel.OperationBehaviorAttribute.ReleaseInstanceMode property is set to System.ServiceModel.ReleaseInstanceMode.None for all operations.

Sharing InstanceContext Objects


You can also control which sessionful channel or call is associated with which InstanceContext object by performing that association yourself. For a complete example, see InstanceContextSharing.

Concurrency

Concurrency is the control of the number of threads active in an InstanceContext at any one time. This is controlled by using the System.ServiceModel.ServiceBehaviorAttribute.ConcurrencyMode with the ConcurrencyMode enumeration.

The following three concurrency modes are available:


• Single: Each instance context is allowed to have a maximum of one thread processing messages in the instance context at a time. Other threads wishing to use the same instance context must block until the original thread exits the instance context.

• Multiple: Each service instance can have multiple threads processing messages concurrently. The service implementation must be thread-safe to use this concurrency mode.

• Reentrant: Each service instance processes one message at a time, but accepts re-entrant operation calls. The service only accepts these calls when it is calling out through a WCF client object.

Note:


Understanding and developing code that safely uses more than one thread can be difficult to write successfully. Before using Multiple or Reentrant values, ensure that your service is properly designed for these modes. For more information, see ConcurrencyMode.

The use of concurrency is related to the instancing mode. In PerCall instancing, concurrency is not relevant, because each message is processed by a new InstanceContext and, therefore, never more than one thread is active in the InstanceContext.

The following code example demonstrates setting the ConcurrencyMode property to Multiple.

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
public class CalculatorService : ICalculatorConcurrency
{

}
Sessions Interact with InstanceContext Settings


Sessions and InstanceContext interact depending upon the combination of the value of the SessionMode enumeration in a contract and the System.ServiceModel.ServiceBehaviorAttribute.InstanceContextMode property on the service implementation, which controls the association between channels and specific service objects.

The following table shows the result of an incoming channel either supporting sessions or not supporting sessions given a service's combination of the values of the System.ServiceModel.ServiceContractAttribute.SessionMode property and the System.ServiceModel.ServiceBehaviorAttribute.InstanceContextMode property.


Popular Posts