.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> Silverlight >> Post New Resource Bookmark and Share   

 Subscribe to Articles

How to bind XML file as collection of object in Silverlight using WCF service

Posted By:Vishal Nayan       Posted Date: April 06, 2011    Points: 200    Category: Silverlight    URL: http://www.dotnetspark.com  

Binding to a single object is straight forward, but practically we are more interested in binding to a collection object say like, all employee in a table. Dependency property supports the single value binding, so binding to collection of object had to be dealt with little more sophistication. Any control which support list of items is derived from items control so to support collection binding, itemscontrol class defines some properties.
 

Introduction:

Binding to a single object is straight forward, but practically we are more interested in binding to a collection object say like, all employee in a table. Dependency property supports the single value binding, so binding to collection of object had to be dealt with little more sophistication. Any control which support list of items is derived from items control so to support collection binding, itemscontrol class defines some properties.

What are these properties?


1) ItemsSource: it point to collection which has all the objects that will be shown in the list

2) ItemTemplate: it provides the datatemplate that will be used to create the visual appearance of each item.

3) ItemsPanel: It provides a template that will be used create the layout container that holds all the items in the list.

4) DisplayMem berPath: it identifies the property that will be used to create the display text for each item.

Ok, so let us create a sample project to demonstrate binding of collection object.

Step 1: Create a Silverlight application project let's say "CollectionBindingByService"

Step2:
Add an xml file for data storage to CollectionBindingByService.Web project and name is store.xml.



Step 3:
I have inserted some data into it with data nodes like below ;


  355
  16
  RU007
  Rain Racer 2000
  image.gif
  1499.9900
  Looks like an ordinary bumbershoot, but don't be fooled! Simply place Rain Racer's tip on the ground and press the release latch. Within seconds, this ordinary rain umbrella converts into a two-wheeled gas-powered mini-scooter. Goes from 0 to 60 in 7.5 seconds - even in a driving rain! Comes in black, blue, and candy-apple red.
  16
  Travel


Step 4:
Add a WCF service svc file. Name is StoreDb.svc

Step 5:
Now add a class say  Product.cs where we wil define our property.

Below is code of our product class with variables and property declared . note we have inherited our class with INotifyPropertyChanged
[DataContract()]
public class Product : INotifyPropertyChanged
{
    private bool hasChanges = false;
    public bool HasChanges
    {
        get { return hasChanges; }
        set { hasChanges = value; }
    }
    private string modelNumber;
    [DataMember()]
    public string ModelNumber
    {
        get { return modelNumber; }
        set
        {
            modelNumber = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ModelNumber"));
        }
    }
    private string modelName;
    [DataMember()]
    public string ModelName
    {
        get { return modelName; }
        set
        {
            modelName = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ModelName"));
        }
    }
    private double unitCost;
    [DataMember()]
    public double UnitCost
    {
        get { return unitCost; }
        set
        {
            unitCost = value;
            OnPropertyChanged(new PropertyChangedEventArgs("UnitCost"));
        }
    }
    private string description;
    [DataMember()]
    public string Description
    {
        get { return description; }
        set
        {
            description = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Description"));
        }
    }
    private string categoryName;
    [DataMember()]
    public string CategoryName
    {
        get { return categoryName; }
        set { categoryName = value; }
    }
    private string productImagePath;
    [DataMember()]
    public string ProductImagePath
    {
        get { return productImagePath; }
        set { productImagePath = value; }
    }
    public Product(string modelNumber, string modelName,
    double unitCost, string description)
    {
        ModelNumber = modelNumber;
        ModelName = modelName;
        UnitCost = unitCost;
        Description = description;
    }
    public Product(string modelNumber, string modelName,
    double unitCost, string description,
    string productImagePath)
        :
        this(modelNumber, modelName, unitCost, description)
    {
        ProductImagePath = productImagePath;
    }
    public Product(string modelNumber, string modelName,
    double unitCost, string description, string categoryName,
    string productImagePath) :
        this(modelNumber, modelName, unitCost, description)
    {
        CategoryName = categoryName;
        ProductImagePath = productImagePath;
    }
    public Product() { }
    public override string ToString()
    {
        return ModelName + " (" + ModelNumber + ")";
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, e);
    }
}


We have created our servcie contract with AspNet compability requirement mode to Allowed. Now we need to create operation contract i.e. methods.
Before that in svc page contructor , we will load XML file into our dataset ,like below;

