How to programmatically create a BasicHttpBinding?

briba picture briba · Nov 4, 2013 · Viewed 20.8k times · Source

I have to following code:

BasicHttpBinding binding = new BasicHttpBinding ();

Uri baseAddress = new Uri ("URL.svc");

EndpointAddress endpointAddress = new EndpointAddress (baseAddress);

var myChannelFactory = new ChannelFactory<IMyInterface> (binding, endpointAddress);

IMyInterface client = null;

try
{
    client = myChannelFactory.CreateChannel ();
    var a = client.WsFunction ("XXXXXX");                    
    ((ICommunicationObject)client).Close ();
}
catch
{
    if (client != null)
    {
        ((ICommunicationObject)client).Abort ();
    }
}

Where "IMyInterface" is the interface that my WS implements.. for example:

[ServiceContract]
public interface IMyInterface
{
    [OperationContract]
    Result WsFunction1 (string param);

    [OperationContract]
    Result WsFunction2 (string param);

    [OperationContract]
    Result WsFunction3 (string param);
}

And it returns something like this:

[DataContract]
public class Result
{
    string a = "";
    string b = "";

    [DataMember]
    public string A
    {
        get { return a; }
        set { a = value; }
    }

    [DataMember]
    public string B
    {
        get { return b; }
        set { b = value; }
    }
}

When I run this code, I can reach the WS, but I can never get the Result filled out.

What am I doing wrong?

Thanks in advance!

Answer

Millie Smith picture Millie Smith · Nov 4, 2013

The easiest way to access a service via a BasicHttpBinding is to generate the client code from SlSvcUtil.exe, which is a silverlight utility application.

SLsvcUtil.exe /directory:C:\users\me\Desktop http://URL.svc

That should create a MyInterfaceClient class inside of the file it generates.

Then in your code you can do:

var binding = new BasicHttpBinding() {
    Name = "BindingName",
    MaxBufferSize = 2147483647,
    MaxReceivedMessageSize = 2147483647
};

var endpoint = new EndpointAddress("URL.svc");

MyInterfaceClient client = new MyInterfaceClient(binding, endpoint);

client.WSFunctionCompleted += (object sender, WSFunctionCompletedEventArgs e) => {
    //access e.Result here
};

client.WSFunctionAsync("XXXXXX");

Your mileage may vary. Let me know if this works.