Saturday, April 14, 2012

Extension Methods (C# Programming Guide)

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable  and System.Collections.Generic.IEnumerable types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable(Of T) appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable(Of T) type such as List(Of T) or Array.

The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this is not a requirement for extension methods.
class ExtensionMethods2    
{
    static void Main()
    {            
        int[] ints = { 10, 45, 15, 39, 21, 26 };
        var result = ints.OrderBy(g => g);
        foreach (var i in result)
        {
            System.Console.Write(i + " ");
        }           
    }        
}
//Output: 10 15 21 26 39 45
 
 
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

The following example shows an extension method defined for the System.String class. Note that it is defined inside a non-nested, non-generic static class:
 
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
} 
 
The WordCount extension method can be brought into scope with this
using directive:
 
using ExtensionMethods;
 
string s = "Hello Extension Methods";
int i = s.WordCount();
 
In your code you invoke the extension method with instance method 
syntax. However, the intermediate language (IL) generated by the 
compiler translates your code into a call on the static method. 
Therefore, the principle of encapsulation is not really being 
violated. In fact, extension methods cannot access private variables 
in the type they are extending.
 
 
 

Tuesday, February 14, 2012

Enterprise Library 5 Exception Handling

Last week I discovered a nice feature inside the Enterprise Library 5 Exception Handling application block. On the ExceptionManager class a new method is available called Process(). This method automatically performs exception management and throws the exception based on the configuration. It accepts the policy name and a delegate or a lambda expression; the application block manages any exception that occurs while executing the method or lambda expression, also if the postHandlingAction is set to ThrowNewException then the application block throws the exception as a result of the respective execution of the configured exception handlers.
This minimizes the amount of exception logic you need to write a lot. Typical usage of the Process method will be similar to the code snippet given next:
   1:  //Get instance of ExceptionManager using static method of Enterprise Library Container
   2:   
   3:  ExceptionManager exManager = EnterpriseLibraryContainer.Current.GetInstance();
   4:   
   5:  Order order = null;
   6:  OrderRepository orderRepository = new OrderRepository();
   7:   
   8:  //try..catch block not required...
   9:  //Automatic Exception Management through Process method
  10:  order= exManager.Process(
  11:     () => 
  12:        { 
  13:           return orderRepository.GetOrder(1000); 
  14:        }
  15:     ,"Data Access Policy");

Enterprise Library: Caching Application Block

The Enterprise Library Caching Application Block lets developers incorporate a local cache in their applications. It supports both an in-memory cache and, optionally, a backing store that can either be the database store or isolated storage. The Caching Application Block can be used without modification; it provides all the functionality needed to retrieve, add, and remove cached data. Configurable expiration and scavenging policies are also part of the block.

The Enterprise Library Caching Application Block includes the following features:

  • You can use the graphical Enterprise Library configuration tools to manage configuration settings.
  • You can configure a persistent storage location, using either isolated storage or the Enterprise Library Data Access Application Block, whose state is synchronized with the in-memory cache.
  • Administrators can manage the configuration using Group Policy tools.
  • You can extend the block by creating custom expiration policies and storage locations.
  • You are assured that the block performs in a thread-safe manner.

Enterprise Library 5.0

Enterprise Library consists of reusable software components that are designed to assist developers with common enterprise development challenges. It includes a collection of functional application blocks addressing specific cross-cutting concerns such as data access, logging, or validation; and wiring blocks, Unity and the Interception/Policy Injection Application Block, designed to help implement more loosely coupled testable, and maintainable software systems.

Different applications have different requirements, and you will find that not every application block is useful in every application that you build. Before using an application block, you should have a good understanding of your application requirements and of the scenarios that the application block is designed to address. Note that this release of the Enterprise Library includes a selective installer that allows you to choose which of the blocks you wish to install.

