dot net service reference authentication - wcf

Can anyone concisely describe or point me to a resource which explains how to call a service reference and pass in credentials? I have created the service reference from a wsdl, but I am stuck on how to call it with credentials?

I am an idiot - I was using the wrong class, need to use the one with Client in the name, eg
MyServiceClient c as new MyServiceClient();
not
MyService c = new MyService();
This allows setting of the ClientCredentials, eg
c.ClientCredentials.UserName.UserName = "joeblow";

Related

How to implement dynamic endpoint in WCF

i am new in wcf. Dynamic Endpoint is a standard endpoint which performs discovery and automatically selects a matching service that i know. here is a code sample for DynamicEndpoint.
DynamicEndpoint dynamicEndpoint = new DynamicEndpoint(ContractDescription.GetContract(typeof(ICalculatorService)), new WSHttpBinding());
CalculatorServiceClient client = new CalculatorServiceClient(dynamicEndpoint);
Console.WriteLine("Invoking CalculatorService");
Console.WriteLine();
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
i do not understand from the code that it is assumed that we added service reference and then we work with dynamic endpoint. when we add wcf service reference at client side then endpoint related setting automatically added in config file at client end.
could anyone please tell how dynamic endpoint discover my service address at run time just if we pass the contract. suppose if we have no config file at client end then how dynamic endpoint can discover my service?
could anyone please tell me in what kind of situation dynamic endpoint is used and only option ?
please discuss all my points in details. thanks
There are multiple ways of discovering services. There is UDDI and WS-Discovery.
It seems those classes use WS-Discovery. For a better overview, I'd suggest a good book, this is way to broad for a single SO question.

Proxy generated for WCF creating Message Contracts

I'm consuming a WCF service in my project for which I've added the reference using 'Add Service Reference...'. I expected it to generate a clean proxy with a ServiceClient entity and the Interface. Instead, I see that it has created a MethodNameRequest, MethodNameRequestBody, MethodNameResponse, MethodNameResponseBody entities for each OperationContract method.
So while invoking the service methods, the proxy passes to the service method an instance of MethodNameRequest with the input parameters of the method as the properties of the RequestBody. See below an example of a call to AboutInformationGet() method which doesn't accept any parameters.
public WCFDynamicInvocation.PostingService.AboutModel AboutInformationGet() {
WCFDynamicInvocation.PostingService.AboutInformationGetRequest inValue = new WCFDynamicInvocation.PostingService.AboutInformationGetRequest();
inValue.Body = new WCFDynamicInvocation.PostingService.AboutInformationGetRequestBody();
WCFDynamicInvocation.PostingService.AboutInformationGetResponse retVal = ((WCFDynamicInvocation.PostingService.IMIGQPosting)(this)).AboutInformationGet(inValue);
return retVal.Body.AboutInformationGetResult;
}
I believe this behavior is what one would expect to see in a Webservice Proxy. Hence I suspect that the WCF service is not properly configured.
Did someone here face this issue? What would be the change to be done at the service so that the proxy generated is similar to the WCF service.
Cheers.
There is a similar post here.
Right click your service reference -> Configure service reference... -> Check if "Always generate message contracts" check box is checked. Uncheck it and hit OK to regenerate the proxy to see if you get a normal proxy.
After struggling with this for some time, I've finally found that the cause for the message contracts in the proxy was the service interface had the following attribute:
[XmlSerializerFormat(Use = OperationFormatUse.Literal, Style = OperationFormatStyle.Document)]
As I understand, I could decorate the DataContracts with the following attribute to avoid wrapping
[MessageContract(IsWrapped = false)]
but the response still gets wrapped as the OperationContract hasn't been modified.
As there were no particular need to use XMLSerializer in place of WCF's default DataContractSerializer, we would remove the XmlSeralizerFormat decoration.

Config Framework and WIF Federation+Delegation: Need factory.CreateChannelActingAs(token)

My current task is to secure a WCF service. The service is hosted using the configuration framework (5.5, released with the StockTraider sample) and the caller uses the configuration framework as well.
I managed to secure the connection using ws2007FederationHttpBinding.
For the "IsOnline()"-Check my STS issues a service token and this works already but for the actual service calls, I want to have ActAs-Tokens to still know the real user inside the called service.
My STS is capable of issuing the correct ActAs-Tokens.
The problem is the loadbalancing client, which always opens the factory and I cannot call the WIF-methods (ConfigureChannelFactory() and CreateChannelActingAs()) anymore, because they require the factory to be in the created state.
My best try is this, but it looses the ActAs-Subject somewhere and feels like a hack:
IPSServiceClient = new Client(serviceName, settingsInstance, createNewChannelInstance: true);
var token = ((IClaimsIdentity)Thread.CurrentPrincipal.Identity).BootstrapToken;
var factoryObject = IPSServiceClient.createANewChannelFactoryByAddress(IPSServiceClient.getANodeAddress());
var factory = factoryObject as ChannelFactory<IIWBPortalServiceV1>;
factory.ConfigureChannelFactory(); //factory must not be state=open here
factory.Credentials.SupportInteractive = false; //no cardspace
_channel = factory.CreateChannelActingAs(token);
Do I miss an extensibility point in the config framework? What is the best way I should go?
If I make a new console app, add service reference and add the two calls (ConfigureChannelFactory() and CreateChannelActingAs()) it just works!
The posted code inside my questions works. The problem was the web.config of the STS which was missing AudienceUris inside the ActAs-securityTokenHandlers section.
Still: The posted code feels like a hack to me.

