Friday, 22 November 2013

Web API Routing

The diagram below tries do describe the decision process behind selecting the method of the controller that will get executed. I've added a little extra documentation through the annotations on the diagram.



1 Action Based
If the route defines the action parameter then the method selection will be based on the value of that parameter. The matching will be based on the method name or the method alias (A method in the controller may be aliased using the ActionName attribute).
All the matching methods are then filtered by verb. The filtering is done by attributes applied to the method (such as HttpGet). Only the methods that match the verb of the incoming request will be returned. Methods with no attributes will also be considered valid as they don’t have any attributes to allow filtration.

2 Verb Based
When the method selection is verb based we need to get the Http verb used in the request. The controller methods are then filtered in two ways:

Get all the methods annotated with http verb attributes matching the http method in the request (attributes such as HttpGet or HttpPost);
Get all the methods that have the prefix matching the http method in the request (PostBooks matches the Post verb);
3 Check Results Found
All the candidate methods returned by either the verb based or action based approach are then analyzed. If no candidates where found an exception is thrown. If multiple methods were found it’s necessary to analyze it’s parameters to find out the best possible fit.

4 Find Route by Parameters
The parameters from the route and the parameters from the query string are compared to the method's parameters. If no parameters are found in the query string or in the route, all methods without parameters will be selected. If multiple methods match the parameters found, the ones that take the most parameters will win. Here is a diagram that details this specific part of the process:



5 Selection Filters
The last filters executed on the candidate methods will make sure that all methods marked with the NonAction attribute will be excluded.


I hope these diagrams were clear enough to help understand better the process of selecting the controller method that gets executed for a request.

Orginal post : http://perezgb.com/2012/03/08/web-api-routing-in-depth

Friday, 20 January 2012

Finalize, Dispose and Unmanaged Resources

There may be situations where some class has control over resources that are not managed by the runtime such as window handles, database connections, etc. and these resources need to be released as they occupy more memory or affect performance. It can be done explicitly by calling Dispose () to release these objects immediately when they are no more needed. Similarly these objects can also be released implicitly by implementing Finalize() so that they get collected by GC in case someone forgets to call dispose () on these objects. Also since calling Finalize impacts the performance, calls to Finalize can be prevented by invoking the GC.SuppressFinalize method but it should be made sure that it only gets called after Dispose method has completed successfully.

Public class Base:IDisposable
{
       Private bool disposed = false;
      //Implement IDisposable.
      Public void Dispose()
     {
         Dispose(true);
         GC.SuppressFinalize(this);
      }

Protected virtual void Dispose(bool disposing)
{
    if (!disposed)
   {
       if (disposing)
      {
          // Free managed objects.
       }
       // Free unmanaged objects.
       disposed = true;
    }
}
     // using destructor for finalization.
    ~Base()
    {
        Dispose (false);
     }
}

Public class Derived: Base
{
     Private bool disposed = false;
     Protected override void Dispose(bool disposing)
     {
          if (!disposed)
         {
             if (disposing)
            {
                 // Release managed resources.
             }
             // Release unmanaged resources
             disposed = true;
        }
        base.Dispose(disposing);
     }
}

Public class Test
{
      Public static void Main()
      {
          //Scenario#1
          // Dispose is not called; Finalize will be called
          Derived a1 = new Derived();
          . . . . . . . .

          //Scenario#2
          //Dispose is implicitly called in the scope of the using statement.
          using (Derived a2 = new Derived())
          {
                . . . . . . . .
           }

          //Scenario #3
          // Dispose is explicitly called.
          Derived a3 = new Derived();
          . . . . . . . .
          a3.Dispose();
      }
 }

In the above example, object a2 and a3 are released by calling Dispose method of the base class as a result of which the overloaded dispose method of the derived class and then the base class dispose method gets called to release the managed and unmanaged resources .It can be also noted that the call to finalize() has been suppressed at the end of dispose. In case of object a1, since dispose() method is not called explicitly, finalize method gets called by GC which in turn calls the dispose method of derived class where the unmanaged resources gets released

Task Parallel Library

