26 June 2014

How to write a reliable web service

To increase the reliability of a web service you must need to implement following three basic points:
  1. Validate all input parameters.
  2. Result must be predictable to client. (Client can easily identify that call was successful or not)
  3. Handle all unhanded exceptions before sending result to client
Here I will give you a basic sample which has implemented above points.

namespace Test_WebServices
{
    
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class EmployeeService : System.Web.Services.WebService
    {

        [WebMethod]
        public GetEmployeeResult GetEmployee(string code)
        {
            GetEmployeeResult result = new GetEmployeeResult();

            try
            {
                //Always validate parameters and continue execution only if you got the desire value.
                if (ValidateParameter(code, result))
                {
                    
                    //Write you business logic
                    Employee emp = new Employee()
                    {
                        Code = code,
                        Name = "Employee A",
                        Phone = "123",
                        Address = "XYZ Street"
                    };

                    //Return the result with Success code.
                    result.ErrorCode = 0;
                    result.ErrorDesc = "Success";
                    result.Data = emp;
                }
            }
            catch (Exception ex)
            {
                //Instead of sending exception message to your potential client you can send generic exception in response
                //and send an error email to your self.

                result.ErrorCode = -100;
                result.ErrorDesc = "Message: " + ex.Message + " StackTrace:" + ex.StackTrace;
                result.Data = null;
            }

            return result;
        }

        private bool ValidateParameter(string code, GetEmployeeResult Result)
        {
            bool isValid;
            if (string.IsNullOrEmpty(code))
            {
                isValid = false;
                Result.ErrorCode = 1;
                Result.ErrorDesc = "Parameter 'code' is required";
            }
            else if (code.Length <= 2)
            {
                isValid = false;
                Result.ErrorCode = 2;
                Result.ErrorDesc = "Invalid 'code' found";
            }
            else
            {
                isValid = true;
            }
            return isValid;
        }


        public class GetEmployeeResult 
        {
            public int ErrorCode { get; set; }      //This will help caller to quickly identify problem
            public string ErrorDesc { get; set; }   //This can contain detail of the error if any
            public Employee Data { get; set; }      //This is hold the actual result of the service
        }


        public class Employee
        {
            public string Code { get; set; }
            public string Name { get; set; }
            public string Phone { get; set; }
            public string Address { get; set; }
        }
    }


}


Always encapsulate the result in a custom object and send that custom object to client. In our case we are sending 'GetEmployeeResult' object to client. Client of this service can easily identify that the call is successful or not by checking ErrorCode variable. Here is sample code of caller.

EmployeeServiceSoapClient client = new EmployeeServiceSoapClient();
GetEmployeeResult result = client.GetEmployee("E101");
if (result.ErrorCode != 0)
{
    throw new Exception("Error in service : ErrorCode=" + result.ErrorCode + " - ErrorDesc=" + result.ErrorDesc);
}

//Finally we got the data
Employee emp = result.Data;

You can implement these points in any service (WCF, PHP or Java based services) to increase reliability of your code.

01 August 2013

Menu is going behind Silverlight control


If your menu is going behind Silverlight control then you have two options:

Option 1: Set 'Windowless=true' but this option has lots of limitations including performance.
Ref: http://msdn.microsoft.com/en-us/library/cc838156(v=vs.95).aspx

Option 2 (Recommended): Use empty iframe behind your menu. z-index of iframe must be less than to your menu.

Basic concept: "When you take your mouse over to the menu then your menu will be shown at that time make your iframe visible behind your menu."

I am sharing a very basic sample. You have to customize it based on requirement.

Sample: TestMenu.htm


With the help of Muhammad Furqan Khan and Muhammad Fahed Khan, we found iframe based solution. Thank you guys!

16 July 2013

Real Time Timer in C#

In  Dot Net, following timers are not real time.

System.Windows.Forms.Timer
System.Timers.Timer
System.Threading.Timer

Means if you want to run your code at every 100 millisecond then above timer fire even around 110 millisecond or later. Windows is not a real time OS because of this .Net is also not a real time.

To create a real time timer in C# you have to write custom code that can hold CPU to run your code at right time.


class Program
{
   static void Main(string[] args)
  {
    Console.ReadLine();
    Console.WriteLine("Running");
    RealTimeTimerTest obj = new RealTimeTimerTest();
 
    obj.Run();
  }
}
 
public class RealTimeTimerTest
{
   List<DateTime> lst = new List<DateTime>();
  System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
 
  public void Run()
  {
    int Tick = 100;
    int Sleep = Tick - 20;
    long OldElapsedMilliseconds = 0;
    sw.Start();

    while (sw.IsRunning)
    {
      long ElapsedMilliseconds = sw.ElapsedMilliseconds;
      long mod = (ElapsedMilliseconds % Tick);

      if (OldElapsedMilliseconds != ElapsedMilliseconds && (mod == 0 || ElapsedMilliseconds > Tick))
      {

        //-----------------Do here whatever you want to do--------------Start
        lst.Add(DateTime.Now);
        //-----------------Do here whatever you want to do--------------End

        //-----------------Restart----------------Start
        OldElapsedMilliseconds = ElapsedMilliseconds;
        OldElapsedMilliseconds = 0;
        sw.Reset();
        sw.Start();
 
        System.Threading.Thread.Sleep(Sleep); 
         //-----------------Restart----------------End
      }
       
      //------------Must define some condition to break the loop here-----------Start

      if (lst.Count > 500)
      {
        Write();
        break;
      }
      //-------------Must define some condition to break the loop here-----------End
    }
  }

 
  private void Write()
  {
    System.IO.StreamWriter sw = new System.IO.StreamWriter("d:\\text.txt", true);
    foreach (DateTime dtStart in lst)
      sw.WriteLine(dtStart.ToString("HH:mm:ss.ffffff"));    sw.Close();
  }
}

//OUTPUT:
//03:15:55.503314
//03:15:55.603320
//03:15:55.703325
//03:15:55.803331
//03:15:55.903337
//03:15:56.003343
//03:15:56.103348
//03:15:56.203354
//03:15:56.303360
//03:15:56.403365
//03:15:56.503371
//.
//.
//.

23 June 2013

Difference between 'Throw' and 'Throw ex'

Today we are going to compare the difference between 'Throw' and 'Throw ex' with an example. I had created a web project and write the following code:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        int a = 5, b = 0;

        int c = Divide(a, b);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private int Divide(int a, int b)
{
    return a / b;
}

When I run the applicatin it throws exception like this:

 
'Throw ex' basically re-throw the exception and lost the original stack trace. So it is always difficult to track the original stack trace BUT if I replace 'throw ex' to 'throw' like this:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        int a = 5, b = 0;

        int c = Divide(a, b);
    }
    catch (Exception ex)
    {
        throw;
    }
}

private int Divide(int a, int b)
{
    return a / b;
}

Then it will throw exception with original stack trace.

 
 
Key Point: It is better to use 'throw' instead of 'throw ex' where needed BUT observe the above code again. In the above example we are throwing exception in any case and doing nothing inside the catch block THEN why we need try/catch block? In this type of cases it is better to remove try/catch block because we do not need this.

I hope it will clear the difference and also help you to understand invalid usage of try/catch block.

08 June 2013

How volatile keyword work in C#?

Today I was searching for volatile keyword in C#. I have few questions in my mind that how it is really working? how can I test this? so here is what I found useful.

"The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times."

using System;
using System.Threading;
public class Worker
{
  // This method is called when the thread is started. 
  public void DoWork()
  {
    while (!_shouldStop)
    {
      Console.WriteLine("Worker thread: working...");
    }
    Console.WriteLine("Worker thread: terminating gracefully.");
  }
  public void RequestStop()
  {
    _shouldStop = true;
  }
  // Keyword volatile is used as a hint to the compiler that this data 
  // member is accessed by multiple threads. 
  private volatile bool _shouldStop;
}


public class WorkerThreadExample
{
  static void Main()
  {
    // Create the worker thread object. This does not start the thread.
    Worker workerObject = new Worker();
    Thread workerThread = new Thread(workerObject.DoWork);

    // Start the worker thread.
    workerThread.Start();
    Console.WriteLine("Main thread: starting worker thread...");
    // Loop until the worker thread activates. 
    while (!workerThread.IsAlive) ;

    // Put the main thread to sleep for 1 millisecond to 
    // allow the worker thread to do some work.
    Thread.Sleep(1);
    
    // Request that the worker thread stop itself.
    workerObject.RequestStop();


    // Use the Thread.Join method to block the current thread  
    // until the object's thread terminates.
    workerThread.Join();
    Console.WriteLine("Main thread: worker thread has terminated.");
  }
  
  // Sample output: 
  // Main thread: starting worker thread... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: working... 
  // Worker thread: terminating gracefully. 
  // Main thread: worker thread has terminated.
}

Another article contain following about Volatile keyword

The point of volatile is that multiple threads running on multiple CPU's can and will cache data and re-order instructions.

If it is not volatile, and CPU A increments a value, then CPU B may not actually see that incremented value until some time later, which may cause problems.

If it is volatile, this just ensures the 2 CPU's see the same data at the same time. It doesn't stop them at all from interleaving their reads and write operations which is the problem you are trying to avoid

Reference:http://msdn.microsoft.com/en-us/library/vstudio/x13ttww7.aspx
http://stackoverflow.com/questions/154551/volatile-vs-interlocked-vs-lock