Skip to main content
Home Forums Silverlight Programming Programming with .NET - General How do I use Linq to convert xml from a webservice to a custom class?
16 replies. Latest Post by prabakaran.sr on January 13, 2009.
(0)
jvcoacha...
Member
2 points
21 Posts
12-13-2008 9:50 PM |
I have figured out how to create an webservice that returns an xml representation of a dataset. The xml in this case is for a dataset of "Users" with 2 fields:
UserName
Password
What I can't figure out how to do is to take this in my Silverlight 2 app and take the "e.Result" and using Linq, populate a collection of "User".
I am working on this in VB.
How do I go about this?
Are there any "Imports ...." that I need to do?
Thanks for any help,
Shawn Ramirez
prujohn
Contributor
3567 points
703 Posts
12-13-2008 10:01 PM |
You'll need System.Linq and System.Xml.Linq;
Here I am converting XML into collections of class FileItemInfo and FileView. Sorry this is in c#, but you can run it through any number of available converters if you need to:
XElement file = XElement.Load(new StringReader(e.FilesAndViewsXML)); //convert the xml return into strongly typed objects var fileItemResultSet = from xq in file.DescendantsAndSelf("File") select new FileItemInfo() { FileID = new Guid(xq.Element("FileID").Value), FileName = xq.Element("FileName").Value, FileSize = Convert.ToInt32(xq.Element("FileSize").Value), Tags = xq.Element("Tags").Value, CreatedOn = DateTime.Parse(xq.Element("CreatedOn").Value), MimeType = xq.Element("MimeType").Value, LastModified = DateTime.Parse(xq.Element("LastModified").Value), LastAccessed = DateTime.Parse(xq.Element("LastAccessed").Value) }; _fileItems = fileItemResultSet.ToList(); var fileViewResultSet = from vq in file.DescendantsAndSelf("View") select new FileView() { ViewID = new Guid(vq.Element("ViewID").Value), FriendlyName = vq.Element("FriendlyName").Value, ViewQuery = vq.Element("ViewQuery").Value }; _fileViews = fileViewResultSet.ToList();
12-14-2008 9:20 PM |
Thank you, you got me part way there.
Would you be so kind as to point me to a c# -> vb.net converter that knows how to interpret Linq?
Thanks for your time.
12-14-2008 9:27 PM |
Hm I looked around a bit and converts supporting Linq seem to be a rarity. Perhaps someone on the forums here with VB skills will be kind enough to convert the example for you, or provide their own.
12-16-2008 2:57 PM |
prujohn: var fileItemResultSet = from xq in file.DescendantsAndSelf("File")
Thanks for the code. I finally found a C# => VB.Net converter that does Linq
It gave me the code but I get an error when trying to build that says
Name 'xq' is not declared.
So what is 'xq'
Thanks for your help.
Shawn
12-16-2008 3:03 PM |
Can you post me your converted code, and I'll see if I can fix it up.
12-16-2008 3:20 PM |
I finally figured it out:
Dim qryUsers = _ From p In xdoc.Elements("Users").Elements("User") _ Select New User With {.UserID = p.Element("username").Value, .Password = p.Element("password").Value}
This will do the trick.
Thanks for your time, I am greatful.
Elango.ka
Participant
816 points
146 Posts
12-18-2008 12:27 PM |
Hi, the below codes are may be help you to.
Here im also put in how to assign your list data to listbox.
In your webservice(asmx) file have a webmethod return to string at below format,<WebMethod()> _Public Function getData(ByVal CNo As string) As String Dim busobj As New BusinessLayer Dim ds As New DataSet busobj.GetDataset(CNo) Dim dt As DataTable dt = ds.Tables(0) Dim doc As XDocument = New XDocument(New XDeclaration("1,0", Nothing, Nothing), _ New XElement("EmployeeData", From c In dt Select New XElement("Employee", _ New XElement("EmpNo", c.Item(0)), _ New XElement("EmpName", c.Item(1))))) getData = doc.ToStringEnd FunctionNow you refer to your silverlight application to your webservice from localhost or where you have.Page.xaml.vb code:Imports System.XmlImports System.Xml.LinqPublic Sub LoadEmployee(Byval companyNo as integer) Dim obj As New WebRef.WebRefSoapClient 'webRef is your webservice name in SL application obj.getDataAsync(companyNo) AddHandler obj.getDataCompleted, AddressOf Me.obj_getDataCompletedEnd SubPrivate Sub obj_getDataCompleted(ByVal sender As Object, ByVal e As WebRef.getDataCompleteddEventArgs) If e.Error Is Nothing Then Dim doc As XDocument = XDocument.Parse(e.Result) Dim c = From customer In doc.Descendants("Employee") Select New EmployeeData( _ customer.Element("EmpNo"), customer.Element("EmpName")) Me.lstEmployee.ItemsSource = c End IfEnd SubEmployeeData class is; Public Class EmployeeData Private eEmpNo As Integer Private eEmpName As String Public Sub New(ByVal EmpNo As Integer, ByVal EmpName As String) Me.eEmpNo = EmpNo Me.eEmpName = EmpName End Sub Public Property EmpNo() As Integer Get Return eEmpNo End Get Set(ByVal value As Integer) eEmpNo = value End Set End Property Public Property EmpName() As String Get Return eEmpName End Get Set(ByVal value As String) eEmpName = value End Set End PropertyEnd ClassAnd Finally, your SL listbox control can bind the below xaml;<ListBox x:Name="lstEmployee" Height="35" Width="170" VerticalAlignment="Top" Margin="20,0,0,0" HorizontalAlignment="Left"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding EmpName}" FontSize="10" VerticalAlignment="Center" Foreground="Black"></TextBlock> </DataTemplate> </ListBox.ItemTemplate></ListBox>
Thanks
prabakar...
14 points
7 Posts
01-10-2009 11:32 PM |
Hi Elango,
Thanks for the information. Can you please let me know how to bing xml from a webservice to a datagrid. Please let me know some sample.
Thanks In Advance,
Prabakaran
01-12-2009 4:03 AM |
Hi Prabakaran,
The SL datagrid binding is same as listbox bind. And xaml code is just change with your datas. (if autogeneratecolumns=false) . For ex,
<data:DataGrid Height="300" Width="390" HorizontalAlignment="Left" x:Name="grdEmployee" AutoGenerateColumns="False" HeadersVisibility="Column"> <data:DataGrid.Columns> <data:DataGridTemplateColumn Header="Emp No" Width="80"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding EmpNo}" TextAlignment="Left"></TextBlock> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> <data:DataGridTemplateColumn Header="Employee Name" Width="70"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding EmployeeName}" TextAlignment="Left"></TextBlock> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid>
01-12-2009 6:09 AM |
Thank you Mr. Elango. for your information.
How to bind webservice return value to datagrid in silverlight. The webservice returns a XML string. Also i know the webservice structure. Now, Wen i call the webservice it returns some value as string. Please guide me how to bind the values to a datagrid. in vb.net
Thanks For the information Again.
Regards,
01-12-2009 6:25 AM |
Hi,
In your webservice(asmx) file have a webmethod return to string at below format,<WebMethod()> _Public Function getData(ByVal CNo As string) As String Dim busobj As New BusinessLayer Dim ds As New DataSet busobj.GetDataset(CNo) Dim dt As DataTable dt = ds.Tables(0) Dim doc As XDocument = New XDocument(New XDeclaration("1,0", Nothing, Nothing), _ New XElement("EmployeeData", From c In dt Select New XElement("Employee", _ New XElement("EmpNo", c.Item(0)), _ New XElement("EmpName", c.Item(1))))) getData = doc.ToStringEnd Function
So, Your data now in xml string
<EmployeeData><Employee><EmpNo>101</EmpNo><EmpName>Emp1</EmpName></Employee>....... </EmployeeData>
There we see the page.xaml code behind,
Page.xaml.vb code:Imports System.XmlImports System.Xml.Linq
Public Sub New() LoadEmployee() ' call the function loading employee End Sub
Public Sub LoadEmployee(Byval companyNo as integer) Dim obj As New WebRef.WebRefSoapClient ' webRef is your webservice name in SL application obj.getDataAsync(companyNo) AddHandler obj.getDataCompleted, AddressOf Me.obj_getDataCompletedEnd Sub
Now the function handler is return to your xml data. Therefore, "e.Result" is your XML string,
Private Sub obj_getDataCompleted(ByVal sender As Object, ByVal e As WebRef.getDataCompleteddEventArgs) If e.Error Is Nothing Then
Dim doc As XDocument = XDocument.Parse(e.Result) Dim c = From customer In doc.Descendants("Employee") Select New EmployeeData( _ customer.Element("EmpNo"), customer.Element("EmpName")) ' convert xml to your list data Me.grdEmployee.ItemsSource = c
End IfEnd Sub
01-12-2009 8:12 AM |
This is my vb code. Here i am getting some problem in this code. Please let me know some suggestions abt this.
Imports
===================================================
TxtTitleName.Header =
TxtAuthorColumn.Header =
TxtISBNColumn.Header =
dg.ItemsSource = GenerateData(e.Result).ToDataSource
Public Function GenerateData(ByVal ReturnXml As String) As IEnumerable(Of IDictionary)
XDoc = XDocument.Parse(ReturnXml)
title = abc.Document.Descendants(
dict.Add(abc.LastAttribute.ToString, abc.Value)
list.Add(dict)
<Extension()> _
hasData =
firstDict = currentDict
type = pair.Value.[GetType]()
CreateProperty(tb, Convert.ToString(pair.Key), type)
objectType = tb.CreateType()
getIL.Emit(OpCodes.Ldarg_0)
getIL.Emit(OpCodes.Ldfld, fieldBuilder)
getIL.Emit(OpCodes.Ret)
setIL.Emit(OpCodes.Ldarg_0)
setIL.Emit(OpCodes.Ldarg_1)
setIL.Emit(OpCodes.Stfld, fieldBuilder)
setIL.Emit(OpCodes.Ret)
propertyBuilder.SetGetMethod(getPropMthdBldr)
propertyBuilder.SetSetMethod(setPropMthdBldr)
End
01-12-2009 8:58 AM |
Hi,Private Sub BtnTest_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim WebClient As New WebClient WebClient.DownloadStringAsync(New Uri("sampleXML.xml", UriKind.RelativeOrAbsolute)) AddHandler WebClient.DownloadStringCompleted, AddressOf BindWSXml2GridEnd SubWhy you are here want to New uri, i thought you were create one xml file in your server side. We dont need to create a xml file.For ex, your webservice function have a following way<WebMethod()> _Public Function DownloadString() As String Dim busobj As New BusinessLayer Dim ds As New DataSet busobj.GetDataset() Dim dt As DataTable dt = ds.Tables(0) ' here i have my exmaple, you ll used your datas Dim doc As XDocument = New XDocument(New XDeclaration("1,0", Nothing, Nothing), _ New XElement("EmployeeData", From c In dt Select New XElement("Employee", _ New XElement("EmpNo", c.Item(0)), _ New XElement("EmpName", c.Item(1))))) 'here c.item(0) means first column of datatable, and so on... getData = doc.ToStringEnd FunctionSo, this DownloadString is return a string. Now we look at your code, Private Sub BtnTest_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim WebClient As New WebClient WebClient.DownloadStringAsync() 'no need xml file download, becoz this function return a xml string AddHandler WebClient.DownloadStringCompleted, AddressOf BindWSXml2GridEnd SubThen, BindWSXml2Grid function,Public Sub BindWSXml2Grid(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)If IsNothing(e.Error) Then ' here you are dynamically create a datagrid, just your datagrid design with xaml code. my above posts are explained that Dim doc As XDocument = XDocument.Parse(e.Result) Dim c = From customer In doc.Descendants("Employee") Select New EmployeeData( _ customer.Element("EmpNo"), customer.Element("EmpName")) ' convert xml to your list data Me.grdEmployee.ItemsSource = cEnd ifEnd subHere i have used my EmployeeData(above posts i have put this class file example also, you will used your data).Thanks
01-12-2009 9:47 AM |
I tried, what u said. But the EmployeeData class is not invoking. I am getting empty datagrid. Can you please post a sample EmployeeData class.
01-12-2009 10:11 AM |
Hi,Make sure your class properties are correct, becoz xml is case sensitive. <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding EmpName}" TextAlignment="Left"></TextBlock> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> That class is,Public Class EmployeeData Private eEmpNo As Integer Private eEmpName As String Public Sub New(ByVal EmpNo As Integer, ByVal EmpName As String) Me.eEmpNo = EmpNo Me.eEmpName = EmpName End Sub Public Property EmpNo() As Integer Get Return eEmpNo End Get Set(ByVal value As Integer) eEmpNo = value End Set End Property Public Property EmpName() As String Get Return eEmpName End Get Set(ByVal value As String) eEmpName = value End Set End PropertyEnd Class
01-13-2009 7:29 AM |
Thanks for that information.
We have got the solutions and woks fine with your best suggestion.
Need Some other Information. Earlier we where using tomcat server for the webservice. Currently we are going to work with Oracle application server.
I am trying to asscess the the web serivce which hosted in oracle application server. Once i created a service Reference with ".wsdl" file to my project. After add the service Reference i have created a object to wsdl file. But, i am unable to get the webmethod to the service reference object. Also it say's error that client access policy.xml file has to be pasted in the root directly. But we dont know what is the root directory of the oracle application server.
Link for sample: http://www.longhorncorner.com/UploadFile/john_charles/WCFandOracle04112007032407AM/WCFandOracle.aspx
But couldnt get some idea. please help me on this.
Thanks in Advance,