WCF data persistence between sessions - wcf

We are developing a WCF based system. In the process we are trying to lock some data from being modified by more than one users. So we decided to have a data structure that will contain the necessary information for the locking logic to execute (by for example storing the ID of the locked objects)
The problem we are having is persisting that data between sessions. Is there anyway we can avoid executing expensive database calls?
I am not sure how can we do that in WCF since it can only persist data (in memory) during an open session.

Static members of the service implementing class are shared between sessions & calls.

One option would be to use static members as Jimmy McNulty said. I have a WCF service that opens network connections based on a user-specified IP address. My service is configured for PerCall service instance mode. In each session, I check a static data structure to see if a network connection is already opened for the specified IP address. Here's an example.
[ServiceContract]
public interface IMyService
{
[OperationContract]
void Start(IPAddress address);
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class MyService : IMyService
{
private static readonly List<IPAddress> _addresses = new List<IPAddress>();
public void Start(IPAddress address)
{
lock(((ICollection)_addresses).SyncRoot)
{
if (!_addresses.Contains(address)
{
// Open the connection here and then store the address.
_addresses.Add(address);
}
}
}
}
As configured, each call to Start() happens within its own service instance, and each instance has access to the static collection. Since each service instance operates within a separate thread, access to the collection must be synchonized.
As with all synchronization done in multithreaded programming, be sure to minimize the amount of time spent in the lock. In the example shown, once the first caller grabs the lock, all other callers must wait until the lock is released. This works in my situation, but may not work in yours.
Another option would be to use the Single service instance mode as opposed to the PerCall service instance mode.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService : IMyService
{ ... }
From everything I've read, though, the PerCall seems more flexible.
You can follow this link for differences between the two.
And don't forget that the class that implements your service is just that - a class. It works like all C# classes do. You can add a static constructor, properties, event handlers, implement additional interfaces, etc.

Perhaps a caching framework like velocity help you out.

Create a second class and set its InstanceContextMode to single and move all the expensive methods there, then in your original class use that methods.

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?

Subtype of shared data contract

Following advices from people on the internet about service references, I got rid of them now and split the service/data contracts into a common assembly accesible by both the server and the client. Overall this seems to work really well.
However I’m running into problems when trying to use custom objects, or rather custom subtypes, in the service. Initially I wanted to define only interfaces in the common assembly as the contract for the data. I quickly learned that this won’t work though because the client needs a concrete class to instantiate objects when receiving objects from the service. So instead I used a simple class instead, basically like this:
// (defined in the common assembly)
public class TestObject
{
public string Value { get; set; }
}
Then in the service contract (interface), I have a method that returns such an object.
Now if I simply create such an object in the service implementation and return it, it works just fine. However I want to define a subtype of it in the service (or the underlying business logic), that defines a few more things (for example methods for database access, or just some methods that work on the objects).
So for simplicity, the subtype looks like this:
// (defined on the server)
public class DbTestObject : TestObject
{
public string Value { get; set; }
public DbTestObject(string val)
{
Value = val;
}
}
And in the service, instead of creating a TestObject, I create the subtype and return it:
public TestObject GetTestObject()
{
return new DbTestObject("foobar");
}
If I run this now, and make the client call GetTestObject, then I immediately get a CommunicationException with the following error text: “The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:09:59.9380000'.”
I already found out, that the reason for this is that the client does not know how to deserialize the DbTestObject. One solution would be to declare the base type with the KnownTypeAttribute to make it know about the subtype. But that would require the subtype to be moved into the common assembly, which is of course something I want to avoid, as I want the logic separated from the client.
Is there a way to tell the client to only use the TestObject type for deserialization; or would the solution for this be to use data transfer objects anyway?
As #Sixto Saez has pointed out, inheritance and WCF don't tend to go together very well. The reason is that inheritance belongs very much to the OO world and not the messaging passing world.
Having said that, if you are in control of both ends of the service, KnownType permits you to escape the constraints of message passing and leverage the benefits of inheritance. To avoid taking the dependency you can utilise the ability of the KnownTypeAttribute to take a method name, rather than a type parameter. This allows you to dynamically specify the known types at run time.
E.g.
[KnownType("GetKnownTestObjects")]
[DataContract]
public class TestObject
{
[DataMember]
public string Value { get; set; }
public static IEnumerable<Type> GetKnownTestObjects()
{
return Registry.GetKnown<TestObject>();
}
}
Using this technique, you can effectively invert the dependency.
Registry is a simple class that allows other assemblies to register types at run-time as being subtypes of the specified base class. This task can be performed when the application bootstraps itself and if you wish can be done, for instance, by reflecting across the types in the assembly(ies) containing your subtypes.
This achieves your goal of allowing subtypes to be handled correctly without the TestObject assembly needing to take a reference on the subtype assembly(ies).
I have used this technique successfully in 'closed loop' applications where both the client and server are controlled. You should note that this technique is a little slower because calls to your GetKnownTestObjects method have to be made repeatedly at both ends while serialising/deserialising. However, if you're prepared to live with this slight downside it is a fairly clean way of providing generic web services using WCF. It also eliminates the need for all those 'KnownTypeAttributes' specifying actual types.

Utilizing multiple service contracts over the same WCF channel or session

I'm in the process of writing a duplex WCF service using NetTcpBinding, and I've run into an architecture question that I think I know the answer to, but hope that I'm wrong.
Our service is stateful, and we've selected NetTcpBinding with PerSession InstanceContextMode. For various reasons, this is something that we require. I'm trying to break up our larger interface (where large blocks of the operations would not apply to many clients) into multiple smaller interfaces with the operations logically grouped. While it's simple enough to have a single service implementation implement all of the contracts, I'm not sure if it's possible to have multiple service contracts share a single channel (or, more to my requirement, a single session), and I'd definitely need to be able to do that in order to make this work.
I could, of course, include everything on one contract and throw FaultExceptions when an invalid operation is performed, but I'd really like to be able to break these up and not even add an endpoint for inapplicable contracts. Is what I'm looking for possible?
TL;DR Version:
I need to be able to do this:
[ServiceContract]
public interface IServiceA
{
[OperationContract]
void Foo();
}
[ServiceContract]
public interface IServiceB
{
[OperationContract]
void Bar();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IServiceA, IServiceB
{
...
}
And be able to establish one session from the client to the service but use both IServiceA and IServiceB.
The default instance provider over a sessionful channel will give you an instance per connection in your case. You can however extend the instance provider to pick up an existing object from your own cache and return the same object.
How you correlate instances will be upto you using some special message header etc. The underlying channel/Connection will be different for each proxy and also use differnt buffers / concurrency models but you can allow service model to use the same instance.
http://msdn.microsoft.com/en-us/magazine/cc163590.aspx

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.

How to create a trimmed service in WCF

I've got a WCF service with lots of method and DataContracts. It is usually consumed by large application "A". I want to create a tiny application "B" which will use the very same server but only a few methods from the service. I want to reduce the size of the XAP, and since the client is using a fraction of all methods exposed by the service, I'd like to have a smaller service reference file than the one automatically created by Visual Studio. I can remove methods which are not used manually but then I cannot really use update service command.
Any solutions?
Many thanks,
Karol
OK, so you have a complete IGreatService interface with lots of methods, which are implemented on a MyGreatService class.
How about this: you create a new, second interface IMyServiceB which has only those few methods you want to expose to the second group of users. You make it so your service implements both IGreatService and IMyServiceB (that's absolutely possible, no problem):
public class MyGreatService : IGreatService, IMyServiceB
{
..
}
Service B basically then just calls those few methods in the service implementation that you want to expose - let's say, you have MethodA on IGreatService that you want to expose on IMyServiceB as well (as MethodB) - implement it like that:
public class MyGreatService : IGreatService, IMyServiceB
{
....
// as defined on IGreatService
public void MethodA (....)
{
}
....
public void MethodB (.....) // as defined on IMyServiceB
{
MethodA();
}
}
That way, you get two separate interfaces (= services), but basically you write your code only once.
You can then expose IMyServiceB on a distinct and separate endpoint, so that users who are supposed to only see IMyServiceB can just connect to that separate endpoint, and they'll only get whatever they need to use your service-B operations.
Could that work?
Marc