Friday 21 October 2011

RESTful WCF Services

RESTful WCF Services


Hi friends,

I have already  discussed REST ful services in earlier Post .But today in this article I am discussing details of RESTful Services
I am covering following topics in this article
1. Introduction
2. Differnce between normal WCF service and RESTful WCF Service
3. Where to Use RESTful WCF Service
4. Creation of RESTful WCF Service
5. Testing RESTful WCF Service
6. Summary



1. Introduction

WCF means Window communication Foundation which is introduced in .net framework 3.0. Before WCF there is webservice is famous for communication.

RESTful Service means Representational State Transfer (REST),

2. Differnce between normal WCF service and RESTful WCF Service

There is no more difference between WCF service and REST service only main difference is that How Client accesses our Service.
 Normal WCF service runs on the SOAP format but when we create REST service then client can access your service in different architecture style like JSON

REST uses4 HTTP methods to insert/delete/update/retrieve information which is below:
  1. GET - Retrive a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource
3. Where to Use RESTful WCF Service
There are some scenario’s where we can use RESTful service like
  1. Less Overhead because there is no use of SOAP object
  2. Testing is very easy
  3. Standardization is very nice

4. Creation of RESTful WCF Service
Step1.
Create a new WCF project in VS 2008/20010

Step 2:

Delete a Service Model node from Web.config

Step 3.

Build the Solution then   Right click on the svc file and Click on View Markup button
And add following code to the markup

Factory="System.ServiceModel.Activation.WebServiceHostFactory"

Step 4
Add following references to the WCF Service Application project, if you are using VS2010
Microsoft.Http.dll
Microsoft.Http.Extension.dll
System.ServiceModel.Web.dll


Step 5
  [ServiceContract]
    public interface IService1
    {

        [OperationContract(Name = " AddTwoNumber ")]
        [WebInvoke(UriTemplate = "/", Method = "POST")]
         int AddTwoNumber(int i, int j);

       

        [OperationContract(Name = " SubTwoNumber")]
        [WebGet(UriTemplate = "/")]
        int SubTwoNumber(int i, int j);

      
    }

Add your code in your service like here I have created 2 methods like AddTwonumber which takes two parameter I and j
In the above code we use
WebInvoke :- means invoke web method

Webinvoke takes Two parameters like
1. Method Type there are 4 types of method
a.Post      C.Invoke
b.Get       d.Delete
2. UriTemplate = "/ADD” tells  what would be URI for this particular method


Like this we can create RESTful service .

In the above article we studied all the basic details of restful service .

In the next article I will tell you details for Restful service
Thanks friends.





Monday 3 October 2011

Attached Property in Silverlight 4.0

Hi Friends,

In this article you will learn attached property in silverlight 4.0
There are two types of properties in Silverlight
1.     Dependency Property:  In the last article you learn dependency property briefly
2.   Attached Property: In this article you will learn briefly attached property.

In this article I will cover following topics about attached property
1.     Introduction of attached property
2.    What is attached property?
3.     Why we need attached property?
4.    How to register custom attached property in silverlight
5.     Some Attached properties in silverlight



  1. Introduction of attached property

An attached property is a new concept that is defined by Extensible Application Markup Language (XAML). The attached properties are intended to be used as global properties that are settable on any type of object. In WPF/Silverlight, attached properties are typically defined as a form of a dependency property that does not have the conventional property 'wrapper'.
           
2. What is attached Property??

Attached properties are a specialized type of dependency property that is immediately
recognizable in markup due to the TypeName.AttachedPropertyName syntax. For example,
Canvas.Left is an attached property defined by the Canvas type. What makes
attached properties interesting is that they’re not defined by the type you use them
with; instead, they’re defined by another type in a potentially different class hierarchy.
Attached properties allow flexibility when defining classes because the classes
don’t need to take into account every possible scenario in which they’ll be used and
define properties for those scenarios. Layout is a great example of this. The flexibility
of the Silverlight layout system allows you to create new panels that may never have
been implemented in other technologies—for example, a panel that lays elements out
by degrees and levels in a circular or radial fashion versus something like the built-in
Canvas that lays elements out by Left and Top positions.

3.   3.   Why we need attached properties?

The attached properties are a very powerful tool for dynamic extension of classes without inheritance. They also allow us to keep the properties located at their logical places – use what you need only when you need it. Moreover they allow the place, where the property is defined and the place, where it is stored, to be completely different classes that know nothing about each other. Like in the above example the Dock property value is stored in the button instance not in the DockPanel itself.
With the attached properties you can make your classes structure much more comprehensible for the developer by using only the properties that are valid in the specific context.

The good news is that many advantages from the dependency properties model are coming out of the box for the attached properties such as caching, data binding, default values, expressions, styling (which is nothing more than a set of predefined property values), property invalidation and more.




4.  How to create Attached property with example

1. Declare the attached property as static and readonly field in your class.

public static readonly DependencyProperty DockProperty = DependencyProperty.RegisterAttached
(“Dock”, // property name
typeof(Dock), // property type
typeof(DockPanel), // type of the property provider
new PropertyMetadata(Dock.Left, new PropertyChangedCallback(DockPanel.OnDockChanged))); // Property Metadata


2. Create GetDock and SetDock methods that are associated to the attached property.


public static Dock GetDock(UIElement element)
{
   if (element == null)
   {
      throw new ArgumentNullException(“element”);
   }
  
   return (Dock)element.GetValue(DockProperty);
}

public static void SetDock(UIElement element, Dock dock)
{
   if (element == null)
   {
      throw new ArgumentNullException(“element”);
   }
   element.SetValue(DockProperty, dock);
}


3. Create a callback method invoked when the property value is changed.


private static void OnDockChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
   // Do something when the property is changed.

   UIElement reference = d as UIElement;
   if (reference != null)
   {

   }
}


The following example code demonstrates how to set the attached property in the xaml markup:


<Button  x:Name=”Item1″  Text=”Item1″  DockPanel.Dock=”Top”/>


The code assumes that the Dock property is an attached property declared in the DockPanel class. 



5.    5.   List of some attached properties in Silverlight

Below you can find a list of some of the attached properties available in .NET Framework. This list is a short reference that was not meant to be complete. I decided to put it here to give you an idea about the way Microsoft uses the attached properties.
Canvas.Top – Define the distance for a control from the top edge of its container;
Canvas.Left – Define the distance for a control from the left edge of its container;
Canvas.ZIndex – Z Index of the control;
Grid.Row – Define the row index for a control placed in a Grid container;
Grid.Column – Define the row index for a control placed in a Grid container;
ScrollViewer.HorizontalScrollBarVisibility – Define the visibility of the horizontal scrollbar;
ScrollViewer.VerticalScrollBarVisibility – Define the visibility of the vertical scrollbar;
ToolTipService.ToolTip – Define the tool tip associated with a control;
and many more….


Hi friends In the next article you will learn routed events briefly .................


Dependency Properties

Hi Friends,
In Silverlight there are some topics are very important but never used in real applications Such as
  1. Dependency Property
  2. Routed Events
  3. Attached Property
  4. Custom Control
In this article I am giving brief description of dependency property means
  1. What are dependency properties?
  2. Creating Dependency Properties?
  3. How to use dependency properties?
What are Dependency Properties?
              In silverlight application all the UI made up of XAML. XAML provides a great way to define layout controls, user input controls, shapes, colors and data binding expressions in a declarative manner. There’s a lot that goes on behind the scenes in order to make XAML work and an important part of that magic is the use of dependency properties. If you want to bind data to a property, style it, animate it or transform it in XAML then the property involved has to be a dependency property to work properly. If you’ve ever positioned a control in a Canvas using Canvas.Left or placed a control in a specific Grid row using Grid.Row then you’ve used an attached property which is a specialized type of dependency property. Dependency properties play a key role in XAML and the overall Silverlight framework.
Any property that you bind, style, template, animate or transform must be a dependency property in Silverlight applications. You can programmatically bind values to controls and work with standard CLR properties, but if you want to use the built-in binding expressions available in XAML (one of my favorite features) or the Binding class available through code then dependency properties are a necessity. Dependency properties aren’t needed in every situation, but if you want to customize your application very much you’ll eventually end up needing them. For example, if you create a custom user control and want to expose a property that consumers can use to change the background color, you have to define it as a dependency property if you want bindings, styles and other features to be available for use. Now that the overall purpose of dependency properties has been discussed let’s take a look at how you can create them.
Creating Dependency Properties
        When .NET first came out you had to write backing fields for each property that you defined as shown next:
Brush _ScheduleBackground;

public Brush ScheduleBackground
{

    get { return _ScheduleBackground; }
    set { _ScheduleBackground = value; }

}
Although .NET 2.0 added auto-implemented properties (for example: public Brush ScheduleBackground { get; set; }) where the compiler would automatically generate the backing field used by get and set blocks, the concept is still the same as shown in the above code; a property acts as a wrapper around a field. Silverlight dependency properties replace the _ScheduleBackground field shown in the previous code and act as the backing store for a standard CLR property.
The following code shows an example of defining a dependency property named ScheduleBackgroundProperty:
public static readonly DependencyProperty ScheduleBackgroundProperty =
  DependencyProperty.Register("ScheduleBackground", typeof(Brush),
  typeof(Scheduler), null);

Looking through the code the first thing that may stand out is that the definition for ScheduleBackgroundProperty is marked as static and readonly and that the property appears to be of type DependencyProperty. This is a standard pattern that you’ll use when working with dependency properties. You’ll also notice that the property explicitly adds the word “Property” to the name which is another standard you’ll see followed. In addition to defining the property, the code also makes a call to the static DependencyProperty.Register method and passes the name of the property to register (ScheduleBackground in this case) as a string. The type of the property, the type of the class that owns the property and a null value (more on the null value later) are also passed. In this example a class named Scheduler acts as the owner.
The code handles registering the property as a dependency property with the call to Register(), but there’s a little more work that has to be done to allow a value to be assigned to and retrieved from the dependency property. The following code shows the complete code that you’ll typically use when creating a dependency property. You can find code snippets that greatly simplify the process of creating dependency properties out on the web. The MVVM Light download available from http://mvvmlight.codeplex.com comes with built-in dependency properties snippets as well.
public static readonly DependencyProperty ScheduleBackgroundProperty =
  DependencyProperty.Register("ScheduleBackground", typeof(Brush),
  typeof(Scheduler), null);

public Brush ScheduleBackground
{
    get { return (Brush)GetValue(ScheduleBackgroundProperty); }
    set { SetValue(ScheduleBackgroundProperty, value); }
}
The standard CLR property code shown above should look familiar since it simply wraps the dependency property. However, you’ll notice that the get and set blocks call GetValue and SetValue methods respectively to perform the appropriate operation on the dependency property. GetValue and SetValue are members of the DependencyObject class which is another key component of the Silverlight framework. Silverlight controls and classes (TextBox, UserControl, CompositeTransform, DataGrid, etc.) ultimately derive from DependencyObject in their inheritance hierarchy so that they can support dependency properties.
Dependency properties defined in Silverlight controls and other classes tend to follow the pattern of registering the property by calling Register() and then wrapping the dependency property in a standard CLR property (as shown above). They have a standard property that wraps a registered dependency property and allows a value to be assigned and retrieved. If you need to expose a new property on a custom control that supports data binding expressions in XAML then you’ll follow this same pattern. Dependency properties are extremely useful once you understand why they’re needed and how they’re defined.
How to use Dependency Proprties
           When working with dependency properties there will be times when you want to assign a default value or detect when a property changes so that you can keep the user interface in-sync with the property value. Silverlight’s DependencyProperty.Register() method provides a fourth parameter that accepts a PropertyMetadata object instance. PropertyMetadata can be used to hook a callback method to a dependency property. The callback method is called when the property value changes. PropertyMetadata can also be used to assign a default value to the dependency property. By assigning a value of null for the final parameter passed to Register() you’re telling the property that you don’t care about any changes and don’t have a default value to apply.
Here are the different constructor overloads available on the PropertyMetadata class:
PropertyMetadata Constructor Overload
Description
PropertyMetadata(Object)
Used to assign a default value to a dependency property.
PropertyMetadata(PropertyChangedCallback)
Used to assign a property changed callback method.
PropertyMetadata(Object, PropertyChangedCalback)
Used to assign a default property value and a property changed callback.

There are many situations where you need to know when a dependency property changes or where you want to apply a default. Performing either task is easily accomplished by creating a new instance of the PropertyMetadata class and passing the appropriate values to its constructor. The following code shows an enhanced version of the initial dependency property code shown earlier that demonstrates these concepts:
public Brush ScheduleBackground
{
    get { return (Brush)GetValue(ScheduleBackgroundProperty); }
    set { SetValue(ScheduleBackgroundProperty, value); }
}

public static readonly DependencyProperty ScheduleBackgroundProperty =

DependencyProperty.Register("ScheduleBackground", typeof(Brush),
  typeof(Scheduler), new PropertyMetadata(new SolidColorBrush(Colors.LightGray),
  ScheduleBackgroundChanged));

private static void ScheduleBackgroundChanged(DependencyObject d,
  DependencyPropertyChangedEventArgs e)
{
    var scheduler = d as Scheduler;
    scheduler.Background = e.NewValue as Brush;
}
The code wires ScheduleBackgroundProperty to a property change callback method named ScheduleBackgroundChanged. What’s interesting is that this callback method is static (as is the dependency property) so it gets passed the instance of the object that owns the property that has changed (otherwise we wouldn’t be able to get to the object instance). In this example the dependency object is cast to a Scheduler object and its Background property is assigned to the new value of the dependency property. The code also handles assigning a default value of LightGray to the dependency property by creating a new instance of a SolidColorBrush.
What you learn in this post
In this post you’ve seen the role of dependency properties and how they can be defined in code. They play a big role in XAML and the overall Silverlight framework. You can think of dependency properties as being replacements for fields that you’d normally use with standard CLR properties. In addition to a discussion on how dependency properties are created, you also saw how to use the PropertyMetadata class to define default dependency property values and hook a dependency property to a callback method.
The most important thing to understand with dependency properties (especially if you’re new to Silverlight) is that they’re needed if you want a property to support data binding, animations, transformations and styles properly. Any time you create a property on a custom control or user control that has these types of requirements you’ll want to pick a dependency property over of a standard CLR property with a backing field.
In the next article you will learn Attached properties...