Global Variable between two WCF Methods - c#

I have two Methods in a WCF Service say
Method1()
{
_currentValue = 10;
}
Method2()
{
return _currentValue;
}
I have a situation in which, i need to set a value in Method1() and read it in Method2().
I tried using static variable like public static int _currentValue, i could able to read the value set in Method1() in Method2().
But the issue is, i want this variable to react like separate instance variable for each request made. i.e., right now below is the problem
Browser 1 :
- Method1() is called
=> sets _currentValue = 10;
- Method2() is called
=> returns _currentValue = 10;
Browser 2:
- Method2() is called
=> returns _currentValue = 10;
Actually the value set is Browser 1 is static, so in Browser 2
the same value is retrieved.
What i am trying to implement is the variable should act like a new instance for each request made (when calling from each browser). What should i use in this case? a session?

You're going to need some mechanism for correlation because you have two completely different sessions calling into different methods. So I would recommend using a private key that both callers know.
It is a bit impossible for me to know what that key can be because I can't really gather anything from your question, so only you know that, but the simple fact is you're going to need correlation. Now, once you determine what they can use you can do something like this.
public class SessionState
{
private Dictionary<string, int> Cache { get; set; }
public SessionState()
{
this.Cache = new Dictionary<string, int>();
}
public void SetCachedValue(string key, int val)
{
if (!this.Cache.ContainsKey(key))
{
this.Cache.Add(key, val);
}
else
{
this.Cache[key] = val;
}
}
public int GetCachedValue(string key)
{
if (!this.Cache.ContainsKey(key))
{
return -1;
}
return this.Cache[key];
}
}
public class Service1
{
private static sessionState = new SessionState();
public void Method1(string privateKey)
{
sessionState.SetCachedValue(privateKey, {some integer value});
}
public int Method2(string privateKey)
{
return sessionState.GetCachedValue(privateKey);
}
}

It sounds like you may need to use the per session instance context mode for the WCF service. This will allow you to maintain state on a per session basis, so member variables in the service instance will persist between method calls from the same proxy instance. Because each user has their own session, the state of the service instance will vary by user.
Check out this article for more information: http://msdn.microsoft.com/en-us/magazine/cc163590.aspx#S2

You have made your variable static, and this is what's causing the problem. static means that every instance of your class shares the variable, but all you really need is a variable declared outside of your methods, like this:
private int _currentValue;
Method1()
{
_currentValue = 10;
}
Method2()
{
return _currentValue;
}
This variable will be reated separately for each instance of your class - preserving this value between requests for a given user is a separate problem. (A session is one possible solution.)

WCF has provided three ways by which you can control WCF service instances:
Per call
Persession
Single instance
You will find the best solution by reading this
Three ways to do WCF instance management

Seems like an old thread but in case somebody is still interested, this can be achieved by just asking WCF to run a single instance of your service. Add the following line (decorator) to the definition of your class
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
If you want the behavior only for the same session but not across clients then you can mark it as per session by the following service behavior
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
The other option is per call which is the default option.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

Related

Using XML Webservices in ASP.Net statically or as a singleton

I have an ASP.Net site that consumes ASP.Net XML webservices. To communicate with each webmethod in the webservice I have a static class with static business methods, one for each webmethod in the webservice. The static business methods create a new instance of the webreference class each time they are called. The new instance of the webreference class is used to only call the webmethod, none of the properties in the instance of the webreference are changed from their defaults.
My question is can I create just a global static instance of the webreference class to use by all of the static business methods instead of creating a new one each time a static business method is called? (Basically are instances of a webreference class thread safe?)
My concern here is that the instance of the webreference class has some properties that are not thread safe and since the code is for a web site, multiple threads calling the same static business methods at the same time would cause issues between the threads.
The reason I'm asking is to try and find additional changes I can make to increase the site's performance. In tracing the site's performance I see a fair amount of time being spent on creating an instance of the webreference class. Additionally based on the garbage collection counters I'm seeing a lot of time being spent there too.
Example Code:
This is what I'm currently doing
public static class WebMethodWrapper
{
public static bool CallMethodA(string p1)
{
using(com.mysite.service1 _provider = new com.mysite.service1())
{
return(_provider.WebMethodA(p1));
}
}
public static bool CallMethodB(string p1)
{
using(com.mysite.service1 _provider = new com.mysite.service1())
{
return(_provider.WebMethodB(p1));
}
}
}
This is what I'd like to do
public static class WebMethodWrapper
{
static com.mysite.service1 _Provider = null;
static WebMethodWrapper()
{
_Provider = new com.mysite.service1();
}
public static bool CallMethodA(string p1)
{
return(_Provider.WebMethodA(p1));
}
public static bool CallMethodB(string p1)
{
return(_Provider.WebMethodB(p1));
}
}
My question is can I create just a global static instance of the webreference class to use by all of the static business methods instead of creating a new one each time a static business method is called? (Basically are instances of a webreference class thread safe?)
My concern here is that the instance of the webreference class has some properties that are not thread safe and since the code is for a web site, multiple threads calling the same static business methods at the same time would cause issues between the threads.
A jolly good question to which it seems you are well on the way to answering. I agree you should probably stick with your current approach where each static method creates its own local copy of the service client. This encourages thread-safety not only from the point of view of the client, but also guarantees that remote calls to the service are done so using unique proxies - where results are not potentially multiplexed with other requests.
If you went down the other route of using a shared instance, then you have to take into consideration those scenarios where the service faults in one thread.
Maybe there was a timeout?
Maybe some remote business logic failed?
Maybe the network failed because your room-mate is downloading the latest episode of Game of Thrones exceeding your download quota?
You would then need to invalidate that client and recreate a new one. All of this would need to be safely thread-locked. It sort of becomes quite complex to manage this orchestration.
Let's consider your alternative code:
public static bool CallMethodA(string p1)
{
return(_Provider.WebMethodA(p1));
}
Let's say this was successfully called the first time. Now imagine you need to call this 5 mins 5 seconds later but sadly by this time the server has severed the connection because it has a timeout of 5 mins. Your second call faults. The above code would need to be adjusted to allow for those scenarios. In our simple example below we recreate the client during a failure and try once more.
Perhaps:
public static class WebMethodWrapper
{
static com.mysite.service1 _Provider = null;
static object _locker = new object();
static WebMethodWrapper()
{
_Provider = new com.mysite.service1();
}
static com.mysite.service1 Client
{
get
{
lock (_locker)
{
return _Provider;
}
}
}
public static bool CallMethodA(string p1)
{
try
{
return (Client.WebMethodA(p1));
}
catch (Exception ex) // normally just catch the exceptions of interest
{
// Excercise for reader - use a single method instead of repeating the below
// recreate
var c = RecreateProxy();
// try once more.
return (c.WebMethodA(p1));
}
}
public static bool CallMethodB(string p1)
{
try
{
return (Client.WebMethodB(p1));
}
catch (Exception ex) // normally just catch the exceptions of interest
{
// Excercise for reader - use a single method instead of repeating the below
// recreate
var c = RecreateProxy();
// try once more.
return (c.WebMethodB(p1));
}
}
static com.mysite.service1 RecreateProxy()
{
lock (_locker)
{
_Provider = new com.mysite.service1();
return _Provider;
}
}
}
All of this could be wrapped-up in some generic service client cache that could maintain a collection of ready-to-go clients in a connection pool? Maybe a background thread periodically pings each client to keep them alive? An exercise for the reader perhaps.
Then again, sharing the same proxy instance between threads may not be a good idea from the service point of view, unless your service is marked as per-call which may or may not impact your design or performance.
Conclusion
Your current code is arguably safer and less complex.
Good luck!

Executing one Method At the Start of Several other Methods

i probably dont have the right words but i have tried my best.
say i have a function in c# such as DoWork and within that function i want to call another function such as CheckScore(). However, CheckScore() is a generic function that i want to call from multiple places.
So in my class when i create another function DoWork2, DoWork3 is there any way i can execure CheckScore() as the first line instead of typing those everytime?
For eg. can i avoid
string DoWork2(){
CheckScore()
}
Instead just have
string DoWork2(){}
but CheckScore() is executed anyways?
One potential, though still not foolproof, method is to abstract your security checks into Attributes. This way you can decorate your methods with something like:
[CheckToken]
public string DoWork() {
....
}
This isn't necessarily the best answer because it still requires you to attribute the method. You could instead create an attribute for your web service class, which would execute the [CheckToken] on any method call of the class.
[CheckToken]
public class MyWebService {
...
}
The only issue here is if you have some methods where you want to execute different security checks, or no security checks.
A C# web service framework that has pretty good security features baked into the framework is Service Stack. http://www.servicestack.net/ It has security attributes already built in that you can use, and it promotes clean separation of concerns.
Another very robust option involves intercepting method calls. C# has a class "ContextBoundObject" which can be used for this purpose. You'd need to have your class inherit from ContextBoundObject, and then you can start to dynamically intercept method calls and perform your security checking based upon the context of the method call being made and its parameters. ContextBoundObject does add some overhead to your calls, so you'll need to factor that into your decision. Method interception is great for things like security, performance monitoring, health checks, method retries, and other cross cutting concerns.
Here's a simple getting-started article on ContextBoundObject (and Aspect Oriented Programming). http://www.codeproject.com/Articles/8414/The-simplest-AOP-scenario-in-C
For J...
I wouldn't have the method code query the result. Since we're talking about a web service, there's a pipeline involved where a request is initiated by a client, that request is sent to the service, that service initializes its handlers, deserializes the request, routes the request to the appropriate method, executes the method, serializes the response, and returns the response to the client (this is a big simplification..). Most frameworks I've seen have some hooks for you to specify attributes on your service methods that get checked at the point prior to method execution and can be used to handle security (ie, return a 401 http code for a web service). I believe he said he's using WCF and while it's been a while since I've used WCF, I know this can be done - see http://msdn.microsoft.com/en-us/library/ms733071.aspx
So he could derive his custom security attribute from some WCF security attribute and create his own authentication logic based upon some token, which he'd most likely have to grab from the headers of the request. ServiceStack makes this super easy, I'd imagine it's not that hard using WCF either. Chances are someone's already done this for WCF and the code is out there somewhere.
This may not be exactly what you are looking for, but I would associate the "CheckScore" with the getter for the property when the score is accessed. That way, when using the property it feels like you are not writing out the CheckScore a lot, and also you don't have a CheckScore function being called every time any old method is invoked in your application.
private int _score;
public int Score
{
get
{
CheckScore();
return _score;
}
}
public void DoWork1()
{
if (Score > 10) {
// Case 1
}
}
public void DoWork2()
{
if (Score < 20) {
// Case 2
}
}
Putting CheckScore in a property will still result in it being called a lot.
You could use a private readonly field and set it in the constructor. This will minimise the number of calls to CheckScore.
public class MyClass
{
private readonly int _score;
public MyClass()
{
_score = CheckScore();
}
public int Score
{
get
{
return _score;
}
}
public void DoWork1()
{
if (Score > 10) {
// Case 1
}
}
public void DoWork2()
{
if (Score < 20) {
// Case 2
}
}
}
Given the additional information in comments, one solution to this problem is to create a small class to encapsulate methods which require authentication :
abstract class AuthenticateClass
{
private bool AuthenticateUser(){
return true; // do your authentication
}
public int Perform(){
if (!AuthenticateUser()){
return -1;
} else
return AuthenticatedMethod();
}
protected abstract int AuthenticatedMethod();
}
This gives you a class that performs the authentication and, if successful, performs your method. Implement it like :
class SomeAuthentMethod : AuthenticateClass
{
protected override int AuthenticatedMethod()
{
return 10; // whatever method...
}
}
and use it like :
SomeAuthentMethod myMethod = new SomeAuthentMethod();
if (myMethod.Perform() = -1){
// unable to authenticate user, please log in, etc
}
If the authentication passes this returns 10, otherwise it returns -1 (authentication failed). This lets you generate any number of methods which automatically include authentication.
Alternatively, you might use a static class to do the authentication -- for example :
static class Authenticate
{
public delegate int MethodDelegate();
private static bool AuthenticateUser(){
return true; // do your authentication
}
public static int Perform(MethodDelegate MyMethod){
if (!AuthenticateUser())
{
return -1;
}
else return MyMethod();
}
}
Where you could then have :
private int myMethod(){
return 10; //whatever method...
}
and then implement like :
if (Authenticate.Perform(myMethod) = -1){
// unable to authenticate user, please log in, etc
}
Obviously you can extend both of these patterns to handle whatver "not logged in" or "not authenticated" action within the abstract or static class itself. This should, at least, provide a few ideas of how to approach the problem.