DataSet ds = new DataSet();
public StoreDb()
{
    ds.ReadXml(HttpContext.Current.Server.MapPath("store.xml");
}


Now we will create a method which will return product detail when any product id is provided by cleint.

    [OperationContract]
    public Product GetProduct(int ID)
    {
        DataRow productRow = ds.Tables["Products"].Select("ProductID = " + ID.ToString())[0];
        Product product = new Product((string)productRow["ModelNumber"],
        (string)productRow["ModelName"], Convert.ToDouble(productRow["UnitCost"]),
        (string)productRow["Description"], (string)productRow["CategoryName"],
        (string)productRow["ProductImage"]);
        return product;
    }


Now we will create a method which will return product detail for all products.

[OperationContract()]
public List GetProducts()
{
    List products = new List();
    foreach (DataRow productRow in ds.Tables["Products"].Rows)
    {
        products.Add(new Product((string)productRow["ModelNumber"],
        (string)productRow["ModelName"], Convert.ToDouble(productRow["UnitCost"]),
        (string)productRow["Description"], (string)productRow["CategoryName"],
        (string)productRow["ProductImage"]));
    }
    return products;
}


Step 7:
build CollectionBindingByService.Web and open web.config file , you will see visual studio has wcf hadautomatically configured it.


  
    
      
        
        
      
    
  
  
  
    
      
      
    
  


Step 8:
Now Set CollectionBindingByService.Web as start up project and press F5. Come to CollectionBindingByService project and click to add service reference.



Step 9:
Come back to CollectionBindingByService project and add a user control ,name is ProductFromService.xaml
Now here we wil create a XAML interface to display data by accessing wcf service.



When you look into XAML for this , notice the code for listbox

Here I have used DisplayMemberPath ,which create the display text for each item.
You can see in this interface we have a listbox for displaying all product names. Three buttons for getting product details , adding and deleting them as well. We have option to fetch product detail by providing product id.

Step 10:
Lets write code for GetProduct , which wil fetch all product name in listbox.
Now Open ProductFromService.xmal.cs and add this namespace
using CollectionBindingByService.ProductService;
At first we need to create a observable collection object.

    private ObservableCollection products = new ObservableCollection();
    private void btnGetProduct_Click(object sender, RoutedEventArgs e)
    {
        EndpointAddress address = new EndpointAddress("http://localhost:" +
        HtmlPage.Document.DocumentUri.Port + "/CollectionBindingByService.Web/StoreDb.svc");
        StoreDbClient client = new StoreDbClient(new BasicHttpBinding(), address);
        client.GetProductsCompleted += new EventHandler(client_GetProductsCompleted);
        client.GetProductsAsync();
    }
    void client_GetProductsCompleted(object sender, GetProductsCompletedEventArgs e)
    {
        try
        {
            products.Clear();
            foreach (Product product in e.Result) products.Add(product);
            lstProduct.ItemsSource = products;
        }
        catch
        {
            lblError.Text = "Failed to contact service.";
        }
    }


When the user clicks the Get Products button, the event-handling code calls the GetProducts () method asynchronously:
When the product list is received from the web service, the code stores the collection as a member variable in the page class for easier access elsewhere in your code. The code then sets that collection as the ItemsSource for the list:

Step 11:
Set CollectionBindingByService.Web as start up project and Press F5, and click on get product, you will see below like result.



Step 12: Click on any product item , you will notice that textboxes get populated respectively.
Here we are using datacontext of higest layout control , i.e. grid here, to bind the data. For textboxes we have just used binding expression like below;
Text="{Binding Description, Mode=TwoWay}">

    private void lstProduct_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        gridProductDetails.DataContext = lstProduct.SelectedItem;
    }




Step 13:
Now let us test for Product ID, say 365. Here we are calling GetProductID operation contract.



Step 14: Now let us try to add any item.
It is quite simple, we need to create an object of class product and then add it into listbox. See the code below;

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        Product p = new Product();
        p.ModelName = "New Product";
        products.Add(p);
        lstProduct.SelectedItem = p;
        lstProduct.UpdateLayout();
        lstProduct.ScrollIntoView(p);
    }




Step 15: Now let us try to delete any item.

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
products.Remove((Product)lstProduct.SelectedItem);
}

Here we are removing that selected product from product observable object.

Cool, isn't. So we saw how to display, add and delete collection items.

Hope you enjoyed reading. Cheers

 Subscribe to Articles

     

Further Readings:

Responses
Author: Amit Mehra         Company URL: http://www.dotnetspark.com
Posted Date: April 06, 2011

Great job Vishal..Keep it up...
Author: Vishal Nayan         Company URL: http://www.dotnetspark.com
Posted Date: April 07, 2011

Thanks Amit

Regards.

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend