How can I callback the client and expose a new Channel with instance context - wcf

I'm making a WCF service with netTcpBinding which has a main lobby with multiple chatrooms which the clients can enter. The Lobby class implements ILobby as the service contract.
When a client wishes to enter a room I want to callback the client exposing a new Channel containing the InstanceContext for the room he just entered but after much searching I am doubting that this is possible.
For example on the Service side I might have
class Lobby : ILobby
{
Dictionary<string, Chatroom> rooms;
public void JoinRoom(string roomname)
{
if (rooms[roomname].TryEnter()) {}
}
}
class ChatRoom : IChatRoom
{
public bool TryEnter(string username)
{
ILobbyCallback callback =
OperationContext.Current.GetCallbackChannel<ILobbyCallback>();
// How do I do this next bit?
callback.JoinedRoom(pass some instance context here);
return true;
}
}
On the client side callback method I want
public void JoinedRoom(InstanceContext for the room on the service side)
{
// Create a new WCF proxy using above InstanceContext
// Create a WPF UI for the new room passing the proxy so it can communicate
// with the room class directly without going via the root service
}
Is this possible? What's the best practice for spawning new classes with their own contracts on the service side? Or do I just have to bundle everything into one massive MyService class and handle everything myself?

You cannot pass instance context as parameter to any operation contract. It doesn't make sense because that context has local scope. It is called "instance context" = it is context of current service instance. In duplex scenario both client and server has its own service:
Clients calls server's service through its proxy
Server calls client' service through received callback channel
Server's service instance context has meaning only on the server. It is not clear what you are trying to achieve (except very complex architecture).
If you want to share context on client you can try to pass around the instance context used for the very first proxy you created - I'm not sure if it will work but you can try it
If you want to share service instance context between multiple proxies you must develop your own IInstanceContextProvider and perhaps also your own IInstanceProvider (depending on what you want to achieve), wrap them in behavior and add them to the service. That will put whole complexity of session handling and correct instance releasing under your control (it obviously has its pros and cons).
But is it really needed? When I look at your code I see that one service and one proxy is enough. Also your JoinRoom operation doesn't need to use callback at all, it can be just request response method.

Related

WCF: Select between regular and duplex service contract at runtime

I am writing a WCF client/service. The service can perform some long operations so I have added a callback contract IProgressCallback. The system I am developing has to run in all kind of environments so I suspect that I will run into an environment where a callback channel cannot be opened (I might be wrong here).
So to be careful I have defined the operation contract like this.
[ServiceContract()]
interface IContract
{ ... }
[ServiceContract(CallbackContract = typeof(IProgress))]
interface IDuplexContract : IContract
{ ... }
This works great on the server side. I can easily configure the service to use either contract.
The problem however arises on the client side. I have manually defined 2 proxies
public class ContractProxy
: ClientBase<IContract>, IContract
{ ... }
public class DuplexContractProxy
: DuplexClientBase<IDuplexContract>, IDuplexContract
{ ... }
Again both proxies work fine.
Now I have a proxy factory which is responsible for creating the correct proxy. It can easily figure out which proxy to instantiate but my problem arises when I try to return the proxy.
The user needs to get an object back that is at least IContract and ICommunicationObject but I haven't been able to find what to return. I have tried to the following:
IContract CreateProxy(...) // The user lacks access to Open, Abort, Close, etc.
ClientBase<IContract> CreateProxy(...) // DuplexClientBase derives from ClientBase but the generic parameter is different and it isn't covariant so this cannot be done.
// First define a generic interface and then make both proxies implement it.
IProxy<TContract> : TContract, ICommunicationObject // TContract cannot be restricted to an interface so I cannot make IProxy derive from TContract
Currently as a workaround I am simply returning the IContract interface but then everyone using the proxy will have to start by casting it to a ICommunicationObject to open the proxy etc.
Does anyone here have a better way to do this or am I simply being overly worried that duplex communication might not work in some environments?

WCF Proxy Pool/Manager

My application needs to comunicate with several external WCF services to satisfy requests from client applications. Being itself a WCF service, it must of course be able to process several simultaneous requests. That being, and since I will be acessing more than one service, I thought about grouping clients in the following manner:
public static class ClientManager
{
private static readonly Service1Client _service1Client = new Service1Client();
private static readonly Service2Client _service2Client = new Service2Client();
...
public static Service1Client Service1DefaultClient { get { return _service1Client; } }
public static Service2Client Service2DefaultClient { get { return _service2Client; } }
}
Then, from the remaining of the code, I would only need to execute
ClientManager.Service1DefaultClient.SomeMethod();
ClientManager.Service2DefaultClient.SomeMethod();
...
The idea is to create a central place to better manage WCF clients. However, I don't really know if this design is the most appropriate one for a service which will be issuing several requests at the same time to Service1DefaultClient and Service2DefaultClient. What do you suggest? Creating a more complex client pool with several proxies from each service to choose from?
Having static client proxies doesn't look like a good idea to me.
If ClientBase instance transitions to the Faulted state, it becomes unusable and you have to re-create it.
If you have a stateful service, session lifetime will be the same as lifetime of a client proxy object, which is very long in your case.
Depending on your binding settings, ClientBase may serialize concurrent calls made on the same proxy instance. In your case, this may strongly affect performance.
I just don't see what problem does this solve.
Proxies are relatively lightweight because of the ChannelFactory caching, so I would just create a new instance every time it is needed.