WCF Percall mode and threadstatic variables

We have multiple WCF services all working with InstanceContextMode=PerCall and all WCF service instances are generated by employing Unity (IOC) and implementing IInstanceProvider.
A correlation identifier is used to audit all method calls and database processes with the same identifier.
In order to achieve this, an endpoint behavior is created by implementing IDispatchBehavior and in AfterReceiveRequest method, a guid is generated and assigned to a ThreadStatic (CommonData) property. This property can be access in all layers of the application. The following code block shows the population of CommonData, and the CommonData class;
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
CommonData.ClearDictionary();
//the lines between are deleted as they are not relevant to the question
CommonData.Current.Add(MessageHeaderCodes.CorrelationId, Guid.NewGuid().ToString());
return null;
}
and commondata class:
public class CommonData
{
[ThreadStatic]
private static Dictionary<string, string> headerData;
public static Dictionary<string, string> Current
{
get
{
if (headerData == null)
{
headerData = new Dictionary<string, string>();
}
return headerData;
}
}
private CommonData()
{
}
public static string GetHeader(string header)
{
string headerValue = string.Empty;
KeyValuePair<string, string> headerKeyValuePair = CommonData.Current.SingleOrDefault(p => p.Key == header);
headerValue = headerKeyValuePair.Value;
return headerValue;
}
public static void ClearDictionary()
{
Current.Clear();
}
}
The problem here is the following;
In some of the services, developers reported that the correlation identifier returns null. Since the problem is intermittant it is not possible to have a full stack trace at the moment. Also, they stated that reseting IIS resolves this problem temporarily.
Any help is appreciated...
This doesn't really answer your question, and would have been a comment, except I wanted to have some code...
I am confused by your GetHeader method. Why are you doing a Linq .FirstOrDefault() on the dictionary, instead of just:
public static string GetHeader(string header)
{
if(CommonData.Current.ContainsKey(header))
return CommonData.Current[header];
return null;
}
Aside from that, I don't actually see anything wrong with your code. I am curious as to where the developers are getting the null identifier. They would of course have to make sure they are on the same thread that the dispatcher was called on. If any async process, or ThreadPool was used anywhere to run something on another thread, then the [ThreadStatic] would not exist.
I had an issue once where I (very stupidly) referenced my [ThreadStatic] variable from a method that was called by a finalizer, which is run on the GC thread, so my thread static was always null. oops :)
As Blam suggested, I have employed OperationContext.Current by writing an Extension to store custom objects. Below is the extension:
public class OperationContextExtension : IExtension<OperationContext>
{
public void Attach(OperationContext owner)
{
this.Current = new Dictionary<string, string>();
}
public void Detach(OperationContext owner)
{
this.Current = null;
}
public Dictionary<string,string> Current { get; set; }
}
On the otherhand, I have to add System.ServiceModel reference to the domain objects. Although it does not seem to be a proper way as domain objects can access to the service layer, it resolved my problem.
Several things:
First, Your Threadstatic value creation is better implemented by ThreadLocal. This is basically the case whenever you need your threadstatic field to be initialized. Use
private static ThreadStatic<Dictionary<string, string>> headerData = new ThreadStatic<Dictionary<string, string>>(() => new Dictionary<string, string>());
Second, for acquiring the value from the dictionary, what you're looking for is the TryGetValue method. I.e. not Contains-Get pair (as it does hash lookup twice unnecessary), and certainly not SingleOrDefault.
And third, to have a reliable ID identifying whatever happened from the one service call, just have it as one of the parameters of all the subsequent method calls.

