Wednesday, 10 April 2013

Use the Per­Call or PerS­es­sion instance con­text mode

Use the Per­Call or PerS­es­sion instance con­text mode

The Instance­Con­textMode also plays a sig­nif­i­cant role in the over­all per­for­mance of your ser­vice, and of the three options avail­able to you – Per­Call, PerS­es­sion and Sin­gle­ton – you should con­sider Per­Call or PerS­es­sion for a highly scal­able WCF service.
Whilst the Per­Call instance con­text mode is gen­er­ally regarded as the most scal­able option it does carry with it the need to cre­ate a instance of your class for each request and you need to ensure that 1) you have a para­me­ter­less con­struc­tor, and 2) this con­struc­tor should do as lit­tle as pos­si­ble. If there are any sig­nif­i­cant steps that need to be per­formed, such as load­ing some ref­er­ence data, you should avoid doing these in the para­me­ter­less con­struc­tor so they aren’t per­formed for each request:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{
    public MyService()
    {
        ReferenceData = LoadReferenceData(); // will be called for EACH request…
    }
    public MyReferenceData ReferenceData { get; private set; }
    …
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService2 : IMyService
{
    // called the first time the reference data is used and shared across all instances
    private static MyReferenceData ReferenceData = LoadReferenceData();
    public MyService2()
    {
        // ideal constructor which does nothing
    }
    …
}
In cases where the ini­tial­iza­tion steps are lengthy and unavoid­able, or your class require a num­ber of para­me­ters in the con­struc­tor (for instance, when you pro­gram­mat­i­cally host a ser­vice retrieve from an IoC con­tainer) the para­me­ter­less con­struc­tor can become a prob­lem. To get around this, you could cre­ate a wrap­per for your class and expose the wrap­per as the ser­vice instead but hold a sta­tic instance of the under­ly­ing ser­vice which all the requests are passed on to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyServiceWrapper : IMyServiceWrapper
{
    // get the underlying service from the container
    private static IMyService MyService = _container.Resolve<IMyService>();
    public MyServiceWrapper()
    {
        // parameterless constructor which does nothing, so easy to constructor
    }
    public void DoSomething()
    {
        MyService.DoSomething();
    }
}
// dummy interface to ensure the wrapper has the same methods as the underlying service
// but helps to avoid confusion
public interface IMyServiceWrapper : IMyService
{
}
For a ses­sion­ful ser­vice, the PerS­es­sion instance con­text mode gives you all the ben­e­fit of the Per­Call instance con­text mode and at the same time reduces the over­head you pay for that extra con­cur­rency because new instances of your class are no longer cre­ated for each request but for each ses­sion instead.
If your ser­vice is ses­sion depen­dant then you should def­i­nitely go with PerS­es­sion, but beware, if the chan­nel does not cre­ate a ses­sion your ser­vice will behave as if it was a Per­Call service.

Increase the num­ber of idle IO threads in the thread pool

Per­haps the most over­looked aspect when it comes to increas­ing con­cur­rency of a WCF ser­vice. If you’ve set your ser­vice to use Per­Call or PerS­es­sion instance con­text mode and upped the throt­tling set­tings, but are still not get­ting the response times you’re look­ing for, then it’s worth inves­ti­gat­ing whether the calls are being queued because there is not enough IO threads in the Thread­Pool to han­dle the requests.
You can estab­lish whether or not the requests are actu­ally tak­ing longer to process under load (as opposed to being queued at a ser­vice level) either by pro­fil­ing locally or using some form of run-time log­ging (I wrote a LogEx­e­cu­tion­Time attribute which might come in handy). If the calls aren’t tak­ing longer to process and you’re not see­ing very high CPU util­i­sa­tion then the increase in response time is likely a result of the request being queued whilst WCF waits for a new IO thread to be made avail­able to han­dle the request.
WCF uses the IO threads from the Thread­Pool to han­dle requests and by default, the Thread­Pool keeps one IO thread around for each CPU. So on a sin­gle core machine that means you only have ONE avail­able IO thread to start with, and when more IO threads are needed they’re cre­ated by the Thread­Pool with a delay:
“The thread pool main­tains a min­i­mum num­ber of idle threads. For worker threads, the default value of this min­i­mum is the num­ber of proces­sors. The Get­MinThreads method obtains the min­i­mum num­bers of idle worker and I/O com­ple­tion threads.
When all thread pool threads have been assigned to tasks, the thread pool does not imme­di­ately begin cre­at­ing new idle threads. To avoid unnec­es­sar­ily allo­cat­ing stack space for threads, it cre­ates new idle threads at inter­vals. The inter­val is cur­rently half a sec­ond, although it could change in future ver­sions of the .NET Framework.
If an appli­ca­tion is sub­ject to bursts of activ­ity in which large num­bers of thread pool tasks are queued, use the Set­MinThreads method to increase the min­i­mum num­ber of idle threads. Oth­er­wise, the built-in delay in cre­at­ing new idle threads could cause a bottleneck.”
How­ever, as Wen­Long Dong pointed out in his blog (see ref­er­ences sec­tion), rais­ing the Min­IO­Threads set­ting in the Thread­Pool doesn’t work as you’d expect in .Net 3.5 because of a known issue with the Thread­Pool which has since been fixed in .Net 4. So if you’re still run­ning .Net 3.5 like most of us, then you will need to go and grab the hot­fix from here:
http://support.microsoft.com/kb/976898

Part­ing thoughts:

Per­for­mance tun­ing isn’t an exact sci­ence, and you have to make a case by case judge­ment on how best to approach your per­for­mance issues. Encour­ag­ing greater con­cur­rency is just one of the ways you can improve per­for­mance, but it’s by no means a sil­ver bul­let! In fact, if you go too far down the con­cur­rency route you could find your­self fac­ing a num­ber of problems:
  • 100% CPU – exces­sive num­ber of con­cur­rent threads can max out your CPU and a lot of CPU time can be wasted on con­text switch­ing whilst your ser­vice becomes less responsive.
  • DOS attack – same as above, but intended by a would be attacker.
  • Out­OfMem­o­ryEx­cep­tion – if your ser­vice is return­ing a large set of data from database/committing large amount of data­base writes within a trans­ac­tion, it’s not unthink­able that you might run into the dreaded Out­OfMem­o­ryEx­cep­tion given that: 1) in prac­tice you only have a per process cap of around 1.2 ~ 1.5GB of mem­ory and each active thread is allo­cated a 1MB of mem­ory space (regard­less of how much it actu­ally uses); 2) each con­cur­rent call per­forms large num­ber of object cre­ations which takes up avail­able mem­ory space until they’re garbage col­lected 3) writ­ing to the Data­base within a trans­ac­tion adds to the trans­ac­tion log which also eats into the avail­able memory.

Ref­er­ences:

Wen­Long Dong’s post on WCF responses being slow and Set­MinThreads does not work
Wen­Long Dong’s post on WCF request throt­tling and Server Scalability
Wen­Long Dong’s post on WCF becom­ing slow after being idle for 15 seconds
Scott Weinstein’s post on cre­at­ing high per­for­mance WCF services
Dan Rigsby’s post on throt­tling WCF ser­vice and main­tain­ing scalability

WCF Service Performance, is it all about calls per second?

Non-Functional Requirements - Performance

Of all the non-functional or technical requirements, performance is the one that seems to get the most attention. I personally know developers who will spend hours and hundreds of dollars of their customers money in trying to shave milliseconds off a routine in a WCF Service.
In this hub I will dispel some of the common myths surrounding performance using the WCF (Windows Communication Foundation) platform, and provide some metrics I have captured for the WCF services in live production systems. I remember starting out using WCF and not being able to find a single resource that would give me any actual real data to compare my benchmarks against.
I am now into my third major implementation using the WCF service stack, by that I mean big projects at enterprise clients with many interdependent services. The production environments are real, load balanced and representative.
The model I use to build service orientated software utilizes the Manager, Gateway, Engine pattern (GME), thus the metrics are affected by a combination of technology and pattern.

Manager, Gateway, Engine Pattern

 

Manager, Gateway, Engine Pattern 

 

What is Performance?

Performance is an indication of the responsiveness of a system to execute any action within a given interval of time.
The performance of any software is  dependent on many factors, most of which have nothing to do with the framework and technology used to build it. Even the most performant software can still have a method that causes an endless loop or a “live lock” that causes a client to wait.A poor server or network could also be the cause of a loss of performance.

The issue then is to ensure that neither the model nor the technology is the cause
of any unacceptable loss of performance.

Technology - WCF, Model - GME

The technology in this instance is WCF, the model advocates that every class is a service in order to leverage the built in plumbing that comes with WCF, but one often hears the question, what about performance?

This is the wrong question to ask, as in reality nobody except developers even cares about performance as long as performance is adequate.
So the actual question is, is the performance adequate? So let’s weigh it all up with all classes as WCF services we automatically benefit from:

