I have a situation where I need to create a (arguably dirty) soak test runner. The idea being to use something like Tasks or the ThreadPool to run a massive amount of the tests at one time.
The issue is that it will be using a lot of (poorly developed, by me) helper classes that use statics within them. This has never been an issue as everything was torn down and restarted after it was used. This means that when I start multiple threads in the same app domain, they use the same statics, and things get messy.
Note: it is an assumption based on testing I've been doing, I'm not 100% sure on that being the issue.
I've tried creating a new AppDomain (AppDomain.Create) and then created an instance of a class using it (domain.CreateInstanceFromAndUnwrap), and it creates the instance, and I can call methods on it. The problem is that it doesn't seem to be running in the new AppDomain.
Here's the code I have so far:
static void CallBack(BasePerfTest bpf)
{
Console.WriteLine("CurrentAppDomain (WithinCallback): {0}", Thread.GetDomain().Id);
AppDomain newdomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
//newdomain.ExecuteAssembly(".\\PerformanceTestRunner.exe", new string[] { bpf.ToString() });
ProcessRunner pr = (ProcessRunner)newdomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, "PerformanceTesting.ProcessRunner");
pr.RunProcess(bpf);
}
}
[Serializable]
public class ProcessRunner
{
public void RunProcess(BasePerfTest bpf)
{
Console.WriteLine("CurrentAppDomain (WithinPR): {0}", Thread.GetDomain().Id);
}
}
Now, I would expect that the RunProcess() method is executed in the domain, but the DomainID is still the same, and therefore it's hitting the issue with the statics colliding.
Now, I did created a separate console app, and the commented out line shows the code I used to run it. This DID run in the new domain, but the question is why.
I'm happy to be pointed in the direction of some bedtime reading on how this works, I've 'd for the past day and I think I must just not be using the right terms.
Any help is much appreciated.
Thanks,
Martin
There are two ways to expose objects over AppDomain boundaries:
Serializable - serializes the object, so you get a copy.
MarshalByRefObject - creates a proxy to your object, using remoting.
You need the latter for your ProcessRunner class.
Make your class inherit from MarshalByRefObject:
public class ProcessRunner : MarshalByRefbject
{
public void RunProcess(BasePerfTest bpf)
{
Console.WriteLine("CurrentAppDomain (WithinPR): {0}", Thread.GetDomain().Id);
}
}
When you instantiate your class in the second AppDomain, you get a proxy. The example in the documentation for MarshalByRefObject on MSDN should also help you - it demonstrates almost exactly what you are trying to do.
Your ProcessRunner class must inherit from System.MarshalByRefObject. What is happening is that the object is actually being created in the secondary appdomain, but when you assign it to your local 'pr' variable it is marshalling it by value back to your primary appdomain, in effect creating a second instance of ProcessRunner in the primary appdomain. If you inherit from MarshalByRefObject then pr will instead get a transparent proxy object which forwards calls to the object residing in the secondary appdomain.
Related
I created a class for authentication of my project.
I want to use it in my website and also in mobile application but why this class has a static constructor and should be get instance one time, it didn't work well, I mean I want to get instance for each application once.
I want to know how fix it?
It sounds to me like you're looking for a singleton pattern.
"I mean I want to get instance for each application once."
I assume you mean that you want to construct an instance once per application.
The easiest implementation is to use this:
public class MyAuth
{
private static readonly MyAuth instance = new MyAuth();
public static MyAuth Instance { get { return instance; } }
private MyAuth()
{
// initialization goes here and will be called once
}
// Members.
}
So first off, I'm not sure if this is a good solution. Authorization is usually updated from different applications, so it might be better to flush the authentication once in a while.
Second, note that member functions can be called from multiple threads. If you want to do it like this, you have to use locking for fields that you use (either directly or indirectly). Be sure to know what you're doing.
There is an alternative solution that solves all this in a neat way (and a ton of other issues). It's called a database; you might want to consider using that.
Dynamics CRM 2011 on premise. (But this problem exists in many situations away from Dynamics CRM.)
CRM plugins have an entry point:
void IPlugin.Execute (IServiceProvider serviceProvider)
(http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.iplugin.execute.aspx)
serviceProvider is a reference to the plugin execution context. Anything useful that a plugin does requires accessing serviceProvider, or a member of it.
Some plugins are large and complex and contain several classes. For example, I'm working on a plugin that has a class which is instantiated multiple times. This class needs to use serviceProvider.
One way to get access to serviceProvider from all the classes that need it would be to add a property to all those classes and then to set that property. Or to add properties for the parts of serviceProvider that each class needs. Either of these approaches would result in lots of duplicate code.
Another approach would be to have a global variable in the scope of the thread. However, according to http://msdn.microsoft.com/en-us/library/cc151102.aspx one "should not use global class variables in plug-ins."
So what is the best way to have access to serviceProvider without passing it around everywhere?
P.S. If an example helps, serviceProvider provides access to a logging object. I want almost every class to log. I don't want to pass a reference to the logging object to every class.
That's not quite what the warning in the documentation is getting at. The IServiceProvider isn't a global variable in this context; it's a method parameter, and so each invocation of Execute gets its own provider.
For improved performance, Microsoft Dynamics CRM caches plug-in instances. The plug-in's Execute method should be written to be stateless because the constructor is not called for every invocation of the plug-in. In addition, multiple threads could be running the plug-in at the same time. All per invocation state information is stored in the context. This means that you should not use global class variables in plug-ins [Emphasis mine].
There's nothing wrong with passing objects from the context to helper classes which need them. The warning advises against storing something in a field ("class variable") on the plugin class itself, which may affect a subsequent call to Execute on the same instance, or cause concurrency problems if Execute is called by multiple threads on the same instance simultaneously.
Of course, this "globalness" has to be considered transitively. If you store anything in either the plugin class or in a helper class in any way that multiple calls to Execute can access (using fields on the plugin class or statics on either plugin or helper classes, for example), you leave yourself open to the same problem.
As a separate consideration, I would write the helper classes involved to accept types as specific to their function as possible - down to the level of individual entities - rather than the entire IServiceProvider. It's much easier to test a class which needs only an EntityReference than one which needs to have an entire IServiceProvider and IPluginExecutionContext mocked up.
On global variables vs injecting values required by classes
You're right, this is something that comes up everywhere in object-oriented code. Take a look at these two implementations:
public class CustomEntityFrubber
{
public CustomEntityFrubber(IOrganizationService service, Guid entityIdToFrub)
{
this.service = service;
this.entityId = entityIdToFrub;
}
public void FrubTheEntity()
{
// Do something with service and entityId.
}
private readonly IOrganizationService service;
private readonly Guid entityId;
}
// Initialised by the plugin's Execute method.
public static class GlobalPluginParameters
{
public static IOrganizationService Service
{
get { return service; }
set { service = value; }
}
public static Guid EntityIdToFrub
{
get { return entityId; }
set { entityId = value; }
}
[ThreadStatic]
private static IOrganizationService service;
[ThreadStatic]
private static Guid entityId;
}
public class CustomEntityFrubber
{
public FrubTheEntity()
{
// Do something with the members on GlobalPluginParameters.
}
}
So assume you've implemented something like the second approach, and now you have a bunch of classes using GlobalPluginParameters. Everything is going fine until you discover that one of them is occasionally failing because it needs an instance of IOrganizationService obtained by calling CreateOrganizationService(null), so it accesses CRM as the system user rather than the calling user (who doesn't always have the required privileges).
Fixing the second approach requires you to add another field to your growing list of global variables, remembering to make it ThreadStatic to avoid concurrency problems, then changing the code of CustomEntityFrubber to use the new SystemService property. You have tight coupling between all these classes.
Not only that, all these global variables hang around between plugin invocations. If your code has a bug that somehow bypasses the assignment of GlobalPluginParameters.EntityIdToFrub, suddenly your plugin is inexplicably operating on data that wasn't passed to it by the current call to Execute.
It's also not obvious exactly which of these global variables the CustomEntityFrubber requires, unless you read its code. Multiply that by however many helper classes you have, and maintaining this code starts to become a headache. "Now, does this object need me to have set Guid1 or Guid2 before I call it?" On top of that, the class itself can't be sure that some other code won't go and change the values of global variables it was relying on.
If you used the first approach, you simply pass in a different value to the CustomEntityFrubber constructor, with no further code changes needed. Furthermore, there's no stale data hanging around. The constructor makes it obvious which dependencies the class has, and once it has them, it can be sure that they don't change except in ways they were designed for.
As you say, you shouldn't put a member variable on the plugin since instances are cached and reused between requests by the plugin pipeline.
The approach I take is to create a class that perform the task you need and pass a modified LocalPluginContext (making it a public class) provided by the Developer Toolkit (http://msdn.microsoft.com/en-us/library/hh372957.aspx) on the constructor. Your class then can store the instance for the purposes of executing it's work just in the same way you would with any other piece of code. You are essentially de-coupling from the restrictions imposed by the Plugin framework. This approach also makes it easier to unit test since you only need to provide the execution context to your class rather than mocking the entire plugin pipeline.
It's worth noting that there is a bug in the automatically generated Plugin.cs class in the Developer Toolkit where it doesn't set the ServiceProvider property - At the end of the constructor of the LocalPluginContext add the line:
this.ServiceProvider = serviceProvider;
I have seen some implementations of an IoC approach in Plugins - but IMHO it makes the plugin code way too complex. I'd recommend making your plugins lean and simple to avoid threading/performance issues.
There are multiple things I would worry about in this design request (not that it's bad, just that one should be aware of, and anticipate).
IOrganizationService is not multi-thread safe. I'm assuming that other aspects of the IServiceProvider are not as well.
Testing things at an IServiceProvider level is much more complicated due to the additional properties that have to be mocked
You'd need a method for handle logging if you ever decided to call logic that is currently in your plugin, outside of the plugin (e.g. a command line service).
If you don't want to be passing the object around everywhere, the simple solution is to create a static property on some class that you can set it upon plugin execution, and then access from anywhere.
Of course now you have to handle issue #1 from above, so it'd have to be a singleton manager of some sort, that would probably use the current thread's id to set and retrieve the value for that thread. That way if the plugin is fired twice, you could retrieve the correct context based on your currently executing thread. (Edit Rather than some funky thread id lookup dictionary, #shambulator's ThreadStatic property should work)
For issue #2, I wouldn't be storing the IServiceProvider as is, but split up it's different properties (e.g. IPluginExecutionContext, IOrganizationService, etc)
For issue #3, it might make sense to store an action or a function in your manager rather than the object values themselves. For example, if rather than storing the IPluginExecutionContext, store a func that accepts a string to log and uses the IPlurginExeuctionContext to log. This allows other code to setup it's own logging, without being dependent on executing from within a plugin.
I haven't made any of these plugins myself, but I would treat the IServiceProvider like an I/O device.
Get the data you need from it and convert that data to format that suits your plugin. Use the transformed data to set up the other classes. Get the the output from the other classes and then translate back to terms the IServiceProvider can understand and use.
Your input and output are dependent on the IServiceProvider, but the processing doesn't have to be.
From Eduardo Avaria at http://social.microsoft.com/Forums/en-US/f433fafa-aff7-493d-8ff7-5868c09a9a9b/how-to-avoid-passing-a-context-reference-among-classes
Well, as someone at SO already told you, the global variables restriction is there cause the plugin won't instantiate again if it's called within the same context (the object context and probably other environmental conditions), so any custom global variable would be shared between that instances, but since the context will be the same, there's no problem in assigning it to a global variable if you want to share it between a lot of classes.
Anyways, I'd rather pass the context on the constructors and share it have a little more control over it, but that's just me.
I have a method that I'm trying to call from a unit test.
This method will in real life be run from a background thread. It uses some code to kick off in the invoke updates to the UI thread (using Application.Current.Dispatcher.BeginInvoke .... ).
However Application.Current is null when being called from the unit tests.
I don't really what to put an if (Application.Current !=null) around everything to fix.
Is there any other way around this?
_statusUpdates is an ObservableCollection
Below is the part of the code in the method I'm looking to test (it is more of an integration test than a unit test to be fair).
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (EventHandler)delegate
{
_statusUpdates.Add(new StatusUpdate
{
DateTime = DateTime.Now,
Message = "Checking For Messages"
});
}, null, null);
The following code snippet works for me:
if (System.Windows.Application.Current == null)
{ new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; }
IIRC, I had a problem where Application was null using a WPF control embedded in a WinForms application and that code snippet was suggested as a solution to the problem in another question on StackOverflow (sorry, can not find the source). It solves the same problem in unit tests (and I don't believe the ShutdownMode property needs to be explicitly set in that case).
As already stated, you simply won't have an Application class during unit tests.
That said, there's an issue here I think needs addressing - by having code that relies on a defined static property, in your case Application.Current.Dispatch, you are now very tightly coupled to the specific implementation of that class, namely the WPF Application class, where you do not need to be.
Even if you simply wrap the idea of "the current root dispatcher" in a Singleton-style class wrapper, now you have a way of decoupling yourself from the vagaries of the Application class and dealing directly with what you care about, a Dispatcher:
Note, there are MANY MANY ways to write this, I'm just putting up the simplest possible implementation; hence, I will not be doing any multithreaded safety checks, etc.
public class RootDispatcherFetcher
{
private static Dispatcher _rootDispatcher = null;
public static Dispatcher RootDispatcher
{
get
{
_rootDispatcher = _rootDispatcher ??
Application.Current != null
? Application.Current.Dispatcher
: new Dispatcher(...);
return _rootDispatcher;
}
// unit tests can get access to this via InternalsVisibleTo
internal set
{
_rootDispatcher = value;
}
}
}
Ok, now this implementation is only slightly better than before, but at least you now have finer control over access to the type and are no longer strictly dependent on the existence of an Application instance.
Use Dispatcher.CurrentDispatcher instead of Application.Current.Dispatcher
Gets the System.Windows.Threading.Dispatcher for the thread currently
executing and creates a new System.Windows.Threading.Dispatcher if one
is not already associated with the thread.
You will not have an Application object in a unit-test runner. These are usually "console" based applications that simply run and execute non-UI code ("units").
I suggest you don't use a unit test framework to test UI-specific information, I suggest a automated UI testing framework to do that.
So the issue here is that somewhere your Application object has to be created. So you need to find where the System.Windows.Application (or some descendent) class is being instantiated.
If the project was built from a template, then you'll probably find this class in the App.xaml file. You just need to make sure that this gets instantiated somehow. Else, search your entire project for an Application class, and then you'll have to instantiate it manually. Should fix it.
i'm working on a fork of the Divan CouchDB library, and ran into a need to set some configuration parameters on the httpwebrequest that's used behind the scenes. At first i started threading the parameters through all the layers of constructors and method calls involved, but then decided - why not pass in a configuration delegate?
so in a more generic scenario,
given :
class Foo {
private parm1, parm2, ... , parmN
public Foo(parm1, parm2, ... , parmN) {
this.parm1 = parm1;
this.parm2 = parm2;
...
this.parmN = parmN;
}
public Bar DoWork() {
var r = new externallyKnownResource();
r.parm1 = parm1;
r.parm2 = parm2;
...
r.parmN = parmN;
r.doStuff();
}
}
do:
class Foo {
private Action<externallyKnownResource> configurator;
public Foo(Action<externallyKnownResource> configurator) {
this.configurator = configurator;
}
public Bar DoWork() {
var r = new externallyKnownResource();
configurator(r);
r.doStuff();
}
}
the latter seems a lot cleaner to me, but it does expose to the outside world that class Foo uses externallyKnownResource
thoughts?
This can lead to cleaner looking code, but has a huge disadvantage.
If you use a delegate for your configuration, you lose a lot of control over how the objects get configured. The problem is that the delegate can do anything - you can't control what happens here. You're letting a third party run arbitrary code inside of your constructors, and trusting them to do the "right thing." This usually means you end up having to write a lot of code to make sure that everything was setup properly by the delegate, or you can wind up with very brittle, easy to break classes.
It becomes much more difficult to verify that the delegate properly sets up each requirement, especially as you go deeper into the tree. Usually, the verification code ends up much messier than the original code would have been, passing parameters through the hierarchy.
I may be missing something here, but it seems like a big disadvantage to create the externallyKnownResource object down in DoWork(). This precludes easy substitution of an alternate implementation.
Why not:
public Bar DoWork( IExternallyKnownResource r ) { ... }
IMO, you're best off accepting a configuration object as a single parameter to your Foo constructor, rather than a dozen (or so) separate parameters.
Edit:
there's no one-size-fits-all solution, no. but the question is fairly simple. i'm writing something that consumes an externally known entity (httpwebrequest) that's already self-validating and has a ton of potentially necessary parameters. my options, really, are to re-create almost all of the configuration parameters this has, and shuttle them in every time, or put the onus on the consumer to configure it as they see fit. – kolosy
The problem with your request is that in general it is poor class design to make the user of the class configure an external resource, even if it's a well-known or commonly used resource. It is better class design to have your class hide all of that from the user of your class. That means more work in your class, yes, passing configuration information to your external resource, but that's the point of having a separate class. Otherwise why not just have the caller of your class do all the work on your external resource? Why bother with a separate class in the first place?
Now, if this is an internal class doing some simple utility work for another class that you will always control, then you're fine. But don't expose this type of paradigm publicly.
I am running into a design disagreement with a co-worker and would like people's opinion on object constructor design. In brief, which object construction method would you prefer and why?
public class myClass
{
Application m_App;
public myClass(ApplicationObject app)
{
m_App = app;
}
public method DoSomething
{
m_App.Method1();
m_App.Object.Method();
}
}
Or
public class myClass
{
Object m_someObject;
Object2 m_someOtherObject;
public myClass(Object instance, Object2 instance2)
{
m_someObject = instance;
m_someOtherObject = instance2;
}
public method DoSomething
{
m_someObject.Method();
m_someOtherObject.Method();
}
}
The back story is that I ran into what appears to be a fundamentally different view on constructing objects today. Currently, objects are constructed using an Application class which contains all of the current settings for the application (Event log destination, database strings, etc...) So the constructor for every object looks like:
public Object(Application)
Many classes hold the reference to this Application class individually. Inside each class, the values of the application are referenced as needed. E.g.
Application.ConfigurationStrings.String1 or Application.ConfigSettings.EventLog.Destination
Initially I thought you could use both methods. The problem is that in the bottom of the call stack you call the parameterized constructor then, higher up the stack, when the new object expects a reference to the application object to be there, we ran into a lot of null reference errors and saw the design flaw.
My feeling on using an application object to set every class is that it breaks encapsulation of each object and allows the Application class to become a god class which holds information for everything. I run into problems when thinking of the downsides to this method.
I wanted to change the objects constructor to accept only the arguments it needs so that public object(Application) would change to public object(classmember1, classmember2 etc...). I feel currently that this makes it more testable, isolates change, and doesn't obfuscate the necessary parameters to pass.
Currently, another programmer does not see the difference and I am having trouble finding examples or good reasons to change the design, and saying it's my instinct and just goes against the OO principles I know is not a compelling argument. Am I off base in my design thoughts? Does anyone have any points to add in favor of one or the other?
Hell, why not just make one giant class called "Do" and one method on it called "It" and pass the whole universe into the It method?
Do.It(universe)
Keep things as small as possible. Discrete means easier to debug when things inevitably break.
My view is that you give the class the smallest set of "stuff" it needs for it to do its job. The "Application" method is easier upfront but as you've seen already, it will lead to maintainence issues.
I thing Steve McConnel put it very succintly. He states,
"The difference between the
'convenience' philosophy and the
'intellectual manageability'
philosophy boils down to a difference
in emphasis between writing programs
and reading them. Maximizing scope
may indeed make programs easy to
write, but a program in which any
routine can use any variable at any
time is harder to understand than a
program that uses well-factored
routines. In such a program you can't
understand only one routine; you have
to understand all the other routines
with which that routine shares global
data. Such programs are hard to read,
hard to debug, and hard to modify." [McConnell 2004]
I wouldn't go so far as to call the Application object a "god" class; it really seems like a utility class. Is there a reason it isn't a public static class (or, better yet, a set of classes) that the other classes can use at will?