Monday, July 21, 2014

REST vs SOAP

REST stands for REpresentational State Transfer (REST) which enforces a stateless client server design where web services are treated as resource and can be accessed and identified by there URL unlike SOAP web services which were defined by WSDL.
Web services written by applying REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol.

SOAP
SOAP, originally defined as Simple Object Access Protocol, is a protocol specification for exchanging structured information in XML form.SOAP is protocol which relies on XML, that defines what is in the message and how to process it,set of encoding rules for data types, representation for procedure calls and responses.


REST vs SOAP

Before going for differences between two lets first see the differences in request header :

Sample SOAP & REST Request message for Weather Web Service :


 


SOAP vs REST Key Differences
Here are some of Key differences between SOAP and REST web Service :

  •  REST uses HTTP/HTTPS, SOAP can use almost any transport to send the request(for example we can have SOAP Messages over SMTP),  SOAP is a XML based messaging protocol.
  • REST is totally stateless operations where as SOAP supports statefull calls too. 
  • SOAP has more strict contract in the form of WSDL between applications, no such contract exists in case of REST.
  • AS REST APIs can be consumed using simple GET requests, RESTresponse can be cached, this is not possible with SOAP.
  • REST is Lighter, SOAP requires an XML wrapper around every request and response(SOAP Headers, XML tags etc). Thats why REST is preferred choice in mobile devices and PDA's
  •  SOAP message format is restricted to XML only where as REST supports other formats too for example JSON.  
  • REST is simpler in terms of development as compared to SOAP.
  • Browsers can handle REST easily as compared to SOAP as REST is based on HTTP where SOAP is another wrapper over HTTP.

Why to use SOAP ? 
SOAP provides some features like Security, Reliable Messaging, Atomic transaction which are not available in REST API.

  • WS-Security  & WS-SecureConversation  Provide support for using security tokens like Kerberos, and X.509.
  • WS-ReliableMessaging   Reliable messages delivery between distributed applications in case of failures.
  • WS-AtomicTransaction, two-phase commit across distributed transactional resources
  • In case where exact specification  of exchange format need to agreed between applications SOAP is better suitable.

Sunday, July 13, 2014

Maintaining Application State

We usually can create two types of cookies,
1. Session cookies.
2. Persistent cookies.

A session cookies exists only in memory. If a user closes the Web browser,  the session cookie disappears forever.

A persistent cookie, on the other hand, can last for months or even years. When you create a persistent cookie, the  cookie is stored permanently by the user's browers on the user's computer. Internet Explorer,  for example,  stores cookies in a set of text files contained in the following  folder:
\Documents and Settings\[user]\Cookies

Thursday, July 10, 2014

What is the difference between static class and singleton pattern?

In the first overview; we see both singleton class and static class are look similar. But there are many difference and here are the major points.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.

A static class allows only static methods.

Singleton object stores in Heap but, static object stores in stack.

We can clone the object of Singleton but, we can not clone the static class object.

Singleton class follow the OOP(object oriented principles) but not static class
we can implement interface with Singleton class but not with Static class.

Friday, July 4, 2014

Command Design Pattern

 

Implementing the Command interface

First things first: all command objects implement the same interface, which consists of one method.

here's the Command interface:

 public interface Command{  
   public void execute();  
 }  

Implementing a Command to turn a light on

Now, let's say you want to implement a command for turning a light on.
Referring to our set of vendor classes, the Light class has two methods: on() and off(). Here's how you can implement this as a command:


public class LightOnCommand : Command{  
   Light light;  
   public LightOnCommand(Light light){  
     this.light=light;  
   }  
   public void execute(){  
     light.on();  
   }  
 }  

Using the command object

Okey, let's make things simple: say we've got a remote control with only one button and corresponding slot to hold a device to control:


public class SimpleRemoteControl{  
   //we have one slot to hold our command which will control one device.  
   Command slot;  
   public SimpleRemoteControl(){}  
   //we have a method for setting the command the slot is going to control.   
   //This could be called multiple times if the client of this code wanted   
   //to change the behavior of the remote button.  
   public void setCommand(Command command){  
     slot=command;  
   }  
   //This method is called when the button is pressed .   
   //All we do take the current command bound to the slot and  
   //call its execute() method.  
   public void buttonWasPressed(){  
     slot.execute();  
   }  
 }

Creating a simple test to use the Remote Control

Here's just a bit of code to test out the simple remote control. Let's take a look and we'll point out how the pieces match the Command Pattern diagram:


//This is our client in Command pattern-speak.  
 public class RemoteControlTest{  
   public static void main(String[] args){  
     //The remote is our invoker; it will be passed a command object that can be used to make  
     //requests.  
     SimpleRemoteControl remote = new SimpleRemoteControl();  
     //Now we create a Light object, this will be the Receiver of the request.  
     Light light= new Light();  
     //Here, creates a Command and pass it to the Receiver.  
     LightOnCommand lightOn=new LightOnCommand(light);  
     remote.setCommand(lightOn);//Here, pass the command to the invoker.  
     remote.buttonWasPressed();//And then we simulate the button being pressed.  
   }  
 }  

Thursday, June 19, 2014

Thread Pool - BackgroundWorker

BackgroundWorker is a helper class in theSystem.ComponentModel namespace for managing a worker thread. It can be considered a general-purpose implementation of the EAP, and provides the following features:
  • A cooperative cancellation model
  • The ability to safely update WPF or Windows Forms controlswhen the worker completes
  • Forwarding of exceptions to the completion event
  • A protocol for reporting progress
  • An implementation of IComponent allowing it to be sited in Visual Studio’s designer
BackgroundWorker uses the thread pool, which means you should never call Abort on a BackgroundWorker thread.

Using BackgroundWorker

Here are the minimum steps in using BackgroundWorker:
  1. Instantiate BackgroundWorker and handle the DoWork event.
  2. Call RunWorkerAsync, optionally with an object argument.
This then sets it in motion. Any argument passed toRunWorkerAsync will be forwarded to DoWork’s event handler, via the event argument’s Argument property. Here’s an example:
class Program  
 {  
  static BackgroundWorker _bw = new BackgroundWorker();  
  static void Main()  
  {  
   _bw.DoWork += bw_DoWork;  
   _bw.RunWorkerAsync ("Message to worker");  
   Console.ReadLine();  
  }  
  static void bw_DoWork (object sender, DoWorkEventArgs e)  
  {  
   // This is called on the worker thread  
   Console.WriteLine (e.Argument);    // writes "Message to worker"  
   // Perform time-consuming task...  
  }  
 }  
BackgroundWorker has a RunWorkerCompleted event that fires after the DoWork event handler has done its job. Handling RunWorkerCompleted is not mandatory, but you usually do so in order to query any exception that was thrown in DoWork. Further, code within a RunWorkerCompleted event handler is able to update user interface controls without explicit marshaling; code within the DoWork event handler cannot.
To add support for progress reporting:
  1. Set the WorkerReportsProgress property to true.
  2. Periodically call ReportProgress from within the DoWork event handler with a “percentage complete” value, and optionally, a user-state object.
  3. Handle the ProgressChanged event, querying its event argument’s ProgressPercentage property.
  4. Code in the ProgressChanged event handler is free to interact with UI controls just as withRunWorkerCompleted. This is typically where you will update a progress bar.
To add support for cancellation:
  1. Set the WorkerSupportsCancellation property to true.
  2. Periodically check the CancellationPending property from within the DoWork event handler. If it’s true, set the event argument’s Cancel property to true, and return. (The worker can also set Cancel and exit withoutCancellationPending being true if it decides that the job is too difficult and it can’t go on.)
  3. Call CancelAsync to request cancellation.
Here’s an example that implements all the preceding features:
   var bgWorker = new BackgroundWorker { WorkerReportsProgress = true };  
   bgWorker.DoWork += (o, e) =>  
   {  
     //Worker thread code. Gets called in a Non-UI thread.  
   };  
   bgWorker.ProgressChanged += (o, e) =>  
   {  
     //Progress change gets called on the UI thread. Controls can be accessed safely  
   };  
   bgWorker.RunWorkerCompleted += (o, e) =>  
   {  
     //gets called when worker thread finishes. UI thread. Controls can be accessed safely  
   };  
   bgWorker.RunWorkerAsync();  


 using System;  
 using System.Threading;  
 using System.ComponentModel;  
 class Program  
 {  
  static BackgroundWorker _bw;  
  static void Main()  
  {  
   _bw = new BackgroundWorker  
   {  
    WorkerReportsProgress = true,  
    WorkerSupportsCancellation = true  
   };  
   _bw.DoWork += bw_DoWork;  
   _bw.ProgressChanged += bw_ProgressChanged;  
   _bw.RunWorkerCompleted += bw_RunWorkerCompleted;  
   _bw.RunWorkerAsync ("Hello to worker");  
   Console.WriteLine ("Press Enter in the next 5 seconds to cancel");  
   Console.ReadLine();  
   if (_bw.IsBusy) _bw.CancelAsync();  
   Console.ReadLine();  
  }  
  static void bw_DoWork (object sender, DoWorkEventArgs e)  
  {  
   for (int i = 0; i <= 100; i += 20)  
   {  
    if (_bw.CancellationPending) { e.Cancel = true; return; }  
    _bw.ReportProgress (i);  
    Thread.Sleep (1000);   // Just for the demo... don't go sleeping  
   }              // for real in pooled threads!  
   e.Result = 123;  // This gets passed to RunWorkerCompleted  
  }  
  static void bw_RunWorkerCompleted (object sender,  
                    RunWorkerCompletedEventArgs e)  
  {  
   if (e.Cancelled)  
    Console.WriteLine ("You canceled!");  
   else if (e.Error != null)  
    Console.WriteLine ("Worker exception: " + e.Error.ToString());  
   else  
    Console.WriteLine ("Complete: " + e.Result);   // from DoWork  
  }  
  static void bw_ProgressChanged (object sender,  
                  ProgressChangedEventArgs e)  
  {  
   Console.WriteLine ("Reached " + e.ProgressPercentage + "%");  
  }  
 }  