WCF Benefits

 
1. Encrypted calls
2. Authentication
3. Identity propagation
4. Authorization
5. Security audit
6. Transactional propagation
7. Transactional voting
8. Calls timeout
9. Reliability
10. Tracing and logging
11. Profiling and instrumentation
12. Instance management
13. Durability
14. Error masking
15. Fault isolation
16. Channel faulting
17. Buffering and throttling
18. Data version tolerance
19. Synchronization
20. Remotability
21. Queuing
22. Relay
23. Discovery
 
WCF Benefits

So what about performance

So what about performance, WCF is not free, but it is adequate for most applications, most applications will never notice it. Raw WCF with a single client calling to a single service with no work in it on a laptop provides some 10,000 calls per second, raw C# offers some 300,000 calls per second.
To put the calls per second thing into perspective I would imagine that Amazon runs at about 150 calls per second.
But raw WCF offers no value, in a real system with every aspect of WCF enabled, WCF can manage 100 calls per second on a laptop; in contrast, a C# application with all the equivalent aspects created as bespoke code and enabled manages a maximum of 10 calls per second.
Strange you may think, what has happened?
The WCF aspects underwent years of rigorous testing by some of the most devious minds in the industry and has been optimized and performance tweaked.

So if you care about performance you have  to use WCF as all  its aspects have been performance tested  against hundreds of different scenarios and perform better than the components you have written and only tested against the one or two scenarios that you knew about. 

Cost of WCF

There is a cost to using every WCF  aspect;  every aspect will cause a certain degradation in performance, this is summed in the table below.

Cost of WCF Aspects

ASPECT
COST (%)
Encoding
0
Process Boundry
0
Authorization
0
Authentication
0
Instancing mode
0
Reliability
10
Performance counters
25
Transactions
66
Message Protection
85
Logging and Tracing
95
source: J Lowy

Security is not an option