Microsoft Enterprise Library 5.0 contains the following application blocks:

  • Caching Application Block. Developers can use this application block to incorporate a cache in their applications. Pluggable cache providers and persistent backing stores are supported.
  • Cryptography Application Block. Developers can use this application block to incorporate hashing and symmetric encryption in their applications.
  • Data Access Application Block. Developers can use this application block to incorporate standard database functionality in their applications, including both synchronous and asynchronous data access and returning data in a range of formats.
  • Exception Handling Application Block. Developers and policy makers can use this application block to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
  • Logging Application Block. Developers can use this application block to include logging functionality for a wide range of logging targets in their applications. This release further improves logging performance.
  • Policy Injection Application Block. Powered by the Interception mechanism built in Unity, this application block can be used to implement interception policies to streamline the implementation of common features, such as logging, caching, exception handling, and validation, across a system.
  • Security Application Block. Developers can use this application block to incorporate authorization and security caching functionality in their applications.
  • Unity Application Block. Developers can use this application block as a lightweight and extensible dependency injection container with support for constructor, property, and method call injection, as well as instance and type interception.
  • Validation Application Block. Developers can use this application block to create validation rules for business objects that can be used across different layers of their applications.

Enterprise Library also includes a set of core functions, including configuration and instrumentation, and object lifecycle management. These functions are used by all other application blocks.

Common Scenarios

Enterprise Library can be useful in a variety of situations:

  • Enterprise Library provides sufficient functionality to support many common scenarios that enterprise-level applications must address.
  • Enterprise Library can serve as the basis for a custom library. You can take advantage of the extensibility points incorporated in each application block and extend the application block by adding new providers. You can also modify the source code for the existing application blocks to incorporate new functionality, and even add new application blocks to Enterprise Library. You can either develop extensions for existing application blocks and new application blocks yourself, or you can use extensions and application blocks developed by others.
  • Enterprise Library is designed so that its application blocks can function independently of each other. You need to install and add only the application blocks that your application will use; you do not need to install or add the entire library.
  • Enterprise Library includes the source code and the unit tests for all application blocks. This means you can explore the implementations, modify the application blocks to merge into your existing library, or you can use parts of the Enterprise Library source code in other application blocks or applications that you build.
  • Enterprise Library includes documentation, hands-on labs, and source code. Enterprise Library embodies many design patterns, and demonstrates good architectural and coding techniques. You can use the library as a tool for learning architectural, design, and coding proven practices.

What's New

This major release of Enterprise Library contains many compelling new features and updates that will make developers more productive. There are no new blocks; instead the team focused on making the existing blocks shine, on testability, maintainability and learnability. The new features include:

  • Major architectural refactoring that provides improved testability and maintainability through full support of the dependency injection style of development
  • Dependency injection container independence (Unity ships with Enterprise Library, but you can replace Unity with a container of your choice)
  • Programmatic configuration support, including a fluent configuration interface and an XSD schema to enable IntelliSense
  • Redesign of the configuration tool to provide:
    • A more usable and intuitive look and feel
    • Extensibility improvements through meta-data driven configuration visualizations that replace the requirement to write design time code
    • A wizard framework that can help to simplify complex configuration tasks
  • Data accessors for more intuitive processing of data query results
  • Asynchronous data access support
  • Honoring validation attributes between Validation Application Block attributes and DataAnnotations
  • Integration with Windows Presentation Foundation (WPF) validation mechanisms
  • Support for complex configuration scenarios, including additive merge from multiple configuration sources and hierarchical merge
  • Optimized cache scavenging
  • Better performance when logging
  • Support for the .NET 4.0 Framework and integration with Microsoft Visual Studio 2010
  • Improvements to Unity
  • A reduction of the number of assemblies

Saturday, February 11, 2012

ASP.NET MVC Overview

The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.

MVC design pattern



MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.

The MVC framework includes the following components:

  • Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.

    In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.

  • Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit Boldview of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.

  • Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.

The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.

The loose coupling between the three main components of an MVC application also promotes parallel development. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.


When to Create an MVC Application


You must consider carefully whether to implement a Web application by using either the ASP.NET MVC framework or the ASP.NET Web Forms model. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.)

Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach.

Advantages of an MVC-Based Web Application

The ASP.NET MVC framework offers the following advantages:

  • It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.

  • It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.

  • It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller.

  • It provides better support for test-driven development (TDD).

  • It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.


Advantages of a Web Forms-Based Web Application

The Web Forms-based framework offers the following advantages:

  • It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.

  • It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller.

  • It uses view state on server-based forms, which can make managing state information easier.

  • It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.

  • In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.