Calling WCF service dynamically with ref and out parameters

I have gone through following references and found that a WCF service can be called dynamically. But, i have not been able to call a service (method) accepting parameters as ref and out.
Calling a WCF service from a client without having the contract interface
Dynamic Programming with WCF
Dynamically Invoking Web Services... With WCF This Time
Invoking WCF Service without adding a Service Reference.
Is there any way to make such call with ref and out parameters?
Invoking WCF Service without adding a Service Reference. works greate provided i know the Contract. So i added the web reference first, copied the generated proxy into actual project and then removed the web refernce and simply called the method as
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress epAddr = new EndpointAddress("http://192.168.0.233/GMS/GMSService.svc");
GMSContract.IGMSService _interface = ChannelFactory<GMSContract.IGMSService>.CreateChannel(binding, epAddr);
...
bool r = _interface.MyGMSMethod(..., ref ..., out ..., out ...);

WCF Callback implementation function never gets called

I am designing a WCF service with callback, but my implementation of the callback function never gets called. And I am confused about the generated service proxy, so please help.
Here is the scenario: in the server side, I defined the service interface IMyService and callback interface IMyServiceCallback, I also implemented the IMyService in the server project. Besides the server project, I surely have another client project, to which I added the service reference in VS. And I implemented the IMyServiceCallback interface on the client side. So here comes the problem: when I am debugging it, the function never goes into my implementation of IMyServiceCallback and of course the desired result never comes out.
And this is I where I got confused: when I added the service reference in the client side, it actually generated three interfaces on the local: IMyService, IMyServiceCallback, and IMyServiceChannel plus the client proxy class. And in my local implementation of IMyServiceCallback, I declared the class to implement the local IMyServiceCallback interface, not the one from service side. Could this be the problem? Why is there two declarations of the interface under different projects(and hence different namespaces)? The reason I implement the client side interface is, if I implemented from the server side interface, it would give the error: "InstanceContext provided to the ChannelFactory contains a UserObject that does not implement the CallbackContractType error" when I tried to call the service. And another confusing part is, on the server side if I declare the callback interface name as IMyCallback, or anything else, instead of IMyServiceCallback, the generated interface on the client side would still be IMyServiceCallback, which is the name of the service interface plus the suffix "Callback". And in this situation I also got the "InstanceContext provided to the ChannelFactory contains a UserObject that does not implement the CallbackContractType error".
I guess there is something that I misunderstood about the "add service reference" and how I should implement the interface(which one to implement). Could anyone help me? Thanks!
Updated:
I somehow fixed the problem. Firstly, the two declarations is fine is desired. The local client will need to implement the local interface, which is generated when adding the service reference. And my problem was that I also defined a DataContract but the generated reference file didn't have it. It could either because I had added the assembly of the service project as reference(somebody said in this case add service reference will not generate the Datacontract) or because I was missing DataMember attribute. But anyway, after I fixed both parts, the function is working now.
When you "Add Service Reference" and generate a proxy, it is totally separate from your service implementation. Remember, you may be consuming a service that you have not written and do not have access to the service source code.
The client code should use the client generated interfaces. If you change your service, you need to regenerate the proxy.
If you find this too messy, and you know you will always control both ends, you can share the service interfaces in a common assembly and generate a proxy class at runtime using DuplexChannelFactory.CreateChannel().
As for your problem, I can only assume you are not registering your callback properly. This is covered here.
if you want publish , you must implement IMyServiceCallback and IMyService together in same project.
if only subscribe , you must implement IMyServiceCallback interface
I fixed the issue when my callback instruction was embedded in a function call.
I learned that placing the callback in just a method that does not return a result works fine.
However, when the callback instruction is placed within a function I ran into timeout issue.
I resolved it by using a backgroundworker thread within the function being invoked:
public static IMyServiceCallback Callback;
.
.
.
TaskStateData taskStateData = GetSomeData();
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (se, ev) =>
{
Tuple<OperationContext, TaskStateData> data = ev.Argument as Tuple<OperationContext, TaskStateData>;
var operationContext = data.Item1;
if (operationContext != null)
{
Callback = operationContext.GetCallbackChannel<IMyServiceCallback>();
Callback.OnCallBack();
}
};
Tuple<OperationContext, TaskStateData> payload = new Tuple<OperationContext, TaskStateData>(OperationContext.Current, taskStateData);
backgroundWorker.RunWorkerAsync(payload);