I don`t know about you, but in my world security is not an option, also service guidelines tell us that services should be secure, so if message protection is mandatory, then you have security enabled and you should then also enable everything else as it will not affect your performance as you have already taken the hit for security.
Only logging and tracing becomes optional, and that can always be turned on and off via configuration files if you need it.

The Metrics

So without boring you, in my tests, with every aspect of WCF turned on in a production environment, calling from a test harness with multiple calls on multiple threads, I typically get the following:
For transactional calls (insert, update, delete) with real business logic behind it, between 25 -40 calls per second.
For select type calls (no transaction) it hovers around 90 - 120 calls per second.
If did did some work on optimizing the code and utilizing all the cores of the server by going parallel where it made sense to do so, I could get more, but who has time for that, this is adequte.
I think of scaling in terms of virtual server instances, so if I want more, I just add another node to the load balancer and get another instance up.

 

 

Tuesday, 9 April 2013

Improving WCF Service Performance

This article is from MSDN. i was surprised after reading it.hope u too r surprised after reading


WCF services expose numerous configuration parameters that affect performance. This topic provides general guidance for setting optimal values for these configuration parameters to improve performance of WCF services.
Implement serviceThrottling behavior for backend WCF services. Service throttling allows you to even out the load on your backend WCF servers and to enforce resource allocation. serviceThrottling behavior for backend WCF services is configured by modifying the values for the maxConcurrentCalls, maxConcurrentSessions, and maxConcurrentInstances parameters in the config file for the WCF service. Set maxConcurrentCalls, maxConcurrentSessions, and maxConcurrentInstances to a value greater than 16 * the number of CPUs or CPU cores. For example, on a computer with 8 CPU cores, set maxConcurrentCalls, maxConcurrentSessions, and maxConcurrentInstances to a value greater than 128 (16 * 8 = 128) as follows:
<serviceThrottling
maxConcurrentCalls="200"
maxConcurrentSessions="200"
maxConcurrentInstances="200" />
The NetTcpBinding.ListenBacklog property controls the maximum number of queued connection requests that can be pending for a Web service. The NetTcpBinding.MaxConnections property controls the maximum number of connections to be pooled for subsequent reuse on the client and the maximum number of connections allowed to be pending dispatch on the server. Each of these properties uses a default value of 10 which may be suboptimal, especially for document processing scenarios that require high throughput.
Consider increasing the default value of these properties for high-throughput, document-processing scenarios that use WCF services which implement the netTcpBinding binding class.
In the following example, both the listenBacklog and maxConnections parameters are set to a value of “200”.
<netTcpBinding>
   <binding name="netTcpBinding"
      closeTimeout="00:10:00"
      openTimeout="00:10:00"
      receiveTimeout="00:10:00"
      sendTimeout="00:10:00"
      transactionFlow="false"
      transferMode="Buffered"
      transactionProtocol="OleTransactions"
      hostNameComparisonMode="StrongWildcard"
      listenBacklog="200"
      maxBufferPoolSize="1048576"
      maxBufferSize="10485760"
      maxConnections="200"
      maxReceivedMessageSize="10485760">
      <readerQuotas
         maxDepth="32"
         maxStringContentLength="8192"
         maxArrayLength="16384"
         maxBytesPerRead="4096"
         maxNameTableCharCount="16384" />
      <reliableSession
         ordered="true"
         inactivityTimeout="00:10:00"
         enabled="false" />
      <security mode="None">
         <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
         <message clientCredentialType="Windows" />
      </security>
   </binding>
</netTcpBinding>
For more information about the NetTcpBinding.ListenBacklog property, see NetTcpBinding.ListenBacklog Property (http://go.microsoft.com/fwlink/?LinkId=157752) on MSDN.
For more information about the NetTcpBinding.MaxConnections property, see NetTcpBinding.MaxConnections Property (http://go.microsoft.com/fwlink/?LinkID=157751) on MSDN.
By default, several ASP.NET httpModules are defined in the Request Pipeline in IIS 6.0 and in the Classic or Integrated Pipeline in IIS 7.0. These components intercept and process all incoming requests. The default modules are defined in the web.config file contained in the %windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG folder for 32-bit ASP.NET applications and in the %windir%\Microsoft.NET\Framework64\v2.0.50727\CONFIG folder for 64-bit ASP.NET applications, as shown by the following snippet.
<httpModules>
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule"/>
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
<add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/>
<add name="RoleManager" type="System.Web.Security.RoleManagerModule"/>
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/>
<add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/>
<add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/>
<add name="Profile" type="System.Web.Profile.ProfileModule"/>
<add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</httpModules>
In most scenarios it is not necessary to load all of these modules. Therefore, it is possible to improve performance by eliminating the following httpModules when running WCF Web services:
  • Session
  • WindowsAuthentication
  • FormsAuthentication
  • PassportAuthentication
  • RoleManager
  • AnonymousIdentification
  • Profile
The WCF Module/Handler Registration Tool is available for download at http://go.microsoft.com/fwlink/?LinkId=157593 (http://go.microsoft.com/fwlink/?LinkId=157593). This utility can be used to install, list, or configure the following WCF modules:
  • WCF Synchronous HTTP module and handler
  • WCF Asynchronous HTTP module and handler
  • WCF HTTP module and handler
For more information about using the asynchronous WCF HTTP modules/handlers to improve the scalability of IIS 7.0 hosted WCF services, see Wenlong Dong’s blog Orcas SP1 Improvement: Asynchronous WCF HTTP Module/Handler for IIS7 for Better Server Scalability (http://go.microsoft.com/fwlink/?LinkId=157428).

Concepts

Optimizing BizTalk Server WCF Adapter Performance

Thursday, 21 March 2013

Designing a new DataBase

hi ,
everyone i am developer , recently i started working on a new database design. i was getting a lot of suggestion from varios blogs .

so i decided to list them down :

When you start your database design the first thing to analyze is the nature of the application you are designing for, is it Transactional or Analytical. You will find many developers by default applying normalization rules without thinking about the nature of the application and then later getting into performance and customization issues. As said, there are two kinds of applications: transaction based and analytical based, let’s understand what these types are.
Transactional: In this kind of application, your end user is more interested in CRUD, i.e., creating, reading, updating, and deleting records. The official name for such a kind of database is OLTP.
Analytical: In these kinds of applications your end user is more interested in analysis, reporting, forecasting, etc. These kinds of databases have a less number of inserts and updates. The main intention here is to fetch and analyze data as fast as possible. The official name for such a kind of database is OLAP.
In other words if you think inserts, updates, and deletes are more prominent then go for a normalized table design, else create a flat denormalized database structure.
Below is a simple diagram which shows how the names and address in the left hand side are a simple normalized table and by applying a denormalized structure how we have created a flat table structure.

Rule 2: Break your data into logical pieces, make life simpler

This rule is actually the first rule from 1st normal form. One of the signs of violation of this rule is if your queries are using too many string parsing functions like substring, charindex, etc., then probably this rule needs to be applied.
For instance you can see the below table which has student names; if you ever want to query student names having “Koirala” and not “Harisingh”, you can imagine what kind of a query you will end up with.
So the better approach would be to break this field into further logical pieces so that we can write clean and optimal queries.
 


Wednesday, 20 March 2013

SharePoint Basics

SharePoint is a browser based web application developed by Microsoft that enables users within an organization to work together, collaborate, more efficiently through its vast number of features.


Some of the features include the followin. Document Management, Web Content Management, Business Process Management (Workflows), Enterprise Search, Business Intelligence (Dashboards, Reports), Electronic Forms (InfoPath), Social Networking





SharePoint History:



SharePoint (2010) Versions Available
1.  SharePoint Foundation (Free version, known as WSS in  2007. Mainly Provides Document Management)
2.      SharePoint Standard Edition
3.      SharePoint Enterprise Edition
Click the below link for more details of the SharePoint Versions



WSS stands for Windows SharePoint Services. It is a core framework on which MOSS works. WSS features are: Wiki, Blogs site, Document management, Server Farm.


MOSS stands for Microsoft Office SharePoint Server. It is the part of SharePoint which gives more functionality with WSS. MOSS features are:
Mysite, Search Services, Audience Targeting, Excel Services, Form Services.

A library is a component in SharePoint that stores files (documents) and a list is a component in SharePoint that stores rows of information. In Library you can create core document like Word, Excel, and PowerPoint. But in List You cannot create document, instead of that you can attach document in a particular List.

Document Library contains core document such as, MS word, Excel, PowerPoint. But Form library contains document in XML form Such as InfoPath form.

List is a component in SharePoint that stores rows of information. List contains meta data to describe the particular row in more detail.

Sites available in SharePoint are Wiki Sites, Blogs Site, Meeting Sites, Team Sites, and Blank Sites etc.

Site Definitions are the foundations on which all sites and user templates are built. Site Definition is collection ox XML and .aspx file. Site Definitions are predefined components needs to be included when a site was created in SharePoint server.

Webparts are smallest component in SharePoint. Web parts are used to give more functionality to the page. In SharePoint we have custom web part as well as readymade 3rd party web part. You can create a custom web part by using visual studio.

Various web parts available in SharePoint web part gallery are: Data view web part, Content editor web part, Form web part, Excel web access web part, Image web part etc.


SharePoint object model hierarchy:
The Following is the order of the SharePoint Object Model .
  1. SPFarm
  2. SPSite
  3. SPWeb
  4. SPList
  5. SPListItem


·         Farm- is a collection of one or more SharePoint server which having a single configuration database. A farm will contain multiple web applications.
·         Web Application- is always created for Central Administration and at least one web application will be created for the SharePoint intranet, extranet or internet site. A web application is where you implement and maintain authentication.
·         Site Collection- Site collection is the collection of sites and workspaces which create a hierarchy
·         Sites-Site is the container of contents, contents are in the form of List and Library
·         Pages

User Permission levels:

 The following permission levels are assigned to users in SharePoint , they are...

Full Control: Persons have full control over the SharePoint site.
Design: Persons can read, modify, delete records and also modify their views
Contribute: Persons can read, modify, delete records. (This is widely used permission level)
Read: Persons can view the records.
Tools for SharePoint:

Sharepoint Designer

Visual Studio 

Silverlight/Microsoft expression blend



Pages Available are… 

 Site Pages: These are pages that supports user customization by designing tools e.g. SharePoint designer. Some site pages are default.aspx, default.master

Application Pages: Those pages which does not support user customization. These pages are found in virtual -layouts directory. Application pages can be used with any sites or site collection on same server.

You may find application pages at this location:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS

A content type is a reusable thing provided by WSS.  Content type defines the column for an item in a library or list and same can be used for any library or list in that SharePoint application.
For e.g. you are creating a list for leave application then if you are creating column for HR department, IT department then it does not makes any sense.

So used content type where you can create your own column or site column (Given by SharePoint) and you can use this content type with any list or library.

Business Data Catalogue: It is a middleware for your SharePoint site and back end data such as SAP, Siebel and any other Line of Business application.

In BDC you cannot modify data from your SharePoint list. It will be available to your site in read only.

In SharePoint 2010 it is named as BCS (Business Connectivity Services). BCS is two way, i.e. Data can be edit from SharePoint list as well from the back end data base.

Workspace is more specific to a site for e.g. you want to create annual report


CAML stands for Collaborative application markup languages. It is in xml form. And it can be sued to retrieve the data from SharePoint list as well to update and insert.

Stsadm command is used to perform all administrative work like backup, restore, installing feature, adding web part to site etc.

Using the STSADM tool the following commands can be done:

Backup command:
stsadm -o backup -url http://moss:1985/ -filename c:\mysite.bak

To restore:
Create one blank Site collection on same server with any port number e.g. 1986.
stsadm -o restore -url http://moss:1986/ -filename c:\mysite.bak