The ASP.NET MVC framework provides the following features:

  • Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD). All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.

  • An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI enables you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This makes testing easier.

  • Extensive support for ASP.NET routing, which is a powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.

  • Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.

  • Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.


ASP.NET MVC

ASP.NET MVC is a free, fully supported Microsoft framework for developing great web applications using the Model-View-Controller pattern. It provides total control over your HTML and URLs, enables rich Ajax integration, and facilitates test driven development.

To find out more information about ASP.NET MVC, visit the following resources:


ASP.NET MVC 4 Developer Preview Released!

The ASP.NET MVC 4 Developer Preview is now available! To find out more about the release, visit our ASP.NET MVC 4 information page

You can install it via the Web Platform installer:

Or if you prefer to download the installers directly, visit the download details page.

ASP.NET MVC 3 RTM Released!

We've recently released RTM of ASP.NET MVC 3.

To learn about the new features introduced in ASP.NET MVC 3, visit the What's new in ASP.NET MVC 3 page and be sure to read the release notes.

IIS 7.0 New features

IIS7 will ship with both Windows Vista and Windows Longhorn Server. It's obvious that Microsoft has put a lot of time and effort into this release and you can expect IIS7 to be the platform of choice as soon as people can get their servers upgraded. It includes a several new functionalities with very rich integration with ASP.NET.

Feature 1: HttpModules and HttpHandlers can participate in all the requests i.e we can have a ASP.NET HttpModule for a JSP or PHP page even. Building HTTPmodules for authentication, authorization, logging, url-rewriting, auditing now will be very easy with .NET.

Feature 2: ASP.NET configuration can be integrated with IIS. IIS now uses the same web.config configuration model, which means you can have both configure ASP.NET and IIS in a single web.config file. You can now set things like default pages, IIS security, logging, etc within a web.config file and xcopy/ftp it to a server.

Feature 3: This has an integrated Admin UI tool that can manage both IIS and ASP.NET settings. Rich GUI supports settings for Membership, Roles and Profile providers. This tool also supports remote delegated admin over http -- which means you can point the rich-client admin tool at a shared host server and manage your users/roles/profile settings remotely over http.

Feature 4: It provides better request auditing and error debugging. A new functionality called "Failed Request Event Buffering" (affectionately known as "FREB") is introduced. This allows administrators to configure applications to automatically save request information anytime an error occurs during a request, or if a request takes longer than a specified amount of time to complete. This allows us to analyze what exactly happened during a request failure and what errors or exceptions have occurred. This can capture tracing messages generated within ASP.NET or within any component or class library that uses System.Diagnostics -- which makes it much easier for developers and admins to instrument and analyze what is going on with systems at runtimes.

Feature 5: It provides better configuration APIs and command-line tools. In addition to new config and admin APIs, we now have a great command-line admin story that you can use to set/modify/retrieve all configuration information as well as manage the server (start/stop individual apps, lookup their health state, register new apps, refresh SSL certs, etc). The class hierarchy in brief can be figured as: 
 

A code snippet uses the new .NET APIs to query IIS7 to list the active worker processes on the computer. It also lists the Requests and other details about the request like Url, Clinet IP address ..etc.
ServerManager iisManager = new ServerManager();
foreach(WorkerProcess w3wp in iisManager.WorkerProcesses) 
{
    Console.WriteLine("W3WP ({0})", w3wp.ProcessId);
    foreach (Request request in w3wp.GetRequests(0)) 
    {
        Console.WriteLine("{0} - {1},{2},{3}",
        request.Url,
        request.ClientIPAddr,
        request.TimeElapsed,
        request.TimeInState);
    }
}
 
 

Feature 7: Let us examine the new management UI. Here's what the new IIS Manager looks like: 


 


The first thing to notice is the new "Features View" which is shown above. While you can still use the "Content View" to show the files that make up your Web Site in the main pane of the tool, most of the time you'll be using the "Features View" to change site and application settings. 


Feature 8: "Actions" pane is a task-based pane shows you the most common tasks that are related to the currently selected object. For example, here's a close up of the "Actions" pane as it looks when the "Default Web Site" is the currently selected object.