WCF client side instancing and concurrency issues

Hopefully WCF has a reach instancing and concurrency management at service-side via Throttling.
My service client is an ASP.NET application. It consumes more than one WCF service so I create and parametrize WCF client at run-time (no configuration file is used).
Only the end point address is dynamic, and all the services (used by client) have the same method signatures (same contract).
For this reason I have referenced the service through Visual Studio and it has created my service proxy so I just take care of endpoint address at run-time:
class MyWcfClient
{
void DoSomething(string endpintAddress, int data)
{
// Create 'binding' and 'endpoint' ('endpoint' address is dynamic)
ServiceReference.ServiceClient serviceClient = new ServiceReference.ServiceClient(binding, endpoint);
// Parametrize 'serviceClient'
// Call WCF method (send 'data' to appropriate endpoint)
serviceClient.CLose();
}
}
Since the client is an asp.net application, each request runs on it's own worker thread (WCF method calls are very light and fast, so the thread would not block for a long time).
My question is about the instanciation and concurrency at the client-side.
Should MyWcfClient class be Singleton with one serviceClient instance or it be static class and a new serviceClient be created for each call ?
Should I create serviceClient (i.e, an array or list) based on the endpoints (there are 10-100 endpoints) ?
Note that my asp.net threads should not be blocked for a long time (i.e waiting in a queue for sending their related data via WCF)
There is no throttling on client side and it is not needed because you have client code under your control so you have control over number of requests executed. That is the difference to service where without throttling there is no control over number of incomming requests executed elsewhere (out of service control).
So if you want to control number of requests concurrently executed on client you must create object pool - there will be only limited number of MyWcfClient classes available and each class will always create new ServiceClient. Requests will wait in queue for free MyWcfClient instance.
If your only problem is how to create instances of ServiceClient then answer depends on type of binding.
Sessionful bindings like Net.Tcp, Net.Pipe or WsHttp with reliable session or security context: Create new instance for each communication relation. If your relation is just single call, create new instnace for each call. So you can use static class with static method and create new instance in that method.
Sessionless bindings like BasicHttp or WebHttp: You can reuse client for multiple calls but you can't close the client between subsequent calls. You can use array of prepared client instances. You will still need to handle some errors here.
Btw. also check asynchronous client calls and how to correctly close the service client.

Wcf Duplex: Retrieve Client Connection?