Singleton pattern on persistent in-memory cache

Using what I judged was the best of all worlds on the Implementing the Singleton Pattern in C# amazing article, I have been using with success the following class to persist user-defined data in memory (for the very rarely modified data):
public class Params
{
static readonly Params Instance = new Params();
Params()
{
}
public static Params InMemory
{
get
{
return Instance;
}
}
private IEnumerable<Localization> _localizations;
public IEnumerable<Localization> Localizations
{
get
{
return _localizations ?? (_localizations = new Repository<Localization>().Get());
}
}
public int ChunkSize
{
get
{
// Loc uses the Localizations impl
LC.Loc("params.chunksize").To<int>();
}
}
public void RebuildLocalizations()
{
_localizations = null;
}
// other similar values coming from the DB and staying in-memory,
// and their refresh methods
}
My usage would look something like this:
var allLocs = Params.InMemory.Localizations; //etc
Whenever I update the database, the RefreshLocalizations gets called, so only part of my in-memory store is rebuilt. I have a single production environment out of about 10 that seems to be misbehaving when the RefreshLocalizations gets called, not refreshing at all, but this is also seems to be intermittent and very odd altogether.
My current suspicions goes towards the singleton, which I think does the job great and all the unit tests prove that the singleton mechanism, the refresh mechanism and the RAM performance all work as expected.
That said, I am down to these possibilities:
This customer is lying when he says their environment is not using loading balance, which is a setting I am not expecting the in-memory stuff to work properly (right?)
There is some non-standard pool configuration in their IIS which I am testing against (maybe in a Web Garden setting?)
The singleton is failing somehow, but not sure how.
Any suggestions?
.NET 3.5 so not much parallel juice available, and not ready to use the Reactive Extensions for now
Edit1: as per the suggestions, would the getter look something like:
public IEnumerable<Localization> Localizations
{
get
{
lock(_localizations) {
return _localizations ?? (_localizations = new Repository<Localization>().Get());
}
}
}
To expand on my comment, here is how you might make the Localizations property thread safe:
public class Params
{
private object _lock = new object();
private IEnumerable<Localization> _localizations;
public IEnumerable<Localization> Localizations
{
get
{
lock (_lock) {
if ( _localizations == null ) {
_localizations = new Repository<Localization>().Get();
}
return _localizations;
}
}
}
public void RebuildLocalizations()
{
lock(_lock) {
_localizations = null;
}
}
// other similar values coming from the DB and staying in-memory,
// and their refresh methods
}
There is no point in creating a thread safe singleton, if your properties are not going to be thread safe.
You should either lock around assignment of the _localization field, or instantiate in your singleton's constructor (preferred). Any suggestion which applies to singleton instantiation applies to this lazy-instantiated property.
The same thing further applies to all properties (and their properties) of Localization. If this is a Singleton, it means that any thread can access it any time, and simply locking the getter will again do nothing.
For example, consider this case:
Thread 1 Thread 2
// both threads access the singleton, but you are "safe" because you locked
1. var loc1 = Params.Localizations; var loc2 = Params.Localizations;
// do stuff // thread 2 calls the same property...
2. var value = loc1.ChunkSize; var chunk = LC.Loc("params.chunksize");
// invalidate // ...there is a slight pause here...
3. loc1.RebuildLocalizations();
// ...and gets the wrong value
4. var value = chunk.To();
If you are only reading these values, then it might not matter, but you can see how you can easily get in trouble with this approach.
Remember that with threading, you never know if a different thread will execute something between two instructions. Only simple 32-bit assignments are atomic, nothing else.
This means that, in this line here:
return LC.Loc("params.chunksize").To<int>();
is, as far as threading is concerned, equivalent to:
var loc = LC.Loc("params.chunksize");
Thread.Sleep(1); // anything can happen here :-(
return loc.To<int>();
Any thread can jump in between Loc and To.

