How to create a WCF client without settings in config file? - wcf

I just start work on WCF a month ago. Please forgive me if I ask something already answered. I try to search first but found nothing.
I read this article, WCF File Transfer: Streaming & Chunking Channel Hosted In IIS. It works great. Now I like to integrate client side code to be part of my application, which is a dll running inside AutoCAD. If I want to work with config file, I have to change acad.exe.config which I don't think is a good idea. So I think if it possible, I want to move all code in config file to code.
Here is config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Mtom" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService"
contract="MGFileServerClient.IService"
name="BasicHttpBinding_IService" />
</client>
</system.serviceModel>
Could you please help me to make this change?

You can do all the setting up from within code, assuming that you don't need the flexibility to change this in the future.
You can read about setting up the endpoint on MSDN. Whilst this applies to the server the configuration of the endpoint and bindingd apply to the client as well, its just that you use the classes differently.
Basically you want to do something like:
// Specify a base address for the service
EndpointAddress endpointAdress = new EndpointAddress("http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1");
// Create the binding to be used by the service - you will probably want to configure this a bit more
BasicHttpBinding binding1 = new BasicHttpBinding();
///create the client proxy using the specific endpoint and binding you have created
YourServiceClient proxy = new YourServiceClient(binding1, endpointAddress);
Obviously you'll probably want to configure the binding with security, timeouts etc the same as your config above (you can read about the BasicHttpBinding on MSDN), but this should get you going in the right direction.

This is totally code based configuration and working code. You dont need any configuration file for client. But at least you need one config file there (may be automatically generated, you dont have to think about that). All the configuration setting is done here in code.
public class ValidatorClass
{
WSHttpBinding BindingConfig;
EndpointIdentity DNSIdentity;
Uri URI;
ContractDescription ConfDescription;
public ValidatorClass()
{
// In constructor initializing configuration elements by code
BindingConfig = ValidatorClass.ConfigBinding();
DNSIdentity = ValidatorClass.ConfigEndPoint();
URI = ValidatorClass.ConfigURI();
ConfDescription = ValidatorClass.ConfigContractDescription();
}
public void MainOperation()
{
var Address = new EndpointAddress(URI, DNSIdentity);
var Client = new EvalServiceClient(BindingConfig, Address);
Client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
Client.Endpoint.Contract = ConfDescription;
Client.ClientCredentials.UserName.UserName = "companyUserName";
Client.ClientCredentials.UserName.Password = "companyPassword";
Client.Open();
string CatchData = Client.CallServiceMethod();
Client.Close();
}
public static WSHttpBinding ConfigBinding()
{
// ----- Programmatic definition of the SomeService Binding -----
var wsHttpBinding = new WSHttpBinding();
wsHttpBinding.Name = "BindingName";
wsHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1);
wsHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1);
wsHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
wsHttpBinding.SendTimeout = TimeSpan.FromMinutes(1);
wsHttpBinding.BypassProxyOnLocal = false;
wsHttpBinding.TransactionFlow = false;
wsHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
wsHttpBinding.MaxBufferPoolSize = 524288;
wsHttpBinding.MaxReceivedMessageSize = 65536;
wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;
wsHttpBinding.TextEncoding = Encoding.UTF8;
wsHttpBinding.UseDefaultWebProxy = true;
wsHttpBinding.AllowCookies = false;
wsHttpBinding.ReaderQuotas.MaxDepth = 32;
wsHttpBinding.ReaderQuotas.MaxArrayLength = 16384;
wsHttpBinding.ReaderQuotas.MaxStringContentLength = 8192;
wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 4096;
wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;
wsHttpBinding.ReliableSession.Ordered = true;
wsHttpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
wsHttpBinding.ReliableSession.Enabled = false;
wsHttpBinding.Security.Mode = SecurityMode.Message;
wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
wsHttpBinding.Security.Transport.Realm = "";
wsHttpBinding.Security.Message.NegotiateServiceCredential = true;
wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
// ----------- End Programmatic definition of the SomeServiceServiceBinding --------------
return wsHttpBinding;
}
public static Uri ConfigURI()
{
// ----- Programmatic definition of the Service URI configuration -----
Uri URI = new Uri("http://localhost:8732/Design_Time_Addresses/TestWcfServiceLibrary/EvalService/");
return URI;
}
public static EndpointIdentity ConfigEndPoint()
{
// ----- Programmatic definition of the Service EndPointIdentitiy configuration -----
EndpointIdentity DNSIdentity = EndpointIdentity.CreateDnsIdentity("tempCert");
return DNSIdentity;
}
public static ContractDescription ConfigContractDescription()
{
// ----- Programmatic definition of the Service ContractDescription Binding -----
ContractDescription Contract = ContractDescription.GetContract(typeof(IEvalService), typeof(EvalServiceClient));
return Contract;
}
}

Are you looking to retain your custom config and reference it within your application? You may try this article: Reading WCF Configuration from a Custom Location (In regards to WCF)
Otherwise, you can use ConfigurationManager.OpenExeConfiguration.

Related

Transport level security in an intranet Silverlight 5 application

I am implementing transport level security in an intranet Silverlight 5 application.
Binding used is custom netTcpBinding and on server end I have enabled security with below settings and PrincipalPermission.
<customBinding>
<binding closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="02:00:00" sendTimeout="00:05:00">
<binaryMessageEncoding maxSessionSize="1000000">
<readerQuotas maxDepth="64" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="16384" maxNameTableCharCount="16384" />
</binaryMessageEncoding>
<windowsStreamSecurity protectionLevel="EncryptAndSign"/>
<tcpTransport portSharingEnabled="false" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
When my client is a normal c# console app and proxy created using channel fatory everything works fine.
var tcpBinding = new CustomBinding();
tcpBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
var windowsStreamSecurityBindingElement=new WindowsStreamSecurityBindingElement();
windowsStreamSecurityBindingElement.ProtectionLevel= System.Net.Security.ProtectionLevel.EncryptAndSign;
tcpBinding.Elements.Add(windowsStreamSecurityBindingElement);
tcpBinding.Elements.Add(new TcpTransportBindingElement { MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue });
tcpBinding.ReceiveTimeout = new TimeSpan(6, 0, 0);
tcpBinding.SendTimeout = new TimeSpan(0, 30, 0);
tcpBinding.ReceiveTimeout = TimeSpan.FromDays(1);
var proxy = new ChannelFactoryServiceWrapper<IHello>(#"net.tcp://XYZ.globaltest.ABC.com:5580/Hello/tcp", tcpBinding).Channel;
var ping = proxy.Ping();
On client(Silverlight 5) I am using same above piece of code but it’s giving compile time error since WindowsStreamSecurityBindingElement is not available in Silverlight 5.
Please tell me any alternative for this.

WCF service on ServiceBus fails if call longer than 1 minute

I have a WCF Service that is hosted in a ServiceHost object. The ServiceHost is created on the OnStart method of an Azure Worker Role. Here is the code:
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;
Uri baseAddress = ServiceBusEnvironment.CreateServiceUri("http", "my_sb", "SimpleService");
host = new ServiceHost(typeof(SimpleService1.Service1), baseAddress);
BasicHttpRelayBinding binding = new BasicHttpRelayBinding(EndToEndBasicHttpSecurityMode.None, RelayClientAuthenticationType.None);
binding.OpenTimeout = new TimeSpan(1, 1, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.MaxReceivedMessageSize = 73400320;
XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
readerQuotas.MaxArrayLength = 73400320;
binding.ReaderQuotas = readerQuotas;
TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;
sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = "owner";
sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = "blablablabla==";
ContractDescription contractDescription = ContractDescription.GetContract(typeof(SimpleService1.IService1), typeof(SimpleService1.Service1));
ServiceEndpoint serviceEndPoint = new ServiceEndpoint(contractDescription);
serviceEndPoint.Address = new EndpointAddress(baseAddress);
serviceEndPoint.Binding = binding;
IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);
serviceEndPoint.Behaviors.Add(serviceRegistrySettings);
serviceEndPoint.Behaviors.Add(sharedSecretServiceBusCredential);
host.Description.Endpoints.Add(serviceEndPoint);
try
{
host.Open();
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message, "Error");
throw;
}
Trace.WriteLine("SimpleService1 running...");
and the binding configuration on the client side is:
<basicHttpBinding>
<binding name="FileTransferBinding" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxReceivedMessageSize="73400320">
<readerQuotas maxArrayLength="73400320"/>
<security mode="None"/>
</binding>
</basicHttpBinding>
and
<endpoint address="http://my_sb.servicebus.windows.net/simpleservice" binding="basicHttpBinding" bindingConfiguration="FileTransferBinding" contract="Service1reference.IService1" name="FileTransferBinding" behaviorConfiguration="sbBehavior"/>
The problem is that if one call to the service takes longer than 1 minute, the client receives this exception:
The content type application/xml; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly
If I change the binding to a netTcpRelayBinding everything works fine.
This is because the Windows Azure load-balancer disconnects you if the connection is idle for more than a minute.
Your best bet is to use a WCF callback. This will execute a call from the server to the client to let it know that the long-running operation has completed. For more on how to do this have a look at this blog [WCF Callbacks

Cannot connect to a WCF service hosted in a Worker Role

I've created a WCF service and hosted it in cloud through a worker role. Unfortunately when I try to connect to the worker role service I get an exception with the message:
"No DNS entries exist for host 3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net."
3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net is the address for the worker role deployed in azure staging environment.
The workerrole.cs has the following code to expose the WCF service:
public override void Run()
{
using (ServiceHost host = new ServiceHost(typeof(MyService)))
{
string ip = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["tcppoint"].IPEndpoint.Address.ToString();
int tcpport = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["tcppoint"].IPEndpoint.Port;
int mexport = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["mexinput"].IPEndpoint.Port;
// Add a metadatabehavior for client proxy generation
// The metadata is exposed via net.tcp
ServiceMetadataBehavior metadatabehavior = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadatabehavior);
Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
string mexlistenurl = string.Format("net.tcp://{0}:{1}/MyServiceMetaDataEndpoint", ip, mexport);
string mexendpointurl = string.Format("net.tcp://{0}:{1}/MyServiceMetaDataEndpoint", RoleEnvironment.GetConfigurationSettingValue("Domain"), 8001);
host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexendpointurl, new Uri(mexlistenurl));
// Add the endpoint for MyService
string listenurl = string.Format("net.tcp://{0}:{1}/MyServiceEndpoint", ip, tcpport);
string endpointurl = string.Format("net.tcp://{0}:{1}/MyServiceEndpoint", RoleEnvironment.GetConfigurationSettingValue("Domain"), 9001);
host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(SecurityMode.None), endpointurl, new Uri(listenurl));
host.Open();
while (true)
{
Thread.Sleep(100000);
Trace.WriteLine("Working", "Information");
}
}
}
The tcppoint and mexinput are configured with the ports 8001 and 9001. Also Domain is configured with worker role deployment url:3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net
On the client part(a console app), we are using the following configuration in app.config::
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_IMyService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
maxReceivedMessageSize="65536">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:50:00"
enabled="false" />
<security mode="None">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="httpp:\\3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net:9001/MyServiceEndpoint" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IMyService" contract="ServiceReference1.IMyService"
name="NetTcpBinding_IMyService" />
</client>
<behaviors>
<serviceBehaviors>
<behavior name="behave">
<serviceMetadata httpGetEnabled="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy autoDetect="False" usesystemdefault="False" bypassonlocal="True" />
</defaultProxy>
The following code is built using the sample code available in msdn as background. Locally it is working fine. Unfortunately when i deploy it to cloud, the exception occurs. Moreover, when i use the virtual ip instead of the url, a connection time out occurs with the exception the remote machine did not respond.
Looks like you have your service setup to listen on net.tcp (TCP) and your client using http bindings. I would not expect that to work even locally. I am assuming you have actually opened port 9000 in the ServiceDefinition. Remember that will be a load-balanced endpoint. Are you trying to communicate to this instance from within the deployment (inter-role) or from outside the cloud?
I have found it is a lot easier to setup the host and client (when communicating within a role) through code. Try this:
http://dunnry.com/blog/2010/05/28/HostingWCFInWindowsAzure.aspx
If you are trying to hit the service from a client outside the deployment, this still applies, but for the client building part. You will need to use the external DNS name and port defined in ServiceDefinition.
I have also seen DNS errors if you try to hit the endpoint too soon before the role was ready. It can take a bit to propogate the DNS and you should try not to resolve it until it is ready, lest you cache a bogus DNS entry. If you can resolve that DNS name however to your VIP address, that is not the issue.
public void CallWebService(string data)
{
try
{
string uri = "url"+data;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream str = response.GetResponseStream();
StreamReader sr = new StreamReader(str);
String IResponse = sr.ReadToEnd();
}
catch (Exception ex)
{
System.Console.WriteLine("Message: "+ex.Message);
}
}
Hope it helps you.

unable to load wcf restful help page after changing transferMode to "Streamed"

In my project, a wcf restful service, which allow users to upload photos to the web service.
After changing config settings to allow large file upload. (add binding configuration, i.e. "TransferMode", "BufferSize", etc.)
All Operation contracts are all working as expected.
However, the service help page for the endpoint stopped working.
The help page comes back, once I remove the binding config setting on my endpoint
How can I fixed this?? where did i missed
thank you all
<bindings>
<webHttpBinding>
<!-- buffer: 64KB; max size: 64MB -->
<binding name="StreamedBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" transferMode="Streamed"
maxBufferPoolSize="67108864" maxBufferSize="65536" maxReceivedMessageSize="67108864">
</binding>
</webHttpBinding>
</bindings>
<service name="WCFRestFul.ApiRestful">
<endpoint address="" binding="webHttpBinding"
bindingConfiguration="StreamedBinding" bindingName="StreamedBinding"
contract="WCFRestFul.IApiRestful" behaviorConfiguration="web" />
</service>
Update:
I think it is not just because of the transfer mode, but maybe some other setting as well.
The service help page comes back once I remove the "bindingConfiguration" in the code above.
I have 2 endpoints. The other endpoint don't have the "bindingConfiguration", and the service help page works fine on that.
I definitely missed some thing here, maybe some thing simple.
any help will be greatly appreciated
I took carlosfigueira advice, painfully removed my config setting one at a time.
I changed my config settings from
OLD Code
<bindings>
<webHttpBinding>
<!-- buffer: 64KB; max size: 64MB -->
<binding name="StreamedBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" transferMode="Streamed"
maxBufferPoolSize="67108864" maxBufferSize="65536" maxReceivedMessageSize="67108864">
</binding>
</webHttpBinding>
</bindings>
To Final working version (transferMode="Streamed" is removed)
<bindings>
<webHttpBinding>
<binding name="StreamedBinding" maxReceivedMessageSize="67108864" />
</webHttpBinding>
</bindings>
finally the service help page is back.
However I can't understand why it is back same as why it was turned off.
anyway, this is the working solution for my case.
hope someone would find it helpful.
What do you mean by saying that it stops working? In the example below the help page is still returned by the service (and I tried using both IE and Chrome, and they were able to see the page).
public class StackOverflow_5937029
{
[ServiceContract]
public interface ITest
{
[WebGet]
int Add(int x, int y);
}
public class Service : ITest
{
public int Add(int x, int y)
{
return x + y;
}
}
static void SendRequest(string address)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "GET";
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
resp = (HttpWebResponse)e.Response;
}
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
foreach (string headerName in resp.Headers.AllKeys)
{
Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
}
Console.WriteLine();
Stream respStream = resp.GetResponseStream();
Console.WriteLine(new StreamReader(respStream).ReadToEnd());
Console.WriteLine();
Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
Console.WriteLine();
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
WebHttpBehavior behavior = new WebHttpBehavior
{
HelpEnabled = true
};
WebHttpBinding binding = new WebHttpBinding
{
TransferMode = TransferMode.Streamed
};
host.AddServiceEndpoint(typeof(ITest), binding, "").Behaviors.Add(behavior);
host.Open();
Console.WriteLine("Host opened");
SendRequest(baseAddress + "/Add?x=4&y=8");
SendRequest(baseAddress + "/help");
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}

Programmatic configuration of [Silverlight] WCF Client

We're developing a Silverlight Client onto a server-based API exposed via WCF.
I'm trying to move my WCF client code (which works fine) from a configuration-based model to a programmatic model. This will enable me to have a single "root" URL which I can apply at start-up and not require installations to have to maintain humongous configuration files.
I'm stuggling converting my configurations to Silverlight-capable code, though.
Where I have the configuration below for one of my services:
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomBinding_ISilverlightHelper">
<binaryMessageEncoding />
<httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<extendedProtectionPolicy policyEnforcement="Never" />
</httpTransport>
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://localhost:50072/API/WCF/Silverlight/SilverlightHelper.svc"
binding="customBinding" bindingConfiguration="CustomBinding_ISilverlightHelper"
contract="API.WCF.Silverlight.ISilverlightHelper" name="CustomBinding_ISilverlightHelper" />
</client>
</system.serviceModel>
</configuration>
I can't figure out how to create the equivelant client-config code. At the moment I have:
CustomBinding customBinding = new CustomBinding();
// I see I need to do something with customBinding but the properties don't seem
// logical
// I have used BasicHttpBinding, but it just returns with "Not Found" (the service does resolve to a valid URL)
BasicHttpBinding basicHttpBinding = new BasicHttpBinding() { MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue };
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:50072/API/WCF/Silverlight/SilverlightHelper.svc");
ISilverlightHelper silverlightHelper= new ChannelFactory<ISilverlightHelper>(basicHttpBinding, endpointAddress).CreateChannel();
AsyncCallback asyncCallback = delegate(IAsyncResult result)
{
ISilverlightHelper asyncSilverlightHelper = (ISilverlightHelper)result.AsyncState;
string[] files=asyncSilverlightHelper.EndGetPlugInXapNames(result).ToArray();
};
silverlightHelper.BeginGetPlugInXapNames(asyncCallback, silverlightHelper);
Any clues would be appreciated. I've spent all morning Googling/Binging/Overflowing but haven't come across this scenario. Or I might be just so far wrong ...
Sorted it.
I created the BinaryMessageEncodingBindingElement and HttpTransportBindingElements, added them to the CustomBinding and it all works.
Here's my annotated code:
// create the binding elements
BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement();
HttpTransportBindingElement httpTransport = new HttpTransportBindingElement() { MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue };
// add the binding elements into a Custom Binding
CustomBinding customBinding = new CustomBinding(binaryMessageEncoding,httpTransport);
// create the Endpoint URL (I'll use a configured URL later - all web services will then move as one)
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:50072/API/WCF/Silverlight/SilverlightHelper.svc");
// create an interface for the WCF service
ISilverlightHelper silverlightHelper= new ChannelFactory<ISilverlightHelper>(customBinding, endpointAddress).CreateChannel();
// set-up the asynchronous callback
AsyncCallback asyncCallback = delegate(IAsyncResult result)
{
ISilverlightHelper asyncSilverlightHelper = (ISilverlightHelper)result.AsyncState;
string[] files=asyncSilverlightHelper.EndGetPlugInXapNames(result).ToArray();
};
// execute the call
silverlightHelper.BeginGetPlugInXapNames(asyncCallback, silverlightHelper);