Wednesday, 8 May 2019

How to implement session in WCF

Introduction

Session is a well understood term for all of us and as per our common understanding, it is (well, less or more) some duration in which entities recognize each other. Some of us might have played with it in ASP.NET as well. The concept is almost similar in WCF although the technique and usage are a bit different.
In WCF, there is always a service class instance that handles incoming service requests. These instances may already be there (at server when request arrives) or may be created as needed. In WCF, the concept of session is mainly to manage these service instances so that server can be utilized in an optimized way. At the server, there is one special class named InstanceContext that creates/loads service class instance and dispatches requests to it. The correlation can be perceived as:
Sessions_in_WCF/ServiceObjects.JPG
You can see here how stuff is engaged. When some request arrives, it is routed to service instance via instance context. Suppose there is a hit of thousand requests, then service will have to create thousand instance contexts (which in turn will create thousand service instances) to handle these requests. If requests are served in this way, then service is called PERCALL service as each request is served by a new instance context and service instance object (call them as service objects onwards). Consider there is a client that made 100 requests. If service identifies this client and always serves it by a dedicated service object, then this type of service will be known as PERSESSION service as it recognizes the client and serves it by a single instance of service object. On the other hand, if all the requests irrespective of client are served by a single instance of service objects, then the service will be known as SINGLETON service. The following pictures summarize the concept:
Sessions_in_WCF/Per_Call.JPG
Sessions_in_WCF/Per_Session.JPG
Sessions_in_WCF/Singleton.JPG

How to Configure Sessions in WCF?

To configure sessions in WCF, one should know the following three elements:
  1. Binding – Because all bindings do not support sessions. Only WS-*, NetTcpBinding andNetNamedPipeBinding have session support so selection of appropriate binding is necessary.
  2. SessionMode – This service contract specifies service’s possible expectation for session from incoming client request. It has three self describing values:
    • Allowed – Service can accept sessionful clients as well as sessionless.
    • Required – Service will entertain only those clients who have session, sessionless client cannot connect to service.
    • NotAllowed – Service can interact only with sessionless clients. Just opposite to Required.
  3. InstanceContextMode – This is a service behavior that controls instantiation of actual service class. It has the following values:
    • PerCall – Each request made to server will be served by a new instance of service class.
    • PerSession – A Session will have its dedicated service instance and all requests pertaining to the session will be served by that instance only. All sessions will have their individual dedicated service instances.
    • Single –All requests to the service will be served by a single unique instance of service class.
Let’s consolidate this. First a suitable binding should be there which makes the ground to support the session. Then SessionMode of service contract should be supportive so that service could allow sessionful requests and at last InstanceContextMode should be configured such that it responds in a sessionful manner. The last setting is crucial as it is the only one that decides whether a request will be served by a new service instance or by an existing one. There can be numerous combinations of such settings where one has to judge meaningful ones only. E.g. If you specify session supportive binding, Allowed session mode but specify Per Call instance context mode then there is no meaning of such session as each request will be served by a new instance of service class in spite of all other supports.

Let’s Do Some Experiment

Download the attached sample code and follow this article. Doing practical along with theory will make you understand the concept better. In the attached sample code, there are two projects - one a window app and another, a console app. Window project works like a client while another is WCF server. There are two bindings:
  1. basicHttp and
  2. NetTcp
The two button handlers call WCF service on two different bindings. At the service side, the called operation analyzes three objects – Instance context, service context and session Id. Here the intention is to check how different objects and session id are created to handle incoming requests. The form application has a label control that displays session id at the client side.
Now run the code and click the Http button. You will observe that there is no session id at form and neither at service side, now click this button twice, see the instance context and service objects are different each time. This scenario depicts Per Call service as service always uses new instance context and service instance. Now click TCP button twice and observe the values at service and at client. You will find the session id is not same at service and client, still the service responds by the same service objects. When the TCP button is clicked, the client makes a request to service over sessionful channel, service accepts this session responds as sessionful service that’s why each request is served by same instance of service object (Instance context + service instance).
There is one thing to understand that unlike ASP.NET in WCF, session id is not mandatorily to be same at service and client. This is because for the two bindings - NetTCPBinding and NetNamedPipeBinding, WCF identifies the client by the underlying transport channel but for some other bindings (like WSHttp) which uses connectionless HTTP as underlying channel, WCF needs some way to identify the client. In such cases, it adds a new field – Session Id to message header to identify the client. Let’s check this behavior. Replace basicHttpBinding with wsHttpBinding in service’s app.config and update the client with the newer files. Your new endpoint in service’s app.config should look like this:
<endpoint address="pqr" binding="wsHttpBinding"
          contract="wcfservice.Iservice" name="b"/>
Run the app and click on HTTP button twice. You will observe that both client and server have the same session id, instance context and service instance during the two service calls. These objects remained persistent because the default value for InstanceContextMode is PerSession and default value for SessionMode is Allowed. Therefore a sessionful binding’s session was accepted by service and served by sessioned service objects. To experiment further, let’s decorate our code with these attributes. Your code should look like this:
[ServiceContract(SessionMode = SessionMode.Allowed)]
 public interface Iservice
 {
    //some code…
 }
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
 public class serviceclass : Iservice
 {
    // some code…
 }
When you run the code after these changes and click the HTTP button, you will not observe any change from the previous result. Now change instance context mode to PerCall, generate new proxy (by svcutil) and update the client. Your code should look like this:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
 public class serviceclass : Iservice
 {
    // some code…
 }
Run the code and click the Http button twice, you will notice that this time always a new pair of service objects is created to serve the request. The same will happen even if you click the Tcp button. Now just make the InstanceContextMode to single. Your code should look like this:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
 public class serviceclass : Iservice
 {
     // some code…
 }
Now run the code and click both the buttons. This time you will see that both Tcp and Http requests are served by the same service objects. This is because InstanceContextMode.Single configures the service to serve all the requests by same service object.
I hope the concept covered so far is clear to you. Sometimes you can derive the result yourself even without running the code by just analyzing the value of different configuration of SessionMode and InstanceContextMode property. I would recommend you to make some more random configurations and just play with it to make the concept clearer a bit more. [Do remember that by default, InstanceContextModeis PerSession and SessionMode is Allowed. If the underlying binding is not supportive to session, then though having sessionful the service responds as Per call.]

Demarcation of Operations

Demarcation is to annotate service operations by some special attribute to determine the first and last operation in their execution order. Consider a service having 4 methods/operations named- SignIn(), GetDetails(). TransferFund() and SignOut(). In such a scenario, a user must be signed in and then try to fetch details and do transfer. If user signs out, then he should not be allowed for further requests until he signs in. To configure such type of execution order, Demarcation is required. There are two attributes:
  1. IsInitiating (Default - True)
  2. IsTerminating (Default – False)
These attributes decide which operation should be called first and which should be last? For the above four operations, following can be one possible sequence:
[OperationContract(IsInitiating = True)]
 Bool SignIn()

[OperationContract(IsInitiating = false)]
 String GetDetails()

[OperationContract(IsInitiating = false)]
 Bool TransferFund()

[OperationContract(IsInitiating = false, IsTerminating = True)]
 Bool SignOut()
Here initiation and termination refers to a session which is mandatory for demarcation, as service needs to know whether client has followed the particular sequence or not. Here operation 2,3 and 4 are set to IsInitiating = false so cannot be called first but can be called after an Isinitiating = True operation is called. Similarly, Operation 4 is annotated as IsTerminating = True that’s why when it is called, it terminates the session (along with underlying channel) and then client cannot make further calls until a fresh proxy is created and an IsInitiating = True operation is called. To use demarcation, the following configuration is necessary:
  1. A session supportive binding
  2. SessionMode set to Required
When IsTerminating operation is called, WCF discards the channel and never accepts further messages from it. If an operation is not decorated explicitly with any of these attributes, then default value of these attributes will be applicable to it.
That’s all for now.
At last, just recapitulate once - There are 3 things to remember for WCF session:
  1. Sessionful binding
  2. SessionMode service contract
  3. InstanceContextMode service behavior
Demarcation defines first and last operation in execution order.
WCF session is somewhat different than ASP.NET sessions in the following ways as in WCF:
  1. Sessions are created and terminated by clients.
  2. Server does not use session to store some general data.
  3. Session does not heavily rely on Session Id, a group of messages having particular field in their header or body can also be considered part of session.
  4. Session Id may not be same at client and server.
Hope this small article has given you some brief idea about WCF session and now you can feel some base for further reading. Please do some experiments on your own and refer to MSDN for in depth analysis of the concept.
Please let me know if something is missing or needs correction as it will be helpful for all of us.
You can refer to my other article here for WCF transaction.

Friday, 3 May 2019

Write a single method which can be passed either any type of arrays and it returns the list of unique items in the specified list




1.    Consider the following two arrays:

string[] arrStrings = new string[] { “Bal”, “Yuriy”, “Ken”, “Apple”, “Ken” };
int[] arrNumbers = new int[] { 11, 2, 25, 34, 66, 25, 0, 0, 3, 4, 2, 89 };


Write a single method which can be passed either one of these arrays and it returns the list of unique items in the specified list. You cannot use LINQ to solve this problem.using System;


using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arrStrings = new string[] { "Bal", "Yuriy", "Ken", "Apple", "Ken" };
            int[] arrNumbers = new int[] { 11, 2, 25, 34, 66, 25, 0, 0, 3, 4, 2, 89 };
            
            //For Integer arrays
            List<int> objIntList = new List<int>();
            objIntList = GetUniqueList<int>(arrNumbers);

            //For String arrays
            List<string> objStringList = new List<string>();
            objStringList = GetUniqueList<string>(arrStrings);
        }

    

        private static List<T> GetUniqueList<T>(T[] arraMix)
        {
            List<T> objUniqueList = new List<T>();
            foreach (var chkTest in arraMix)
            {
                if (!objUniqueList.Contains(chkTest))
                {
                    objUniqueList.Add(chkTest);
                }
            }
            return objUniqueList;
        }
    }
}















Make Your ASP.NET MVC Website Faster




As we know that performance is an important part for every application on production. If any website is facing issue of performance then the users do not prefer to use that website. There are many ways to improve the performance of a website in ASP.NET MVC. I am going to demonstrate one by one.

Step 1: Release Mode Build

You should always use the debug build on production. You should make sure that application is compiled in Release Mode rather than Debug Mode.

Release Mode

You need to make changes in Web.Config on Production, when going to deploy the ASP.NET MVC application. Make sure compilation debug mode should be false.

Debug Mode

Step 2: Use Single View Engine

As you know in ASP.NET MVC, we can use multiple View Engines; it can be Web Forms [Aspx] orRazor [cshtml] or you can also create your own custom engine to process the ASP.NET MVC Views. We can also configure all engines in same application. 

You need to care two things before setting up the engine for the MVC application. Firstly, Engines list should be clear before setting up new engine and only one engine should be setting up.
  1. protected override void OnApplicationStarted()  
  2. {  
  3.     ViewEngines.Engines.Clear();  
  4.     ViewEngines.Engines.Add(new RazorViewEngine());  
  5.     base.OnApplicationStarted();  
  6.   
  7.   
  8.     AreaRegistration.RegisterAllAreas();  
  9.   
  10.     RegisterGlobalFilters(GlobalFilters.Filters);  
  11.     RegisterRoutes(RouteTable.Routes);  
  12.     RegisterBundles(BundleTable.Bundles);  
  13.     Register(GlobalConfiguration.Configuration);  
  14.     RegisterAuth();  
  15.     System.Threading.LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);  
  16. }  
Step 3: Bundling and Minification

We used to create client side application with attractive design. So, for this we always prefer to use Jquery/Javascript and CSS. But as we all know these files are downloaded when we are going to access the website. If you are using multiple CSS and Jquery file then it will take more time to load it and it makes your site very slow. 

So, you should prefer to use small file which can be loaded faster or single file which load faster rather than multiple file. In MVC there are two concepts behind this Bundling and Minification. This will help your site to make it faster and decrease the load time. 
  1. public static void RegisterBundles(BundleCollection bundles)  
  2. {  
  3.     bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  4.                "~/Content/Jquery/jquery-{version}.js"));  
  5.   
  6.     bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  7.                "~/Content/Jquery/jquery.unobtrusive*",  
  8.                "~/Content/Jquery/jquery.validate*"));  
  9.       
  10.   
  11.     bundles.Add(new ScriptBundle("~/bundles/JqueryHomePage").Include("~/Content/js/jquery-1.8.3.min.js", "~/Content/Jquery/bootstrap.min.js", "~/Content/Jquery/HomeJquery.js"));  
  12.       
  13.     bundles.Add(new StyleBundle("~/Content/HomeMain").Include("~/Content/Css/style.css").Include("~/Content/Css/font-awesome/css/font-awesome.css", new CssRewriteUrlTransform()));  
  14.   
  15. }  
RegisterBundles

Web essentials

Step 4: Caching Enabled

Caching has an important role to make the website faster. It increases the performance smoothly. Actually when website uses the Caching features, it provides the facility to use the existing and downloaded file for next process. Using Caching, you can save some kind of files on server memory and use it next time without downloading the new one.
  1. public class HomeController : Controller  
  2. {  
  3.   [OutputCache(Duration = 300, VaryByParam = "none")] //cached for 300 seconds  
  4.   public ActionResult Index()  
  5.   {  
  6.       return View();  
  7.   }  
  8. }  
You need to make some changes in Web.Config to set the application in Cache mode.
  1. <configuration>  
  2.   <system.webserver>  
  3.     <staticcontent>  
  4.       <clientcache cachecontrolmode = "UserMaxAge" httpexpires="365.00:00:00">  
  5.     </clientcache></staticcontent>  
  6.   </system.webserver>  
  7. </configuration>  
Step 5: Load Minimum Data

Now a days, mostly site connect with database for rendering the data on View. But as we know if you are going to load heavy data one time, it makes your site slow. So, you should always prefer to bring the small amount of the data one time and render it on the View.

The easiest way to do this is to use Paging with your application and show the minimum data one time, this will help your site to increase performance. You can use Stored Procedure to get the data which is the fastest way and also you can add filtering option in it.

Step 6: Use Sprite Images

Images make your website more beautiful and user friendly. I believe, images help us to understand the concepts easily. But if there are multiple images on single page, it will affect the performance of the site. It is because images take time to download.

So, here you can use Sprite Image which combines the multiple images in one and load in single download. You can install Sprite Image generator with your application.

 Sprite Image

Or simply using the Web Essentials feature, you can make images as sprite images. 

Web Essentials feature

Step 7: Client Side Validation


Validation takes important part because it validates the user data that it is valid or not. But suppose after validating the single data, your site is going to load that means user should wait every time to load your site again and again. So, always prefer to make the validation on Client Side. 

It makes your site faster because there is no need to load the site on every input validation. It will show error message if something goes wrong on client side.

Client Side Validation

Step 8: Use Performance Tools

You can do many things to make your site faster. But sometime, we are confused and unable to figure out when my site is taking much time to load or sometimes there are memory leaks issue. So, in that scenario you can use some tools which can help you to figure out the root causes.
  1. Dotnet Memory Profiler
  2. Fiddler
  3. FireBug
  4. Google Page Speed Test
  5. Web Page Test

Thursday, 28 March 2019

There are seven simple tips that will boost the performance of your SQL queries.






 Here are seven simple tips that will boost the performance of your SQL queries.
1. Owner/Schema Name
Always prefix object names (i.e. table name, stored procedure name, etc.) with its owner/schema name.
Reason: If owner/schema name is not provided, SQL Server’s engine tries to find it in all schemas until the object finds it. SQL Server engine will not search for the table outside of its owner/schema if the owner/schema name is provided.
2. The * Operator
Do not use the *  operator in your SELECT statements. Instead, use column names.
Reason: SQL Server scans for all column names and replaces the * with all the column names of the table(s) in the SQL SELECT statement. Providing column names avoids this search-and-replace, and enhances performance.
3. Nullable Columns
Do not use NOT IN when comparing with nullable columns. Use NOT EXISTS instead.
Reason: When NOT IN is used in the query (even if the query doesn’t return rows with null values), SQL Server will check each result to see if it is null or not. Using NOT EXISTS will not do the comparison with nulls.
4. Table Variables and Joins
Do not use table variables in joins. Use temporary tables, CTEs (Common Table Expressions), or derived tables in joins instead.
Reason: Even though table variables are very fast and efficient in a lot of situations, the SQL Server engine sees it as a single row. Due to this, they perform horribly when used in joins. CTEs and derived tables perform better with joins compared to table variables.
5. Stored Procedure Names
Do not begin your stored procedure’s name with sp_.
Reason: When the stored procedure is named sp_ or SP_, SQL Server always checks in the system/master database even if the Owner/Schema name is provided. Providing a name withoutSP_ to a stored procedure avoids this unnecessary check in the system/master database in SQL Server.
6. Use SET NOCOUNT ON
Use SET NOCOUNT ON with DML operations.
Reason: When performing DML operations (i.e. INSERT, DELETE, SELECT, and UPDATE), SQL Server always returns the number of rows affected. In complex queries with a lot of joins, this becomes a huge performance issue. Using SET NOCOUNT ON will improve performance because it will not count the number of rows affected.
7. Avoid Using GROUP BY, ORDER BY, and DISTINCT
Avoid using GROUP BY, ORDER BY, and DISTINCT as much as possible
Reason: When using GROUP BY, ORDER BY, or DISTINCT, SQL Server engine creates a work table and puts the data on the work table. After that, it organizes this data in work table as requested by the query, and then it returns the final result.
Use GROUP BY, ORDER BY, or DISTINCT in your query only when absolutely necessary.