Problem: One of the clients was running the multi threaded application on a single core machine, he upgraded his system to Quadra-core and he observed that the application did not improve or started degrading the performance. The development team later found the reason that applications were not utilizing the benefits of cores and it was still running in single core. Solution: .Net 4.0 has brought a new Task Parallel library which uses the benefits of multi core. The Library efficiently utilizes the system resources to give better performance. Internally it uses Threadpool with improved algorithm with .Net 4.0

Namespace: System.Threading.
Tasks Class - Task

Create Task
Task t1 = new Task(() => Add(1,100));
t1.Start();
t1.Wait(); //Wait till task t1 is completed and then starts t2 Task
t2 = new Task(() => Add(101, 200));
t2.Start();

//Other way of creating multiple task
var tasks = new Task[2];
tasks[0] = Task.Factory.StartNew(() => Add(1, 100));
tasks[1] = Task.Factory.StartNew(() => Add(101, 200));
Task.WaitAll(tasks);

Create Dependency of Task
//Add and then display no’s and see output without creating Dependency
var tasks1 = new Task[4];
tasks1[0] =Task.Factory.StartNew(() => Add(1, 50));
tasks1[1] =Task.Factory.StartNew(() => Add(101, 150));
tasks1[2] =Task.Factory.StartNew(() => Display());
tasks1[3] =Task.Factory.StartNew(() => Display());

//Add and then display no’s and create dependency for sequential display
var tasks1 = new Task[4];
tasks1[0] =Task.Factory.StartNew(() => Add(1, 50));
tasks1[1] =Task.Factory.StartNew(() => Add(101, 150));
// start after completing adding of tasks1
tasks1[2] =tasks1[0].ContinueWith((t) => Display());
// start after completing tasks1[2]
tasks1[3] =tasks1[2].ContinueWith((t) => Display());

Cancel Running Task
For Cancelling a task following steps need to be performed:

1. Create Method with input parameter of Cancellation token and check for IsCancellationRequested Property of token to display the message that task is cancelled

public static void CancelProcess(CancellationToken ct)
{
      Thread.Sleep(1000);
      if (ct.IsCancellationRequested)
     {
         Console.WriteLine("Process cancelled");
     }
}

2. Create token:

      var source = new CancellationTokenSource();
      var token = source.Token;

3. Create task and call the CancelProcess method, also pass the token to the method
      var taskCancel = Task.Factory.StartNew(() => CancelProcess(token), token);

4. Cancel the token source on User's request:
      source.Cancel();

The Dynamic Primitive Type in C#

Runtime type identification made easy! Read on how new ‘dynamic’ type helps.

Let us look at the problems in versions prior to 4.0. A lot of times, we create programs that act on information unaware of its type until at runtime. A type-safe programming language like C# works with runtime-determined information during reflection and has to work a lot with strings which looks clumsy and cause performance problems as shown in the below example.

class Program
{
          public class MyType
         {
            public string MyProperty { get; set; }
          }
         static void Main(string[] args)
         {
             var myType = new MyType();
             var property = typeof(MyTestType).GetProperty("MyProperty");
             property.SetValue(myType, "Hello World", null);
         }
}

This is just a simple example which merely sets a property value of a type. Imagine how complex it would be and how clumsy your program would look if you have to Get \ Set ten different property values and then call ten other methods to perform various operations!!! It is no less than a nightmare to code and will have performance problems on top of it.

How C# 4.0 helps here: 
C# 4.0 brings in a cool new feature in the form of dynamic keyword which makes programmers life easy while working with runtime-determined information as in reflection. The C# compiler offers you a way to mark an expression’s type as dynamic. You can also put the result of an expression into a variable and you can mark a variable’s type as dynamic. This dynamic expression/variable can then be used to invoke a member such as a field, a property/indexer, a method, delegate, and unary/binary/conversion operators.

When your Code invokes a member using a dynamic expression/variable, the compiler generates special IL code that describes the desired operation. This special code is referred to as the payload.

At runtime, the payload code determines the exact operation to execute based on the actual type of the object now referenced by the dynamic expression/variable. Let’s try this on the same sample shown before and see how it makes life better.

class Program
{
       public class MyType
      {
          public string MyProperty { get; set; }
       }
      static void Main(string[] args)
     {
         dynamic myType = new MyType();
         myType.MyProperty = "Hello World";
     }
}