C# thread safety of global configuration settings

In a C# app, suppose I have a single global class that contains some configuration items, like so :
public class Options
{
int myConfigInt;
string myConfigString;
..etc.
}
static Options GlobalOptions;
the members of this class will be uses across different threads :
Thread1: GlobalOptions.myConfigString = blah;
while
Thread2: string thingie = GlobalOptions.myConfigString;
Using a lock for access to the GlobalOptions object would also unnecessary block when 2 threads are accessing different members, but on the other hand creating a sync-object for every member seems a bit over the top too.
Also, using a lock on the global options would make my code less nice I think;
if I have to write
string stringiwanttouse;
lock(GlobalOptions)
{
stringiwanttouse = GlobalOptions.myConfigString;
}
everywhere (and is this thread-safe or is stringiwanttouse now just a pointer to myConfigString ? Yeah, I'm new to C#....) instead of
string stringiwanttouse = GlobalOptions.myConfigString;
it makes the code look horrible.
So...
What is the best (and simplest!) way to ensure thread-safety ?
You could wrap the field in question (myConfigString in this case) in a Property, and have code in the Get/Set that uses either a Monitor.Lock or a Mutex. Then, accessing the property only locks that single field, and doesn't lock the whole class.
Edit: adding code
private static object obj = new object(); // only used for locking
public static string MyConfigString {
get {
lock(obj)
{
return myConfigstring;
}
}
set {
lock(obj)
{
myConfigstring = value;
}
}
}
The following was written before the OP's edit:
public static class Options
{
private static int _myConfigInt;
private static string _myConfigString;
private static bool _initialized = false;
private static object _locker = new object();
private static void InitializeIfNeeded()
{
if (!_initialized) {
lock (_locker) {
if (!_initialized) {
ReadConfiguration();
_initalized = true;
}
}
}
}
private static void ReadConfiguration() { // ... }
public static int MyConfigInt {
get {
InitializeIfNeeded();
return _myConfigInt;
}
}
public static string MyConfigString {
get {
InitializeIfNeeded();
return _myConfigstring;
}
}
//..etc.
}
After that edit, I can say that you should do something like the above, and only set configuration in one place - the configuration class. That way, it will be the only class modifying the configuration at runtime, and only when a configuration option is to be retrieved.
Your configurations may be 'global', but they should not be exposed as a global variable. If configurations don't change, they should be used to construct the objects that need the information - either manually or through a factory object. If they can change, then an object that watches the configuration file/database/whatever and implements the Observer pattern should be used.
Global variables (even those that happen to be a class instance) are a Bad Thing™
What do you mean by thread safety here? It's not the global object that needs to be thread safe, it is the accessing code. If two threads write to a member variable near the same instant, one of them will "win", but is that a problem? If your client code depends on the global value staying constant until it is done with some unit of processing, then you will need to create a synchronization object for each property that needs to be locked. There isn't any great way around that. You could just cache a local copy of the value to avoid problems, but the applicability of that fix will depend on your circumstances. Also, I wouldn't create a synch object for each property by default, but instead as you realize you will need it.

Categories

Resources