how to bind xml file as collection of object in silverlight

13
How to bind XML file as collection of object in Silverlight using WCF service 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 “CollectionBindingByServiceStep2: Add an xml file for data storage to CollectionBindingByService.Web project and name is store.xml.

Upload: others

Post on 04-Feb-2022

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: How to bind XML file as collection of object in Silverlight

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

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.

Page 2: How to bind XML file as collection of object in Silverlight

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.

Page 3: How to bind XML file as collection of object in Silverlight

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

Page 4: How to bind XML file as collection of object in Silverlight

{

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

{

Page 5: How to bind XML file as collection of object in Silverlight

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=AspNetCompatibilityRequirem

entsMode.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;

}

Page 6: How to bind XML file as collection of object in Silverlight

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.

Page 7: How to bind XML file as collection of object in Silverlight

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.

Page 8: How to bind XML file as collection of object in Silverlight

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.

Page 9: How to bind XML file as collection of object in Silverlight

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:"

+

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.";

}

}

Page 10: How to bind XML file as collection of object in Silverlight

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}">

Page 11: How to bind XML file as collection of object in Silverlight

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.

Page 12: How to bind XML file as collection of object in Silverlight

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

}

Page 13: How to bind XML file as collection of object in Silverlight

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