Isn’t it cool? Any expression can implicitly be cast to dynamic since all expressions result in a type that is derived from Object. Normally, the compiler does not allow you to write code that implicitly casts an expression from Object to another type; you must use explicit cast syntax. However, the compiler does allow you to cast an expression from dynamic to another type using implicit cast syntax:

Object o1 = 123; //OK:Imp cast
Int32 n1 = o1; //Err:No imp cast
Int32 n2 = (Int32)o1; //OK:Exp cast
dynamic d1 = 123; //OK:Imp cast
Int32 n3 = d1; //OK:Imp cast

The CLR will validate the cast at runtime to ensure that type safety is maintained. If the object’s type is not compatible with the cast, the CLR will throw an InvalidCastException exception. Sounds interesting? To know more, please refer to the following links: http://msdn.microsoft.com/en-us/magazine/ee336309.aspx http://msdn.microsoft.com/en-us/library/dd264736.aspx



Windows Server AppFabric Installation and Configuration


Preparing Your Computer for Installation


Operating System Windows 7, Windows Server 2003 R2 Standard
Visual Studio 2010 Ultimate 
Team Foundation Server
MS SQL Server 2008 R2
Internet Information Services (IIS) 7.5 with Hotfix #980423 
Microsoft .Net Framework 4.0
Download the Windows Server AppFabric 6.1 @ http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=15848
Recommended update for AppFabric at http://msdn.microsoft.com/en-us / windowsserver/ff637504.aspx.


Install Critical Windows Updates
Before installing Windows Server AppFabric or its prerequisites, use the following procedures to install the latest critical Microsoft updates for your version of Windows, and any available recommended update.


Versions of Windows supported in this release are Windows 7, Windows Server 2008 Service Pack 2, and Windows Server 2008 R2. For production scenarios, only Windows Server 2008 SP2 and Windows Server 2008 R2 are supported. For development scenarios, Windows 7 and Windows Vista SP2 are also supported. 


Install Windows Updates
Click Start, point to All Programs, and then click Windows Update.
Follow the directions on the Windows Update site.
If prompted, restart your computer.
Install Hotfixes


Important
For the latest list of recommended updates for Windows Server AppFabric and its dependencies, see Recommended Updates for Windows Server AppFabric (http://go.microsoft.com/fwlink/?LinkID=185864).


KB980423
You must install KB980423 to fix a set of AppFabric issues caused by Microsoft Web Administration (MWA). After you install this item, you may have to restart your computer.


KB980423 (http://go.microsoft.com/fwlink/?LinkID=185864)


Note 
KB980423 includes KB970773, which is a critical update for IIS Manager in IIS 7.0.
1. Install Windows Server AppFabric


Use the following procedure to install Windows Server AppFabric. You can use the procedures in this topic whether you are starting installation for the first time or adding or removing features after an initial installation. The installation program provides the following functionality:


Enables you to select specific features to install.
Validates the platform to ensure that the product is not installed in an unsupported state, and indicates which prerequisites need to be installed.
Installs AppFabric.
Enables you to remove specific AppFabric features or AppFabric as a whole, ensuring that the computer can be left in a state in which the features or AppFabric can be reinstalled.
Creates the AppFabric Event Collector service, the AppFabric Workflow Management service, and the AppFabric Caching Service. Sets the services to a startup type of manual and a status of stopped. In the configuration process, the Event Collector and Workflow Management services are changed to an automatic startup type and are started. The startup type for the Caching Service remains set to manual.


The AppFabric setup program sets configuration settings in the root (server level) Web.config file, the machine.config file, and the applicationHost.config file.
For information about configuration, see Configure Windows Server AppFabric. You can configure AppFabric either immediately after installation, or in a separate process.


To open the installation wizard


1. Open the installation wizard for initial installation by downloading and running the appropriate setup program from Windows Server AppFabric (http://go.microsoft.com/fwlink/?LinkID=183123), as shown in the following table. 


These programs all run a Microsoft Update package to install AppFabric features, which are features of Windows.

Platform
Setup package
Windows Vista and Windows Server 2008 x64
WindowsServerAppFabricSetup_x64_6.0.exe
Windows 7 and Windows Server 2008 R2 x64
WindowsServerAppFabricSetup_x64_6.1.exe
Windows Vista and Windows Server 2008 x86
WindowsServerAppFabricSetup_x86_6.0.exe
Windows 7 x86
WindowsServerAppFabricSetup_x86_6.1.exe

2. Proceed to the next section of this topic to install AppFabric


To install AppFabric

1. On the Accept License Terms page, read the license terms, and then accept the terms and click Next to continue, or do not accept the terms and then exit the setup wizard.

2. On the Customer Experience Improvement Program page, select Yes to participate in the Customer Experience Improvement program, or No not to participate, and then click Next. Click the Yes, download and install critical updates. button to install the latest critical updates for Windows Server AppFabric as part of the AppFabric setup experience.

3. On the Feature Selection page, select Hosting Services, Caching Services, Cache Client, Hosting Administration and Cache Administration components then click Next.

4. On the Platform Validation page, review the information and download any necessary prerequisite software. Click the link for a component or a configuration issue for more information. After installing components and/or resolving issues, click Refresh to verify that the problem has been fixed and then click Next to continue with the setup wizard. For more information, see Preparing Your Computer for Installation.

5. The Confirm Installation Selections page will display a list of the features that were selected in the Feature Selection page, and will be installed. It displays a list of the required Windows components and the AppFabric features that will be installed. Verify that the lists are correct, and then click Install to begin installation.

Note 

The Application Server role is required for AppFabric. This role will be included in the list of the required Windows components even if it is already installed, and the installation wizard will verify that it has been installed.

6. On the Installation Progress page, you can monitor the progress of the installation.

7. On the Installation Results page, verify that the installation has succeeded. 

To display a list of recommended updates that you can install, click the Recommended Updates link. To run the configuration wizard, select the Launch configuration tool check box, and then click Finish to complete the installation wizard. Click Detailed Installation report to display a log of setup events.


Start Configuration of Windows Server AppFabric

1. Open the AppFabric Configuration Wizard after performing the AppFabric Setup Wizard by selecting the Launch     configuration tool check box on the Installation Results page of the setup wizard, and then clicking Finish to  complete the setup wizard.

2. You can also open the configuration wizard by clicking Start, clicking All Programs, clicking Windows Server AppFabric, and then clicking Configure AppFabric.

3. On the Before You Begin page, select Yes to participate in the Customer Experience Improvement program, or No not to participate, and then click Next. The Configure Hosting Services page will be displayed. Proceed to the next section of this topic. 

Configure Monitoring

On the Configure Hosting Services page, use the tables below to configure monitoring, and then click Next.

Note 

If Hosting Administration is installed, but Hosting Services is not installed, then the services for the AppFabric Event Collection service and the Workflow Management service are not installed, and the text boxes for the identities of the services will display “Service not installed”.


Control
Description
Set monitoring configuration
Select to select the Event Collection service account, and to select and configure the monitoring store.
AppFabric Event Collection service account
Displays the Windows logon account for the Event Collection service. By default, the Event Collection service account is used for the monitoring provider. The Event Collection service account is a member of the Administrators group, and has administrative access to the monitoring database. The default is NT Authority\LocalService.
Change
If you click Change for the Event Collection service account, you will be able to select the user credential for system services. You can select a built-in account or enter a custom user name and password. In the Select User dialog box, select the account that you want to use for the service, and then click OK. Doing so will update the identity (if it was changed) and restart the service.
For more information, see the section Security Model for Windows Server AppFabric in (http://go.microsoft.com/fwlink/?LinkId=193179).
Monitoring provider
Select the provider that will give access to the monitoring database. All valid data providers registered in the local machine.config file will be displayed in this list.
Configure
After selecting the monitoring provider, click to set the configuration for the monitoring provider. For more information about configuring the SQL monitoring provider, see the discussion of the Configure SQL Monitoring Store dialog box below. You can also select a custom monitoring provider.
How to install additional Monitoring providers
You can add a monitoring provider to the list of providers that you can select in the Monitoring provider drop-down box. Click this link to get help on how to add a provider.

If you clicked Configure for the SQL monitoring provider (System.Data.SqlClient) on the Configure Hosting Services page, the Configure SQL Monitoring Store dialog box will be displayed. The following table describes the controls in this dialog box. Use this table to configure the monitoring store, and then click OK to return to the Configure Hosting Services page. Verify that the store was initialized and registered successfully

Control
Description
Register AppFabric monitoring store in root web.config
Select to register the monitoring store identified by the connection string, by adding its configuration to the root Web.config file. This includes the ApplicationServerMonitoringConnectionString and its related monitoring behavior. This registration makes the connection string and behavior available at all scopes on the computer.
You can select this check box even if Initialize monitoring store is not selected. Do so if the “AppFabricMonitoringStore” database is already created and initialized, or to point to the database even if it is not initialized.
Note
This check box is disabled if the Hosting Administration tools are installed, but the Hosting Services feature is not installed.
Initialize monitoring store
Select to initialize the monitoring database “AppFabricMonitoringStore” identified in the connection string, as required before it can be used. Initialization creates the “AppFabricMonitoringStore” database schema and the structure based upon that schema. If the database does not exist, it will be created, and then initialized.
If this check box is selected, but Register AppFabric monitoring store in root web.config is not selected, then the database will be created, if necessary, and initialized, but it will not be available for use from this computer.
The initializing operation is performed by the initialization cmdlets. For more information, see the Windows Server AppFabric help (http://go.microsoft.com/fwlink/?LinkId=164929).
Note
For the database to be created, you must have permissions to create databases on the destination server.
Connection string
String specifying the server and database used to access the monitoring store.
In the Server field, enter the name of the computer that the database is on.
In the Database field, enter the name of the database to be created for monitoring data, or select an existing database from the list.
Security Configuration
Select Windows authentication or SQL Server authentication.
For Windows authentication, to change the administrators, readers, or writers’ role, click Browse and use the standard Select User or Group dialog box to enter a different value. You can change the value for administrators, readers, or writers only if Initialize monitoring store is selected.
Note
When you have installed only Hosting Administration, and you are initializing the monitoring SQL store with Windows authentication, no group or user is entered by default for the Administrators, Readers, or Users role. You will need to click Browse and enter a group or user manually for each role before proceeding with the configuration.

After setting the monitoring configuration, proceed to the next section of this topic if you want to set persistence configuration. Otherwise, click Next to display the Configure Caching Service page, and proceed to the “Configure Caching Service” section of this topic.


Configure Caching Service


On the Configure Caching Service page, use the tables below to configure the Caching Service, and then click Next. A pop-up message will be displayed indicating that this action will apply the Caching Service configuration. To continue, click Yes. When you do so, the configuration settings will be made in the Caching Service configuration file. The Configure Cache Node page will then be displayed.


Note 


This page will be displayed only if you selected at least one of the Caching Services features on the Feature Selection page of the installation wizard (Caching Service, Cache Client, or Cache Administration).



Control
Description
Set Caching Service configuration
Select to add or update system-level configuration of the Caching Service feature.
Caching Service account
Displays the Windows logon account for the Caching Service. By default, the Caching Service account is used for the Caching Service configuration provider. The default is NT AUTHORITY\NETWORK SERVICE.
Change this account from NT Authority \NETWORK SERVICE to NT Authority\LocalSystem.
If your computer is part of a workgroup, you must change the Caching Service account. Use a local account that exists on all computers participating in the cluster and use the same password for the account on all computers. For configuration, the local account must have local administrator privileges, and must not be a built-in account. This step is not necessary for domain-joined machines.
Change
Click to display the Select User dialog box that you use to select an account for the Caching Service account.
For more information, see the section Security Model for Windows Server AppFabric in
 (http://go.microsoft.com/fwlink/?LinkId=193179).
Caching Service configuration provider
When specifying the Caching Service configuration provider, there are two options available:
a.   XML – Caching Service configuration information is stored in an XML file on a network file share.
b.   SQL Server Distributed Cache Configuration Store Provider – Caching Service configuration information is stored in a SQL Server database.
Warning
If XML is selected and the network discovery property is turned off, and you click Browse to select a file share for the XML provider, you will not be able to expand the Network folder in the Browse for Folder dialog box. You can, however, type in a UNC server share. To be able to expand the Network folder, you need to turn network discovery on by opening Control Panel, selecting Network and Internet, selecting Network and Sharing Center, selecting Change Advanced sharing settings, clicking Turn on network discovery, and then clicking Save changes.
Note
In workgroup scenarios, only the XML provider is supported, not database providers.
Configure
If you chose SQL Server AppFabric Caching Service Configuration Store Provider as the configuration provider, click Configure to create or select a Caching Service configuration database.
File Share
If you chose XML Provider as the configuration provider, enter or browse to the network file share that will contain the XML configuration file. The file share must be a valid UNC path, for example, \\server\share.
Important
You must manually create a network file share that is accessible to all cache servers in the cache cluster. The user account that is running the AppFabric configuration wizard must have “Owner” or “Co-Owner” permissions to the specified network file share and “Full Control” permissions to the folder at the file system level.
The Caching Service must have Read/Write access to the network file share.
Browse
If you click Browse for the File share, you will be able to use the Browse for Folder dialog box to select the file share for the XML configuration provider. Select an existing folder or create a new folder, and then click OK.
New cluster/Join cluster
Select New Cluster if this is the first computer in the cluster. When you run Setup on subsequent computers in the cluster, select Join Cluster. The default is New Cluster.
To create or join a cluster, you need to specify the location of the configuration data (either in a database or an XML file), and then on the next page (the Configure AppFabric Cache Node page) enter the ports, and set the firewall settings to unblock the services listed.
When creating a cluster, you need to indicate the cluster size (the number of computers in the cluster). This enables the system to optimize memory allocation.
Cluster size
Select one of the following three options to optimize performance based on cluster size. This setting is available only if the New Cluster control is selected.
·         Small [1-5 computers]
·         Medium [6-15 computers]
·         Large [> 15 computers]
Note
After this selection has been set, it cannot be changed.
Note
Your cluster size is not limited by this selection. You can still add or remove computers from the cluster after optimization. However, performance will only be optimized when the cluster size is within the range specified. Select a cluster size based upon the eventual number of nodes that will be in the cluster. After you set the cluster size during configuration, you cannot change it later. If you select Small for the cluster size, the cluster will be optimized for one to five computers. If your cluster eventually grows to ten computers, the cluster will still be optimized for one to five computers. You cannot subsequently change the cluster size to Medium, in order to optimize the cluster for 6 to 15 computers.



If you selected SQL Server AppFabric Caching Service Configuration Store Provider in the Caching Service configuration provider drop-down list and click Configure, the Windows Server AppFabric Caching Configuration Store dialog box will be displayed. Use the tables below to configure the SQL store, and then click Next.


Note 


When you click OK in the Windows Server AppFabric Caching Configuration Store dialog box, the distributed cache database will be created, and a pop-up message with the results of the operation will be displayed.


Note 


Security configuration settings do not need to be made on this page because Windows authentication is required. Caching does not support SQL authentication.


Control
Description
Register AppFabric Caching Service configuration database
Select “AppFabricCachingStore” to register the configuration database identified by the connection string, by adding its configuration to the root Web.config file, and to set the security configuration. This registration makes the connection string and behavior available at all scopes on the computer. You can select this check box even if Create AppFabric Caching Service configuration database is not selected. Do so if the database is already created.
Create AppFabric Caching Service configuration database
Select to create the configuration database and to specify the connection string. Give a database name as “AppFabricCachingStore”.
Connection String
Enter the server in the Server field and select or type the database in the Database field.



When you click Next with the Configure Caching Service page displayed, the Configure AppFabric Cache Node page will be displayed. Use the tables below to configure the cache node ports and Windows firewall.


Note 
This page will be displayed only if you selected at least one of the Caching Services features on the Feature Selection page. You can set the firewall exceptions only if the Windows Firewall service is enabled.


Note 
If the Windows Firewall is disabled, the Windows firewall exceptions area of the Configure AppFabric Cache Node dialog box will be disabled.


Control
Description
Node ports
Enter or select a unique value for each port, or leave the default settings.
·         Service port. The default is 22233.
·         Cluster port. The default is 22234.
·         Arbitrator port. The default is 22235.
·         Replication port. The default is 22236.
The valid range for port values is 1024 through 65535. Each port must have a unique port number.
Windows firewall exceptions
For the AppFabric Distributed Cache features to function, you must configure the Windows Firewall rules to allow access for the Cache Service.
a.   Windows Server AppFabric: AppFabric Caching Service
b.   Remote Service Management
Important
If you are using a third party (non-Windows) firewall, or a Windows Firewall that is subject to domain policy, you must manually configure the firewall for the caching features to work properly.

Note 
After you click Next on the Configure AppFabric Cache Node page, the Configure Application page will      be displayed if the AppFabric hosting features are installed.



Complete Configuration of Windows Server AppFabric
On the Configure Application page, select Start Internet Information Services (IIS) Manager to configure an application in the IIS Manager. Click Finish to close the configuration wizard.


Note 
After the AppFabric Configuration Wizard has successfully configured the Caching Service, you will need to use administration cmdlets to start the cluster or start individual hosts in the cluster. Use the Start-CacheCluster or Start-CacheHost cmdlet. For more information about these cmdlets, see Cache Administration with Windows PowerShell (http://go.microsoft.com/fwlink/?LinkId=193181).

Start Cache Host Services for the First Time

After installation for the first time, you will need to start the cache cluster. Configure at least one node in the cluster, and then execute a cmdlet to start the cluster. 
In the developer scenario (using a single-node cluster), to start a new cluster execute Use-CacheCluster (to set the context of your Windows PowerShell session to a particular cache cluster) and then execute Start-CacheCluster.

In a multiple-node cluster, to start all cache host services in the cluster (lead hosts first), execute Start-CacheCluster. For additional cache hosts (and any other cluster-level configuration changes) to be acknowledged by the cache cluster, you need to restart all cache host services with Restart-CacheCluster. To start a specific cache host service, execute Start-CacheHost.
 
For more information, see Cache Administration with Windows PowerShell (http://go.microsoft.com/fwlink/?LinkId=193181).

Create AppFabric Cache

To create the AppFabric Cache follow the below steps:

a.  Open the Power Shell by clicking Start, clicking All Programs, clicking Windows Server AppFabric,  and then clicking Caching Administration Windows PowerShell. 

b. Run the following command to create the cache.

c. get-command -module DistributedCacheAdministration

d. Start-CacheCluster

e. New-Cache -CacheName [CacheName]–Expirable false

f. Restart-CacheCluster

g. Get-CacheStatistics  [CacheName]

h. Get-Cache 

Host a Services in AppFabric and Configure the IIS with AppFabric

To configure the IIS with AppFabric follow the below steps:

1. Open the IIS Manager to configure  the AppFabric

2. Right click on Default Web Site, click on Manage WCF and WF Services and then Select Configure as shown in Figure 9.1.1.


    Figure 9.1.1
    1. Now Click on Monitoring from Configure WCF and WF for Site Window as shown below in Figure 9.1.2.

    Figure 9.1.2
    1. Check the Check box “Write events to database”, Select the appropriate Connection string for AppFabric Monitoring database, set the Level to “End to End Monitoring” and then click on Apply button as shown in Figure 9.1.3.

    Figure. 9.1.3.
    1. Finally, click on Ok button to close the windows.
    Now, your IIS is configured with the AppFabric Monitoring.


    To configure the service with AppFabric follow the below steps:

    1. Open the IIS Manager to configure  the AppFabric
    2. Right click on Discovery, click on Manage WCF and WF Services and then Select Configure as shown in Figure 9.2.1.

    Figure. 9.2.1

    1. Now Click on Monitoring from Configure WCF and WF for Site Window as shown in Figure 9.2.2.

    Figure. 9.2.2

    1. Check the Check box “Write events to database”, Select the appropriate Connection string for AppFabric Monitoring database, set the Level to “End to End Monitoring” and then click on Apply button as shown in Figure 9.2.3.
                                       
    Figure. 9.2.3

    1. Now select Auto-Start tab to enable the Auto-Start option as shown in Figure 9.2.4.

    Figure. 9.2.4

    1. Finally, click on Ok button to close the windows.

    Note: Repeat the same steps mentioned in section 9.2 for all the other Service to configure the AppFabric Monitoring.