Press Enter in the next 5 seconds to cancel
Reached 0%
Reached 20%
Reached 40%
Reached 60%
Reached 80%
Reached 100%
Complete: 123
 
Press Enter in the next 5 seconds to cancel
Reached 0%
Reached 20%
Reached 40%
 
You canceled!

Subclassing BackgroundWorker


BackgroundWorker is not sealed and provides a virtual OnDoWork method, suggesting another pattern for its use. In writing a potentially long-running method, you could write an additional version returning a subclassedBackgroundWorker, preconfigured to perform the job concurrently. The consumer then needs to handle only theRunWorkerCompleted and ProgressChanged events. For instance, suppose we wrote a time-consuming method called GetFinancialTotals:
 public class Client  
 {  
  Dictionary <string,int> GetFinancialTotals (int foo, int bar) { ... }  
  ...  
 }  
 We could refactor it as follows:  
 public class Client  
 {  
  public FinancialWorker GetFinancialTotalsBackground (int foo, int bar)  
  {  
   return new FinancialWorker (foo, bar);  
  }  
 }  
 public class FinancialWorker : BackgroundWorker  
 {  
  public Dictionary <string,int> Result;  // You can add typed fields.  
  public readonly int Foo, Bar;  
  public FinancialWorker()  
  {  
   WorkerReportsProgress = true;  
   WorkerSupportsCancellation = true;  
  }  
  public FinancialWorker (int foo, int bar) : this()  
  {  
   this.Foo = foo; this.Bar = bar;  
  }  
  protected override void OnDoWork (DoWorkEventArgs e)  
  {  
   ReportProgress (0, "Working hard on this report...");  
   // Initialize financial report data  
   // ...  
   while (!<finished report>)  
   {  
    if (CancellationPending) { e.Cancel = true; return; }  
    // Perform another calculation step ...  
    // ...  
    ReportProgress (percentCompleteCalc, "Getting there...");  
   }  
   ReportProgress (100, "Done!");  
   e.Result = Result = <completed report data>;  
  }  
 }  
Whoever calls GetFinancialTotalsBackground then gets a FinancialWorker: a wrapper to manage the background operation with real-world usability. It can report progress, can be canceled, is friendly with WPF and Windows Forms applications, and handles exceptions well.



BackgroundWorker and ProgressBar demo

public partial class Form1 : Form   
  {   
   public Form1()   
   {   
    InitializeComponent();   
    Shown += new EventHandler(Form1_Shown);   
    // To report progress from the background worker we need to set this property   
    backgroundWorker1.WorkerReportsProgress = true;   
    // This event will be raised on the worker thread when the worker starts   
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);   
    // This event will be raised when we call ReportProgress   
    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);   
   }   
   void Form1_Shown(object sender, EventArgs e)   
   {   
    // Start the background worker   
    backgroundWorker1.RunWorkerAsync();   
   }   
   // On worker thread so do our thing!   
   void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)   
   {   
    // Your background task goes here   
    for (int i = 0; i <= 100; i++)   
    {   
     // Report progress to 'UI' thread   
     backgroundWorker1.ReportProgress(i);   
     // Simulate long task   
     System.Threading.Thread.Sleep(100);   
    }   
   }   
   // Back on the 'UI' thread so we can update the progress bar   
   void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)   
   {   
    // The progress percentage is a property of e   
    progressBar1.Value = e.ProgressPercentage;   
   }   
  }   

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code