Hi
Maybe this look like ridiculous but this is problem at least for me
I wrote duplex WCF service, in my service I need to get active client service and save them, and when with occurred special event I call specific client and send some values for it. So I define dictionary and save client in that. (With this method client calls)
public static Dictionary<int, IServiceCallbak> ActiveClients;
public void IConnect(int SenderId)
{
if (ActiveClients == null)
ActiveClients = new Dictionary<int, IServiceCallbak>();
Client = OperationContext.Current.GetCallbackChannel<IServiceCallbak>();
if (ActiveClients.Count(ac => ac.Key == SenderId) > 0)
ActiveClients.Remove(SenderId);
ActiveClients.Add(SenderId, Client);
}
So then when I need find client from that dictionary and call specific method : Client.DoSomthing().
Also when Client wants to exit, it calls IDisconnect method which will remove client from dictionary.
so I manage Active-client in service!!!
But there is problem in client for managing themselves
After a period time which define in app.config service connection will be closed and you should renew that and then open the service.
So in this case:
1)Is there any solution for recreate and open the service object automatically in client.
2)Or when in server side when service want call clients, check state of client-service-object from that dictionary, and reopen connection from server-side (Ridiculous-solution)
Edit
I think better solution is to handle Suggestion 1, I don't know how!!!.
So for now the question is: Is way exist to do Suggestion 1 Or not? Previously I describe Suggestion 1 in Comment:
"And automatically refer to event for this case(like closing or aborting), but I don't find anything for doing this in Service-Client"
In order to prevent the server side from closing the connection you could set up a Heartbeat() method in the contract that the client could call periodically. This is not ideal however, for one thing because the underlying socket could drop and this does nothing to remedy that.
As far as your suggestion 1) if on the client side you are inheriting from ClientBase you are somewhat stuck in that no indication of a problem may be given until you call a method to route to the service. You would have to wrap the call in a try / catch and then employ some reconnect logic:
public class MyClass : ClientBase<IContract>, IContract
{
public void ServiceMethod(String data) {
try {
base.Channel.ServiceMethod(data);
}
catch (CommunicationException ce) {
// Perform some reconnect logic here
base.Channel.ServiceMethod(data);
}
}
}
Your comment for suggestion 2) is correct, if there are any firewalls between the server side and client they would most likely not allow the connection
Edit:
To expand on my suggestion for 1), you would need to create a new connection when the call to the service fails with a CommunicationException. The simplest approach would be to create the service channel in the constructor and then create another when the call fails:
class ServiceClient {
Service1Client mService; // Class generated by VS tool
public ServiceClient()
: base() {
mService = new Service1Client();
}
#region IService1 Members
public string GetData(int value) {
CommunicationState state = mService.State;
if (state == CommunicationState.Closed || state == CommunicationState.Faulted) {
mService = new Service1Client();
}
try {
// Note: The state checked above may not be accurate,
// hence the try...catch
return mService.GetData(value);
}
catch (CommunicationException) {
mService = new Service1Client(); // Reconnect logic
return mService.GetData(value); // If it fails again we are out of luck...
}
}
#endregion
}
Edit2:
In WCF the session is handled by the client, if the session between the client and the service is lost, I know of no way to restore that session, either from the client or the service. You are, unfortunately, stuck here.
If the service wants to send via the callback with a broken session, simply put, it can't. Because of the way networks work the service may not know the actual client address. This and various other issues (like firewalls) mean that trying to reestablish a connection to the client from the service just isn't practical. The only approach for the service is to store what data it wanted to send to the client and send it when the service detects that the client has reconnected.
There is no guarantee that the client will know of the underlying socket dropping, until the client tries to send something over the socket, hence the try...catch. Recreating the channel from the client once it becomes aware of a broken connection is the only way I know of to handle the issue; which is what the code example does.
The heartbeat idea is a way to proactively deal with broken connection. Its efficiency depends on your requirements as to how fast you need to detect a broken connection and how many clients are present. The more clients connected the longer the heartbeat would have to be so that you don't put a load on the network at the service.
Edit3:
After some additional digging there may be a way to do what you want automatically. You can create what is known as a Reliable Session. Activating this involves creating additional entries in the config:
<netTcpBinding>
<binding>
<reliableSession ordered="Boolean"
inactivityTimeout="TimeSpan"
enabled="Boolean" />
</binding>
</netTcpBinding>
It is also available for Http related bindings, check out the link to the Microsoft documentation on the feature.

How can I check connection is still valid for Silverlight client using net.tcp for duplex?

I'm putting together a WCF service using net.tcp and netTcpBinding to get duplex comms with my Silverlight client. I call into the service from the Silverlight app and the service calls out to another server, passing it a callback method in the WCF service class. The remote server calls back several times and each time it does, the WCF service uses the callbackchannel to send the data to the Silverlight client. It all works nicely most of the time.
If the user puts in a big request, I get a TimeoutException after a large number of callbacks have already worked. (Clearly, there's some work to do elsewhere to prevent this but I'd like to robustify the service, first.)
I was expecting to do some kind of 'if (client.ConnectionState == faulted)' check before trying to call back to the Silverlight client but I can't seem to find the object that holds the state of the connection. Is there one? Am I approaching this from the wrong side?
This is my first venture into a service net.tcp and duplex. I just moved house and my WCF bible is still in a box. Somewhere. :-) So, I can't do my usual background reading.
Any pointers would be gratefully received. Here's some bare code in case my description is too soupy:
private IActiveDirectoryClient client;
private AsyncSearchRunner runner;
public void Search(Request request)
{
this.client = OperationContext.Current.GetCallbackChannel<IActiveDirectoryClient>();
runner = new AsyncSearchRunner();
runner.Run(request.SearchRoot, request.SearchFilter, request.PageSize,
System.DirectoryServices.Protocols.SearchScope.Subtree, SendObjects);
}
private void SendObjects(List<DirectoryObject> items)
{
Response response = new Response();
response.DirectoryObjects = items.ToArray();
client.SendResponse(response);
}
Yes, there is a State property that is defined in the ClientBase<> class (all the proxy classes are derived from ClientBase<>).
There are some proxy wrappers out there that handle fault states of the connection and re-establish connections as needed. Google for "wcf proxy wrapper".
You can also home-brew something if you use some kind of ServiceLocator pattern.