Monday, October 1, 2012

Best Practices For WCF

There are few the recommended best practices for WCF, what I found during to resolve the performance issue. Recently one my application (WCF based software) is going into production and client had more concerns and worries about the performance because, this application had to deal with bulk data like million records.

In initial phase of development, we have faced lots of design hurdles (due to n-tired approach with SOA) against the performance.

Since last few days I am working on the performance issue and has already done lots of goggling to improve the performance and finally I found few tips and best practices

  1. Avoid multiple service round trips to populate the screen data, Make single call to get all lookup data for screen instead of making each for each data driven control.
  2. If possible and data size allowed, Use the client side caching for static data (master data).
  3. Use the singleton proxy creation pattern or proxy caching approach to create the service proxy.- avoid to create service proxy for each client request.
  4. Implement the server side caching for static data or lookup data.
  5. Choose the proper wcf binding ( nettcp, webhttp, wshttp etcs)
  6. set the right value of the below service behavior Throttling properties to improve WCF performance 
    • maxConcurrentCalls - This specifies the maximum number of messages processed across the service host. The default value for this property is 16 (WCF 4.0 is improved to default is 16 * Processor Count).
    • maxConcurrentInstances - This specifies the maximum number of instances of a context object that executes at one time with the service. The default is Int32.MaxValue.
    • maxConcurrentSessions - This specifies the maximum number of sessions at one time within the service host object. The default value is 10 (WCF 4.0 increases that to 100 * Processor Count).
   <serviceBehaviors>
        <behavior>
         
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
         
          <serviceDebug includeExceptionDetailInFaults="false" />
          <dataContractSerializer maxItemsInObjectGraph="2147483646" />         

<serviceThrottling 

maxConcurrentCalls="16" maxConcurrentSessions="100" maxConcurrentInstances="10" /> 

          <serviceMetadata httpGetEnabled="true" />         
        </behavior>
      </serviceBehaviors>


Wcf Proxy Caching - 
To generate or dispose the wcf proxy, both are very expensive task and it consume good amount of resource and time. so avoid to this,we should use singleton pattern to create wcf proxy or cache proxy.

you will be get more details to visit on below link 
http://blogs.msdn.com/b/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx

Thanks for visiting !

Tips To Improve Entity framework Query Performance

In this blog, we will discuss about the few tips and techniques to improve the entity framework query performance

  • Object tracking turned off 
  • Turn off automatic DetectChanges
  • Avoid the Using block
  • Lazy Loading

1. Object tracking turned off :
when we loads entity in local memory; by deafult it tracks all changes of entity like entity property value changes or deletion of entity and this feature is only beneficial when you want to update the existing entity and but if you only want to read data and you dont want to update entity, then it will be additioanl overload and it will degrade the query performace.

AsNoTracking() function is very useful in writing of no tracking query and it executes very fast because there is no need to store any entity change information.

Example  :
   DbContext context = new DbContext()
   var projects = context.Projects
        .AsNoTracking()
        .ToList();


2. Turn off automatic DetectChanges :
if your application context is not making any entity update or its making bulk insert or update then you can turn off the autoDetectChanges but make sure it is happened only in try/cacth-finally scope

Example :
DbContext context = new DbContext()
context.Configuration.AutoDetectChangesEnabled = false;

3. Avoid the Using block  to create the instance of ObjectContext. :
it takes the lots of times to initialization of ObjectContext and during the initialization, it performs the several steps

  •  Initialize Context (needs to load schema/table metadata from resources)
  •  Validate context
  •  Open connection to DB
  •  Execute submitted SQL script 
  •  Clean up and close DB          
so if you are creating object of DbContext by using  'Using' block and if exection control go out scope of using block, it automatcally will dispose dbContext object.

using (var context = new DbContext())
{
      var projects = context.Projects
        .AsNoTracking()
        .ToList();
}

4. Lazy Loading :
use lazy loading feature and avoid the unnecessary object loading and more information @ Entity Framework - Eager Loading 

5.Examine queries sent to the Database - use ObjectQuery.ToTraceString() to get the raw SQL query what EF is sending to database or you can log sql statement and more information @ Entity Framework - Log SQL Statement 

Monday, May 14, 2012

Hosting WCF Service on IIS 7 with nettcp bindings

this blog will demonstrate how to host nettcpbing enabled wcf service on IIS and after IIS 7.0 releases, it allows to host the tcp binding enabled wcf service.

The nettcpbinding is based on TCP ( Transmission Commision Protocol), this protocal is very efficient in service to service communication and it supports the reliable message delivery and binary message encoding.
  1. Configure nettcpbinding endpoint 
  2. Configure IIS 7.0


Configuring nettcpbinding endpoint :
add the nettcpbinding endpoint in the WCF config file.

<system.serviceModel>
<services>
<service behaviorConfiguration="MyBehavior" name="Wcf_Tcp_Service.Service1">
<endpoint address=""  binding="netTcpBinding" bindingConfiguration="portSharingBinding"  name="MyServiceEndpoint" contract="Wcf_Tcp_Service.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexTcpBinding"name="MyServiceMexTcpBidingEndpoint" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:808/WCFNetTcp/Service1.svc" />
</baseAddresses>
</host>
</service>
</services>


the nettcpbnding endpoint is defined, which use nerTcpBinding and “portSharingBinding” bindingConfiguration which is defined as below :
<bindings>
<netTcpBinding>
<binding name="portSharingBinding" portSharingEnabled="true"/>
<binding name="mexTcp" portSharingEnabled="true">
   <security mode="None" />
</binding>
</netTcpBinding>
</bindings>


The portSharingEnabled Property control whether net.tcp:// port sharing is enabled for the service being configured with this binding.


Note: Port 808 in the end point base address would also be required while performing the configuration settings in IIS 7.0. If you wish to change the port here, remember to perform the same in IIS 7.0 as well.

Configuring IIS 7.0 - 


1.       Under the sites node right click the website you wish to create your WCF Service virtual directory, and select the “Add Application” option,  give your application an alias name and path where the service code resides.  In the Application pool select ASP.NET v4.0 as the application pool and click OK.

2.       Right click the website and select the Edit binding option, this opens up the site bindings dialog. Make sure net.tcp binding type is present with port as 808, if not, go ahead and add a net.tcp binding using the dialog Add button.

3.       Right click the virtual directory created in the first step, select Manage Application -> Advance Settings. In the Advance settings dialog update the Enabled protocols property to “http,net.tcp” and click OK.

4.       Go to the IIS root and select the Features view. In the features “IIS” panel, double click the “ISAPI and CGI Restrictions” feature. In the “ISAPI and CGI Restrictions” window that opens, right click on all the ASP.NET 4.0 entries and select “Allow”.

5.       Go to Windows -> run and type services.msc to open the services control panel. Find the services with the name “Net.Tcp Port Sharing Service” and “Net.Tcp Listener Adapter” and start them.

6.       Add reference of your WCF service to your client application and check whether proxy classes are getting created, if yes, we are done.

Note: If you are unable to find an Application pool with the name ASP.NET v4.0 go ahead and create one. Under IIS root, right click Application Pool node and select “Add Application Pool”. In the dialog give name of the pool as “ASP.NET v4.0”, select .NET Framework 4.0 and click OK.

Troubleshooting


1.       Windows firewall on the service hosting box is not blocking the TCP port/communication.

2.       To find whether the configured port is available or not, open cmd and type “netstat –a” to find the active ports.

>

Wednesday, February 29, 2012

Bad Request Error 400 - WCF Client

I have encountered the Bad Request Error  400  in WCF client and  i have analyzed this issue and found that main cause of this error is the BIG SIZE of request and it exceeded the default wcf request max limit .
>
To resolve this issue , you have to make following changes in WCF config file (in both config file client and server )  and increase  MaxBufferPoolSize, MaxReceivedMessageSize to allow huge contents


 
<basicHttpBinding>
    <binding maxBufferSize="64000000" maxReceivedMessageSize="64000000" maxBufferPoolSize="64000000"

      <readerQuotas maxDepth="64000000" maxStringContentLength="64000000" maxArrayLength="64000000" maxBytesPerRead="64000000" />

      <security mode="None"/>
    </binding>

  </basicHttpBinding>


Note : we can increase the maximum request size to 50MB  for ASP.NET Runtime (IIS)


> Thanks for visiting !!

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...