Fuzz
Fuzz

Reputation: 947

How to correctly use soap webservice client in c#

I am new to c# and trying to consume a SOAP web service, I generated a service reference to the WSDL and am able to do the following to retrieve a DataSet of the response.

SportingGatewaySoapClient myServices = new SportingGatewaySoapClient("GatewaySoapID");

RSportResults sportsResults = myServices.SportResults("username","password");
System.Data.DataSet dataSet = sportsResults.dsSportResults;

I am able to see the correct information if I iterate through the dataset like you would normally :

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            Console.WriteLine(item);
        }
    }
}

But I am failing to see how I can Unmarshall the data directly into the generated classes so I can reference its properties by name. eg :

 // some code here to convert response to a Sport object
 sport.getSportName()

The auto generated Reference.cs file has classes like this :

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.3056.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="https://endpointurl")]
public partial class RSport : object, System.ComponentModel.INotifyPropertyChanged {

    private string sportName;

What step am I missing here?

Upvotes: 1

Views: 696

Answers (1)

Antoine V
Antoine V

Reputation: 7204

Your WCF return a DataSet which contains the RSport objects.

So the idea to create an extension for DataTable. This extension using Reflection will convert each row into an instance of given type

public static class DataTableExtensions
{
    public static IList<T> ToList<T>(this DataTable table) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        IList<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }


    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            property.SetValue(item, row[property.Name], null);
        }
        return item;
    }
}

Next, you convert your datatable like this

System.Data.DataSet dataSet = sportsResults.dsSportResults;
var rs = dataSet.Tables[0].ToList<RSport>();

That is the way to fetch the data

Upvotes: 1

Related Questions