//
you're reading...
Silverlight 3, WCF

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

Problem viewing , read/download full pdf version of article here

Subscribe /email your mailing id at vishalnayan@gmail.com for sample project.

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 ;

<Products>

<ProductID>355</ProductID>

<CategoryID>16</CategoryID>

<ModelNumber>RU007</ModelNumber>

<ModelName>Rain Racer 2000</ModelName>

<ProductImage>image.gif</ProductImage>

<UnitCost>1499.9900</UnitCost>

<Description>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.</Description>

<CategoryID1>16</CategoryID1>

<CategoryName>Travel</CategoryName>

</Products>

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);

}

}

Step 6: Open StoreDb.svc.cs and write code to read XML data store and here now we will define our service contract.

[ServiceContract]

[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]

public class StoreDb

{

}

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<Product> GetProducts()

{

List<Product> products = new List<Product>();

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.

<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior name=”StoreDbBehavior”>

<serviceMetadata httpGetEnabled=”true”/>

<serviceDebug includeExceptionDetailInFaults=”false”/>

</behavior>

</serviceBehaviors>

</behaviors>

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true”/>

<services>

<service behaviorConfiguration=”StoreDbBehavior” name=”StoreDb”>

<endpoint address=”” binding=”basicHttpBinding” contract=”StoreDb”/>

<endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange”/>

</service>

</services>

</system.serviceModel>

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

<ListBox x:Name=”lstProduct” Margin=”5″ DisplayMemberPath=”ModelName”                     SelectionChanged=”lstProduct_SelectionChanged”></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<Product> products = new ObservableCollection<Product>();

private void btnGetProduct_Click(object sender, RoutedEventArgs e)

{

EndpointAddress address = new EndpointAddress(“http://localhost:&#8221; +

HtmlPage.Document.DocumentUri.Port + “/CollectionBindingByService.Web/StoreDb.svc”);

StoreDbClient client = new StoreDbClient(new BasicHttpBinding(), address);

client.GetProductsCompleted += new EventHandler<GetProductsCompletedEventArgs>(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

Problem viewing , read/download full pdf version of article here

Subscribe /email your mailing id @ vishalnayan@gmail.com for sample project.


Advertisements

About Vishal

Vishal Nayan is a seasoned professional with hand on Experience on Mircrosoft Technologies. He always look for challenging IT position that allows him to learn new Microsoft Technologies while utilizing experience of Project Development and Software Engineering Ethics. A MCP in WCF ,and looking forward for more.

Discussion

5 thoughts on “How to bind XML file as collection of object in Silverlight using WCF service

  1. Hi, Nice post,
    but i think that it would just lead to unnecessary overhead.
    We can directly use LINQ to parse xml and get collection instead of calling wcf service (unnecessary overhead ,even wcf call is async).

    Posted by Abhishek Gahlout | 2012/08/21, 5:35 PM
  2. First of all I want to say superb blog! I
    had a quick question that I’d like to ask if you do not mind. I was curious to know how you center yourself and clear your mind prior to writing. I have had a difficult time clearing my mind in getting my thoughts out there. I do take pleasure in writing however it just seems like the first 10 to 15 minutes tend to be lost simply just trying to figure out how to begin. Any suggestions or tips? Appreciate it!

    Posted by http://Monstars.de/penguin-girl/penguin-girl-ruft-hallo | 2013/02/14, 6:42 AM
  3. Awesome things here. I am very satisfied to look your article.

    Thank you so much and I’m taking a look ahead to touch you. Will you please drop me a e-mail?

    Posted by black denim skirt knee length | 2013/08/10, 10:19 PM
  4. What i do not realize is iin reality how you are now not actually a lot more well-favored
    than you may be now. You are very intelligent. You know thus siognificantly relating to this topic, produced me for my part consider it
    from so many numerous angles. Its like men and women aren’t interested except
    it’s one thing to accomplish with Woman gaga! Your own stuffs nice.
    All the time maintain it up!

    Posted by Terrell | 2014/05/21, 12:59 PM

Trackbacks/Pingbacks

  1. Pingback: DotNetShoutout - 2011/04/07

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow Vishalnayan on WordPress.com

Blog Stats

  • 214,547 hits
%d bloggers like this: