Sunday 8 March 2015

Why to Program WCF Service Contract as Interface

If you have not dug deeper or not paid much attention, you won't even be aware that you can program a WCF service contract to a concrete type also, not just to an interface.
Microsoft has provided a lot of ease to the developer but in some senses it has made the developer a little lame also. Providing the ease in the sense that, fro example, if you create a WCF service the visual studio will render a default template to build up your service. Then you do not bother much about why it has generated a specific code? You may sometimes even not take that as an standard guideline but the rule and you start following that up, and that makes you lame as you loose the deeper understanding of the subject.
The same happened with me also until one day it struck to my mind that why I am using this interface as a service contact. I just removed that interface and made the service class as service contract and defined methods inside it as operation contracts, and the service worked fine.
Now I started thinking like why then we expose this through an interface? what are the advantages?
So, here I get it:

  • First of all, as a thumb rule, if we want to follow best design practices we should always program to interface not to implementation. It gives a lot of flexibility and decoupling of the code.
  • Secondly, If a service is exposed through interface, we can make any changes to our implementation without breaking the client, even the name of the service class can be changed.
  • Another advantage can be like, suppose we have a service MyService that exposes O1, O2 nad O3 operation contracts to a client through IMyService1 contract. Now a situation comes where another client comes and asks for the service but wants only O1 and O2 operations and we as a service provider do not want to provide him O3 then it is very easy to do this if we have exposed our service with the interface. What we can do is simply create another contract as IMyService2 that exposes only O1 and O2 operation contracts an expose the service with this contract to this client. Now consider another situation where a client want one more operation contract O4 along with the three, what we can do here create another service contract IMyService3 which exposes only O4. Now the service can be exposed to this client with service contracts IMyService1 and IMyService3. So the crux here is that we can accomplish these changes otherwise also but not with such an ease and minimal changes.


I hope I could explain the idea. If anyone wants to add something to it, then it would be great and more helpful to the readers.


Wednesday 3 December 2014

Disabling Asp.Net Request Validation

Asp.Net runtime does check the posted data for any malicious or dangerous contents for security reasons. For example Asp.Net engine considers any html markup, even pretty harmless or small markup like "<b>", as a security threat and blocks the request and throws potentially dangerous value was detected exception.

This is a good thing to block such request because such request can be a severe threat to your website, but there are some scenarios where you would like to accept such contents in the request. For example, you allow users on your website to enter formatted comments or your website is for sharing messages among users then you would like those messages to be formatted, and in that case your website will need to accept the data with html markup.

So what is the solution?

There are two ways:

  1. Allow the html markup for whole website and stop security validation.
  2. Allow the html markup on the specific pages wherever it is required. 
The second option is a good choice because the security is not compromised for whole website.

Disabling security validation is very simple. I have explained it below for both the cases:


For Specific Pages

Add ValidateRequest="false" in the Page directive of the required pages as:

<%@ Page ValidateRequest="false" %>

Add following section into the web.config of your application:
<location path="Common/pageWithUnsecuredData.aspx">
  <system.web>
    <httpRuntime requestValidationMode="2.0" />
  </system.web>
</location>

Set the value of path to a specific page if there is only one page or to a directory path if you want to allow it for more than one pages.

For Whole Website

Add following section into the web.config of your application:
<configuration>
  <system.web>
    <pages validateRequest="false" />
  </system.web>
</configuration>
Add following section into the web.config of your application for each page:
<location path="Common/pageWithUnsecuredData.aspx">
  <system.web>
    <httpRuntime requestValidationMode="2.0" />
  </system.web>
</location>
Set the value of path to a specific page if there is only one page or to a directory path if you want to allow it for more than one pages.
Note: Setting httpRuntime with requestValidationMode="2.0" is required only if you are using Asp.Net 4.0 or above because in these versions the security validation takes place in earlier phase of page life cycle, however, in version 2.0 security validation takes place in later stage of the page life cycle.


Sunday 5 January 2014

Handling Session Timeout for Ajax Requests

ASP.Net engine is clever enough to deal with normal (non-ajax) requests when user session times out, the asp.net engine automatically redirects the user to login page specified in the web.config file.
Now, the trouble is when the request is made through ajax. The aps.net engine does its bit by redirecting the user to login page but the problem is that redirected page goes as a response to ajax response handler in the javascript. And what happens then? Something very unexpected. You will observe very weird behavior like some javascript error or a distorted UI or may be nothing.
How to deal with such situation? I will suggest here a very simple solution that may help you escape this trouble.

Add following code in the Global.asax file of your web application:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
        // This is a check for Ajax request so that other requests won't fall in this condition.
        if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            if (!Request.IsAuthenticated)
            {
                // You can set the status code to something else if you do not feel 401 as appropriate.
                Response.StatusCode = 401;
                Response.End();
            }
        }
}

Add following code in the javascript:

$(document).ajaxComplete(function (sender, e) {
        if (e.status == 401) {
            alert("Your session has timed out.");
            window.location.href = "Login.aspx";
        }
 });


Above code works if you are using Jquery else you can write the same code in onreadystatuschanged event of XMLHttpRequest.

Also keep in mind that the javascript code should be included in the master page of you application so that it is available to all the pages.



Thursday 2 January 2014

ClickOnce crashing visual studio

Here I am writing one of my deployment issue encounter which gave me tough time. I was trying to deploy an application through ClickOnce and each time I would try publishing it and the visual studio crashes each time.
After struggling a lot I could find out the issue but it took me hours to track it down however the issue was very small.
The issue was due to User Access Control (UAC).

Now, how can you resolved this issue:
1. Go to project properties
2. Go to application tab.

3. Change the Manifest property to Create application without a manifest in the dropdown highlighted in the image below.

Save the project settings and I hope your issue should be resolved.



Friday 27 December 2013

Web application client side caching

This is a very important aspect to understand that how the browser caching works and when and how to control it. I will discuss a few basic things here about the client side caching.

You can enable or disable browser caching of your web pages by specifying following tag in your application's web.config file:

 <system.web>
          <caching>  
 <outputCache  enableOutputCache="false" >  
 </outputCache>
 </caching>
 </system.web>

If you want more control over caching behavior than you should specify it in the page itself. By specifying the caching inside the webpage you can control browser caching at the page level.

Add a page directive to your webpage like this:

<%@ OutputCache Duration="1" NoStore="true" VaryByParam="*" %>

All the three attributes in this directive are required. Here we can specify the duration for which the page should be cached by setting the Duration attribute. The duration is considered in milliseconds.
With attribute VaryByParam you can specify when the page should make a fresh request. If '*' is mentioned for this attribute value that means for each parameter value in the request query string the browser will make a fresh request, if the value of any parameter changes in subsequent request.
For example if i make two subsequent request as:
http://blogger.com?id=121&tag=abc
http://blogger.com?id=122&tag=abc

In both the cases above the browser will make fresh request because the parameter value for 'id' has changed.
If you want the browser to make a fresh request on the change of particular parameter then you can specify it like, VaryByParam="tag".

By setting the value of NoStore you can specify whether you want the browser cache that page or not.

Here is a very tricky point in browser caching that you must remember or it may give you great headache at times and that is, as per the w3c standards the GET requests are always cacheable whether the caching is enabled or disabled. So whenever you are making request from javascript and do not want the page to be cached, make sure that you are making POST request.



Wednesday 25 September 2013

ASP.Net WebMethod

One day I thought, how convenient it would have been if I could call a server method from my client script on my web page, simply, as I can call a javascript method from another javascript method.
And yes, there is the asp.net WebMethod attribute with which we can do a sever method calling as calling a method locally. WebMethod with JQuery and a little bit of JSON and we are done.
Here is the code snippet to implement the same:

Asp.Net Code

[WebMethod] 

public static string ServerMethod(string name)
{    
     return "Hi " + name;
}

WebMethod attribute requires reference to System.Web.Services.
And remember to mark the method static, otherwise it will not work.

Client Script

function GetResultFromServer()
{
   $.ajax({ type:"post",
   url: "Default.aspx/ServerMethod",
   data: JSON.stringify({name:"Boraska"}),
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (data) {
      alert("Hurreyyy! I got " + data.d + "from server method.");
      }
  });}
This small script and WebMethod attribute do the fantastic job, no need to go in detail of page life-cycle events and many more things.
Now, here again, there are few things that needs to be taken care to make this work:
  • Url contains the method name which you want to call. Specify the url carefully. If you need you can pass query strings as well with url.
  • Data is the parameters you want to pass to the server method. The name and number of parameters must match to the server method what you are passing from here.
  • More than one parameters can be passed to the method but their types should be compatible, I mean you can pass "abc" to object type parameter but not to int type of parameter in the server method.


Tuesday 24 September 2013

Sequencing thread access with ManualResetEvent and AutoResetEvent

Threads! tiny things can make a very complex and sophisticated article like clothe and many more. But when not handled with care and knowledge, can spoil all your work and sometimes almost impossible to separate out.
Yes this is the best simulation of nature of .Net Threads. We call thread a light-weight process in terms of many aspects. And this light-weight thing can make very sophisticated software applications, but when used inappropriately can result in hell of bugs in your application. A multi-threaded application is hard to debug and understand. Yes, but most of the sophisticated applications cannot be written without threading.

In this post I am covering ManualResetEvent and AutoResetEvent.

ManualResetEvent and AutoResetEvent are basically used for sequencing the thread access in a multithreaded environment, although can also be used for implementing exclusive access to a shared resource.
Here is an example how to use AutoResetEvent for mutual exclusion

class Program
{
    static void Main(string[] args)
    {
        ThreadingTest.StartTasks();
    }



public class ThreadingTest
{
    private static AutoResetEvent are = new AutoResetEvent(false);
    public static void StartTasks()
    {
        Thread[] threads = new Thread[15];
        for (int i = 0; i < 15; i++)
        {


            threads[i] = new Thread(new ThreadStart(WriteToFile));

            threads[i].Name = i.ToString();


            threads[i].Start();
        }


        Console.WriteLine("Press enter key to start.");
        Console.ReadLine();
        are.Set(); 
        for (int i = 0; i < 15; i++)
        {


            threads[i].Join();
        }

        Console.ReadKey();
    }
    public static void WriteToFile()
    {


        are.WaitOne();

        Console.WriteLine("Thread " + Thread.CurrentThread.Name + "Entered");
        File.AppendAllText(@"d:\test.txt", "This text can be inserted at any position.");
        Thread.Sleep(1000);
        Console.WriteLine("Thread " + Thread.CurrentThread.Name + "Exited");
        are.Set();


    }
}


But there are two points to consider here.
  1. For mutual exclusion lock or monitor is the best and easy solution. If AutoResetEvent resets automatically with WaitOne call but if both the operations WaitOne and Reset does not execute atomically, your application logic could be in great jeopardy.
  2. ManualResetEvent cannot be used for mutual exclusion in this situation as it does not reset automatically.

Now consider the above example in which we are writing to a file. In the above example the text has to be written in a sequential order to the file, what is our option then to implement that? Of course, the solution is ManulaResetEvent or AutoResetEvent. Now, see the code snippet below that explains the situation:

public class ThreadingTest
{   
    static ManualResetEvent[] mre = new ManualResetEvent[3];
    public static void StartTasks()
    {        Thread[] threads = new Thread[3];
        for (int i = 0; i < 3; i++)
        {
            mre[i] =
new ManualResetEvent(false);
        }

        threads[0] =
new Thread(new ThreadStart(Task1));
        threads[1] = new Thread(new ThreadStart(Task2));
        threads[2] = new Thread(new ThreadStart(Task3));

        for (int i = 0; i < 3; i++)
        {
            threads[i].Start();
        }
        // Signal the first event
        mre[0].Set();
    }
    public static void Task1()
    {
        // Do some work here.
        mre[0].WaitOne();
        WriteToFile(
"This is the first text that should be written in the file.");
        // Signal the next event so that other thread can write to file.
        mre[1].Set();
    }

    public static void Task2()
    {
        // Do some work here.
        mre[1].WaitOne();
        WriteToFile(
"This is the second text that should be written in the file.");
        // Signal the next event so that other thread can write to file.
        mre[2].Set();
    }

   
public static void Task3()
    {
        // Do some work here.       
        WaitHandle.WaitAll(mre);
        WriteToFile("This is the last text that should be written in the file.");
    }

   
public static void WriteToFile(string text)
    {
       
File.AppendAllText(@"d:\test.txt", text + Environment.NewLine);
    }
}

If you observe in the above code the three threads are doing their respective tasks but the access to file write is sequential. And that sequence is controlled by ResetEvents. In this situation we can use either ManualResetEvent or AutoResetEvent.
However there are situations where one is preferred over the other. You can read that in my next article ManualResetEvent or AutoResetEvent?.