C# code timing in production - c#

I wish to implement switchable code timing facilities in my production code, the idea being that when performance issues are occurring on a user machine the performance logging can be turned on to provide useful data to indicate where issues are.
To this end my logic would be to have a factory class that would implement a bool property TrackPerformance and a method GetPerformanceTracker that returns either of NullPerformanceTracker or LoggingPerformanceTracker that implement an IPerformanceTracker interface.
The Null is obviously there to do nothing and the other would write out to a Log4Net logger which could potentially be split out from the normal logging if required. I'd use the StopWatch class for timings. So far so good.
The issue?
How best to implement this without it overly affecting performance itself?
I'm thinking of using compiler services attributes on a MarkElapsedTime method as
MarkElapsedTime(string message, [CallerMemberName] callerMemberName = "", [CallerLineNumber] int = 0)
Instantiating a timer at method level seems sub-optimal due to the number of factory calls. It therefore seems to be preferable to instantiate this at a class level, in which case I need to tie the MarkElapsedTime call to the relevant Start() call in order to measure the correct amount of elapsed time.
Loosely
class LoggingPerformanceTracker:IPerformanceTracker
{
private readonly ILog mLogger = LogManager.GetLogger(....);
private readonly StopWatch mStopWatch = new StopWatch();
private readonly Dictionary<int, TimeSpan> mElapsed = new Dictionary<int, TimeSpan>();
private int mNextId = 0;
public void MarkElapsedTime(int timerId, string message, [CallerMemberName] callerMemberName = "", [CallerLineNumber] int = 0)
{
var ts = mStopWatch.Elapsed.Subtract(mElapsed[timerId]);
if (mLogger.IsInfoEnabled)
mLogger.Info(string.Format("{0}: {1} - [{2}({3})]", message, ts, callerMemberName, callerLineNumber));
}
public int Start()
{
if (!mStopWatch.IsRunning)
mStopWatch.Start();
var key = mNextId;
mNextId++;
mElapsed.Add(key, mStopWatch.Elapsed);
return key;
}
}
I've not had to do this before and given that these measurement calls would be placed all over the codebase in key areas I'd ideally like to get it right first time.
Also is the use of the Log4Net logger a good or bad idea - I obviously need to see the data at some point whether that means logging in memory then dumping or sending to file straight off.

So here's how to do some dependency injection to solve this issue.
First, let's just say we have this code:
public class DoSomeWork
{
public void Execute()
{
Console.WriteLine("Starting");
Thread.Sleep(500);
Console.WriteLine("Done");
}
}
It's piece of code that performs some (potentially) long running task.
We might call it like this:
static void Main(string[] args)
{
var doSomeWork = new DoSomeWork();
doSomeWork.Execute();
Console.ReadLine();
}
Now, to add logging I could go thru the code base and add code like this:
public class DoSomeWork
{
public void Execute()
{
var sw = Stopwatch.StartNew();
Console.WriteLine("Starting");
Thread.Sleep(500);
Console.WriteLine("Done");
Console.WriteLine(sw.ElapsedMilliseconds);
}
}
But this means that if I want to add logging code to the entire code base I'm editing a lot of files and making my code more complicated.
There is a way to make this work without adding the logging code to each file.
To start with we need to introduce an interface with the Execute method to abstract the code we're calling.
public interface IDoSomeWork
{
void Execute();
}
Now the DoSomeWork class looks like this:
public class DoSomeWork : IDoSomeWork
{
public void Execute()
{
Console.WriteLine("Starting");
Thread.Sleep(500);
Console.WriteLine("Done");
}
}
Now the calling code looks like this:
static void Main(string[] args)
{
var context = Context.CreateRoot();
context.SetFactory<IDoSomeWork, DoSomeWork>();
var doSomeWork = context.Resolve<IDoSomeWork>();
doSomeWork.Execute();
Console.ReadLine();
}
Now, I've used a dependency injection framework that I wrote for this, but you could use Castle Windsor, Ninject, etc.
The line Context.CreateRoot() creates a dependency injection container. The context.SetFactory<IDoSomeWork, DoSomeWork>() configures the container to know that when I ask for an instance of IDoSomeWork to actually return an instance of DoSomeWork.
The line var doSomeWork = context.Resolve<IDoSomeWork>() asks to container to try to resolve (create or return) an instance of an object that implements IDoSomeWork.
From there the code runs like the original code.
Now I can write a logging class that "decorates" the concrete class.
public class DoSomeWorkLogger : IDoSomeWork, IDecorator<IDoSomeWork>
{
public void Execute()
{
var sw = Stopwatch.StartNew();
this.Inner.Execute();
Console.WriteLine(sw.ElapsedMilliseconds);
}
public IDoSomeWork Inner { get; set; }
}
This class implements IDoSomeWork as well as a special interface IDecorator<IDoSomeWork> required by my container to allow this class to act as a decorator.
So now the calling code looks like this:
static void Main(string[] args)
{
var context = Context.CreateRoot();
context.SetFactory<IDoSomeWork, DoSomeWork>();
context.SetDecorator<IDoSomeWork, DoSomeWorkLogger>();
var doSomeWork = context.Resolve<IDoSomeWork>();
doSomeWork.Execute();
Console.ReadLine();
}
The line context.SetDecorator<IDoSomeWork, DoSomeWorkLogger>() now tells the container that there is a decorator for the IDoSomeWork interface.
So what now happens when the line var doSomeWork = context.Resolve<IDoSomeWork>() is called is that an instance of DoSomeWork is created like before, but also an instance of DoSomeWorkLogger is created. The Inner property of the DoSomeWorkLogger instance is set with the instance of the DoSomeWork and the DoSomeWorkLogger instance is returned from the Resolve method.
So now when the doSomeWork.Execute() method is call then the logger code is run which in turn calls the actual execute code.
The DoSomeWork code doesn't need to change for me to add the logging functionality.
Now this code as it stands isn't perfect yet as we have all of the SetFactory and SetDecorator code that would create dependencies that we want to avoid.
So here's how we get around it.
First the IDoSomeWork, DoSomeWork, and DoSomeWorkLogger code are moved into three separate assemblies.
Then DoSomeWork and DoSomeWorkLogger have two special attributes added. They look like this:
[Factory(typeof(IDoSomeWork))]
public class DoSomeWork : IDoSomeWork { ... }
[Decorator(typeof(IDoSomeWork))]
public class DoSomeWorkLogger : IDoSomeWork, IDecorator<IDoSomeWork> { ... }
Now I can change the calling code to this:
static void Main(string[] args)
{
var config = XDocument.Load(#"fileName");
var context = Context.LoadRoot(config);
var doSomeWork = context.Resolve<IDoSomeWork>();
doSomeWork.Execute();
Console.ReadLine();
}
The container is now configured using an XML file. The format of the XML isn't important, but what is is that it can be changed without recompiling the code. So by changing the XML to not include the assembly that the DoSomeWorkLogger class is defined in will effectively remove the logging. Add that assembly and instantly the logging code is added back in with no recompilation necessary.
Simple. :-)

Related

Swapping out logging action on reused instance based on calling instance

I have a class instance (Eli) which is used in multiple contexts, and which needs to log messages, independent of (but correctly in each) context:
public class Eli
{
void LogMessage(string msg)
{
///what to do here?
}
public void GrillTheCat()
{
LogMessage("I deed it";)
}
}
public class EliWrapper
{
Eli _eli;
Action<string> _logAction;
public EliWrapper(Eli eli, Action<string> logAction)
{
_eli = eli;
_logAction = logAction;
}
public void GrillTheCat()
{
_eli.GrillTheCat(); //I want LogMessage in Eli to invoke the _logAction of this calling instance
}
}
var eli = new Eli();
var wrapper1 = new EliWrapper(eli, msg => Console.WriteLine(msg));
var wrapper2 = new EliWrapper(eli, msg => File.AppendAllText(msg + "\n"));
I realize I could pass in the logger to the GrillTheCat function, but in my real situation, Eli has >10 functions and I don't want to clutter up all of the function signatures just for the sake of logging.
I also realize I could define a LogAction property on Eli, then have the wrappers assign their _logAction value to that property prior to invoking Eli's function, but again I have many functions and it would be somewhat tedious to wrap each one.
What I'm hoping for is a reflection-based solution where Eli's LogMessage function just steps up a couple layers of the call stack, and accesses the wrapper instance's _logAction directly.
What I'm hoping for is a reflection-based solution where Eli's LogMessage function just steps up a couple layers of the call stack, and accesses the wrapper instance's _logAction directly.
I wasn't able to find any reasonable way to access instances outside the current executing method without you heavily modifying signatures(you stated you didn't want to do).
Although I generally would not recommend what you're trying to do because of the tight coupling and general lack of extensibility and intuitiveness - However, I figured out a solution that almost fits the bill.
It is not possible, at least from what I was able to research, to access instance data from calling members. Which is to say you can't walk back up the stack and access instanced variables or objects all will-nilly, unless you explicitly capture and pass them down the stack as you're - err.. um "stacking"?.
The way we work around this is simply by declaring your _logAction as a static member. That way we don't need to access the instance you have of EliWrapper.
What this doesn't do for you is allow you to have multiple EliWrappers with different _logAction's becuase they're static.
Unfortunately without access to the individual instance(which you can't get from the stack - there's no way for Eli to know what EliWrapper wants to do without at least some of the modifications you explicitly wanted to avoid(In my opinion).
Where do we go from here?
Consider
Consider Modifying Eli so it can be used as a base-class that has different versions that log things differently.
Consider Modifying Eli to implement overrides that accept a Action<string> as a override for it's default logging.
Alternatively, but not recommended
Pass the instance of the caller to Eli so it can access instanced(non-static) members on EliWrapper so you don't need to make _logAction static(this would be a simple modification to the code i have provided to you, but would require changing all of Eli's signatures to accommodate object caller.
Store instances of EliWrapper somewhere you can access without instance, such as a static class, where you can access their instance data using reflection without explicitly passing their instances to Eli
Here's the script to access the static field using the stack
public class Eli
{
private readonly Action<string> DefaultLogger = (s) => Console.WriteLine(s);
void LogMessage(string msg)
{
// get the stack so we can get advanced information about
// who called us (CallerMemberNameAttribute was another alternative, but would incur more complex code)
StackTrace stack = new(false);
// step 2 frames up(or however many to get out of Eli and back to the 'caller'
var caller = stack.GetFrame(2)?.GetMethod()?.DeclaringType;
if (caller != null)
{
// check to see if the type that called GrillTheCat()
// has a static private field with the name '_logAction'
var possibleLoggerInCaller = caller.GetField("_logAction", BindingFlags.Static | BindingFlags.NonPublic);
if (possibleLoggerInCaller != null)
{
// get the static value of that field
var possibleLogger = possibleLoggerInCaller.GetValue(null);
// verify that the type of that logger is infact a Action<string>
// since that's what we use to log
if (possibleLogger is Action<string> logger)
{
// log the msg using the overriden logger instead of the default one
logger.Invoke(msg);
return;
}
}
}
// if we got here there wasn't a _logAction in the call stack at frame 2
// so give up and use our default logger
DefaultLogger.Invoke(msg);
}
public void GrillTheCat()
{
LogMessage("I deed it");
}
}
public class EliWrapper
{
Eli _eli;
private static Action<string> _logAction;
public EliWrapper(Eli eli, Action<string> logAction)
{
_eli = eli;
_logAction = logAction;
}
public void GrillTheCat()
{
_eli.GrillTheCat(); //I want LogMessage in Eli to invoke the _logAction of this calling instance
}
}
For my needs, I've gone with throwing exceptions. This procedurally does what I asked: only notifies the calling instance of the message, and requires no modification of function signatures.
Consider implementing a decorator for Eli that implements logging. Here is a rudimentary example that demonstrates this:
// If you haven't already: define an interface for Eli
public interface IEli
{
// Define all Eli's public members
}
// Let Eli implement IEli
public class Eli : IEli
{
...
}
With the existence of the new IEli interface, you can now implement a decorator:
public class LoggingEli : IEli
{
private readonly IEli decoratee;
private readonly Action<string> logAction;
public LoggingEli(IEli decoratee, Action<string> logAction)
{
this.decoratee = decoratee;
this.logAction = logAction;
}
// Implement all IEli members by calling the log action and forwarding
// the call to the decorated IEli instance:
public object SomeEliMethod(string param1, int param2)
{
this.logAction(nameof(SomeEliMethod) + " called for " + param1);
return this.decoratee.SomeEliMethod(param1, param2);
}
// Same for all other 9 IEli methods.
}
Using the new IEli interface and the LoggingEli decorator, you can now construct the following object graph:
var eli = new Eli();
var consoleEli = new LoggingEli(eli, msg => Console.WriteLine(msg));
var fileEli = new LoggingEli(eli, msg => File.AppendAllText(msg + "\n"));
Decorators have the advantage that you are able to add behavior to a class without having to change the original class. Downside is that it is only possible to add behavior at the start or end of the original method, and the behavior only has access to all the parameters going in and out of the called method. In your case, you can't log halfway the method, and can't log anything information that is kept internal to Eli.
In case you need to log halfway or use information that is internal to Eli, you will need to inject the logger into Eli's constructor.

Detecting that a method is called without a lock

Is there any way to detect that a certain method in my code is called without using any lock in any of the methods below in the call stack?
The goal is to debug a faulty application and find out if certain pieces of code aren't thread safe.
This seems like a decent use case for AOP (aspect oriented programming). A very basic summary of AOP is that its a method of dealing with cross cutting concerns to make code dry and modular. The idea is that if you're doing something to every method call on an object (eg. logging each call) instead of adding a log at the start and end of each method you instead you inherit the object and do that outside of the class as to not muddy its purpose.
This can be done a few ways and I'll give you an example of two. First is manually (this isn't great but can be done very easily for small casses).
Assume you have a class, Doer with two methods Do and Other. You can inherit from that and make
public class Doer
{
public virtual void Do()
{
//do stuff.
}
public virtual void Other()
{
//do stuff.
}
}
public class AspectDoer : Doer
{
public override void Do()
{
LogCall("Do");
base.Do();
}
public override void Other()
{
LogCall("Other");
base.Other();
}
private void LogCall(string method)
{
//Record call
}
}
This is great if you only care about one class but quickly becomes unfeasible if you have to do it for many classes. For those cases I'd recommend using something like the CastleProxy library. This is a library which dynamically creates a proxy to wrap any class you want. In combination with an IOC you can easily wrap every service in your application.
Here's a quick example of using CastleProxy, main points being use ProxyGenerator.GenerateProxy and pass in IInterceptors to do stuff around method calls:
[Test]
public void TestProxy()
{
var generator = new ProxyGenerator();
var proxy = generator.CreateClassProxy<Doer>(new LogInterceptor());
proxy.Do();
Assert.True(_wasCalled);
}
private static bool _wasCalled = false;
public class LogInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Log(invocation.Method.Name);
invocation.Proceed();
}
private void Log(string name)
{
_wasCalled = true;
}
}
Now, the logging portion. I'm not sure you really NEED this to be lockless, short locks might be enough but lets proceed thinking you do.
I don't know of many tools in C# that support lock free operations but the the simplest version of this I can see is using Interlocked to increment a counter of how many instances are in the method at any given time If would look something like this:
[Test]
public void TestProxy()
{
var generator = new ProxyGenerator();
var proxy = generator.CreateClassProxy<Doer>(new LogInterceptor());
proxy.Do();
Assert.AreEqual(1, _totalDoCount);
}
private static int _currentDoCount = 0;
private static int _totalDoCount = 0;
public class LogInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == "Do")
{
var result = Interlocked.Increment(ref _currentDoCount);
Interlocked.Increment(ref _totalDoCount);
if(result > 1) throw new Exception("thread safe violation");
}
invocation.Proceed();
Interlocked.Decrement(ref _currentDoCount);
}
}
Interlocked uses magical register magic to do thread safe operation (Compare-And-Swap I believe, but I don't really know). If you need more context than just "It Happened". You can use a concurrent stack or a concurrent queue which are lockless (they use interlock as well: https://msdn.microsoft.com/en-us/library/dd997305.aspx/). I would include a timestamp on these though, since I haven't used them enough to know if they promise to return elements in the order they occurred.
Like I said above, you might not NEED lock free operations but this should. I don't know if any of this is a perfect fit for you since I don't know your exact problem but it should provide you some tools to tackle this.
You could host the CLR yourself, and track the locks taken using the IHostSyncManager::CreateMonitorEvent method. You'd then need to expose your own mechanism from your host to your method called say "IsLockTaken()". You could then call that from your method in your actual code.
I think it is possible, but it would be quite a lot of work and almost certainly a complete distraction from the problem you're trying to solve, but no doubt a lot of fun!
Here's an interesting read on Deadlock detection https://blogs.msdn.microsoft.com/sqlclr/2006/07/25/deadlock-detection-in-sql-clr/

unit test static constructor w/ different config values

I have a class with a static constructor which I use to read the app.config values. How do I unit test the class with different configuration values. I'm thinking of running each test in different app domain so I can have static constructor executed for each test - but I have two problems here:
1. I do not know how to run each test run in separate app domain and
2. how do I change configuration settings at run time?
Can someone please help me with this? Or anyone has a better solution? Thanks.
Personally I would just stick your static constructor into a static method then execute that method in the static block.
You don't need to test .Net being able to load data from config files.
Instead, try to concentrate on testing your own logic.
Change your class so that it gets the configuration values from its constructor (or via properties), and then test it as you would with any other dependency.
Along the way you have also moved your class towards SRP.
As per the configuration loading - concentrate this logic in a separate, non-static class.
EDIT:
Separate the configuration logic into another class. something like this:
public static class ConfigurationLoader
{
static ConfigurationLoader()
{
// Dependency1 = LoadFromConfiguration();
// Dependency2 = LoadFromConfiguration();
}
public static int Dependency1 { get; private set; }
public static string Dependency2 { get; private set; }
}
Then, when you instantiate your class, inject it with the dependencies:
public class MyClass
{
private readonly int m_Dependency1;
private readonly string m_Dependency2;
public MyClass(int dependency1, string dependency2)
{
m_Dependency1 = dependency1;
m_Dependency2 = dependency2;
}
public char MethodUnderTest()
{
if (m_Dependency1 > 42)
{
return m_Dependency2[0];
}
return ' ';
}
}
public class MyClassTests
{
[Fact]
public void MethodUnderTest_dependency1is43AndDependency2isTest_ReturnsT()
{
var underTest = new MyClass(43, "Test");
var result = underTest.MethodUnderTest();
Assert.Equal('T', result);
}
}
...
var myClass = new MyClass(ConfigurationLoader.Dependency1, ConfigurationLoader.Dependency2);
You could go on and use IOC containers, but your problem of testing MyClass with different inputs is solved by this simple testable design.
If you read from (Web)ConfigurationManager.AppSettings, that is just a NameValueCollection, so you can replace your code that reads ConfigurationManager.AppSettings directly with code, that reads from any NameValueCollection.
Just move out your actual configuration parsing to a static method from the static ctor. Static ctor calls that static method and passes ConfigurationManager.AppSettings, but you can call that parser method from the test code, and verify the config parsing without actually touching a file, or messing with appdomains.
But on the long run, really inject your configuration parameters as seldary suggested. Create a configuration class, read the actual values at application start, and set up your IoC container to supply the same configuration instance to all requesters.
This makes further testing easier too, because you classes don't read from a global static configuration instance. You can just pass in a specific configuration instance for differet tests. Of course create a factory method for your tests, to construct a global configuration, so you don't have to do it manually all the time...
I had the same exact problem recently. The only difference was that the configuration value was coming from database instead of app.config. I was able to resolve it using TypeInitializer.
[Test]
public void TestConfigurationInStaticConstructor()
{
// setup configuraton to test
// ...
// init static constructor
ReaderTypeInit();
// Assert configuration effect
// ...
// reset static ctor to prevent other existing tests (that may depend on original static ctor) fail
ReaderTypeInit();
}
// helper method
private void ReaderTypeInit()
{
typeof(< your class with static ctor>).TypeInitializer.Invoke(null, new object[0]);
}

Moq - mock.Object.MyMethod mocking does not work

I have a strange trouble. I am not too familiar with Moq, being more a GUI guy. I tried to mock a factory method in my code. The factory looks like this, and returns a ISettings instance which does many IO Operations. I want it to return a memory only ISettings instance to accelerate my test.
public class SettingsFactory
{
internal ISettings mSettingsImpl;
internal virtual ISettings CreateOrGetSettings()
{
return mSettingsImpl ?? (mSettingsImpl = new XmlSettings());
}
}
and the mock is
var imocked = new Mock<SettingsFactory>() {CallBase = false};
imocked.Setup(x => x.CreateOrGetSettings()).Returns(new NonPersistingSettings());
var tryToSeeTheType = imocked.Object.CreateOrGetSettings();
the tryToSeeTheType is however XMLSettings and not NonPersistingSettings as I would expect. Stepping through results into the code shown me that it goes directly into the original factory method. Any suggestions what I do wrong here?
The "Object" property of a mocked object is not actually an instance of the class you are trying to mock.
The purpose of a mock is to be able to replace an object the method you are trying to test depends on.
Imagine that your SettingsFactory performs very expensive operations like for example accessing the network or a database or the file system. You do not want your test to access those expensive resources so you create a mock. I would be something like this:
public class ClassThatUsesSettingsFactory
{
private readonly SettingsFactory _settingsFactory;
public ClassThatUsesSettingsFactory(SettingsFactory settingsFactory)
{
_settingsFactory = settingsFactory;
}
public void MethodThatCallsSettingsFactory()
{
//... do something
var settings = _settingsFactory.CreateOrGetSettings();
//... do something
}
}
By doing this you are able to replace the SettingsFactory with a mock on your unit test like so:
[TestMethod]
public void MakeSureSettingsFactoryIsCalled()
{
var settingsFactoryMock = new Mock<SettingsFactory>();
settingsFactoryMock.Setup(f => f.CreateOrGetSettings(), Times.Once).Verifiable();
var subjectUnderTest = new ClassThatUsesSettingsFactory(settingsFactoryMock.Object);
subjectUnderTest.MethodThatCallsSettingsFactory();
settingsFactoryMock.Verify();
}
This unit test is basically only making sure that the method CreateOrGetSettings gets called once and only once when the MethodThatCallsSettingsFactory gets executed.
What Moq does is to create a different class with a different implementation of its virtual method that will, most likely, set a flag to true once it gets called and then check the value of that flag on the "Verify" method.
There is a lot to grasp here so I hope it is clear enough since you mentioned that you do not have a lot of experience with Moq.

C# Instance Class with Static Methods - using methods differently between threads

Hello I have this code here:
Memory.OpenProcess(Processes[0].Id);
Hook.Apply(........);
Memory and Hook are both non-static classes, and openprocess and Apply are both static methods within those classes.
However, the problem is, for each instance of my Memory or Hook, I want to have a different process opened, and a different Hook applied.
What I want to do is:
Memory newMemory = new Memory();
newMemory.OpenProcess(processes[1].Id);
Hook newHook = new Hook();
newHook.Apply(....);
But of course I cannot do this because the methods are static and not particular to each instance.
I cannot change the static methods because these methods are coming from a dll in which I do not have access to the source code.
Any ideas?
**Edit: I want to do this so I can avoid having to rehook the process every time a new thread comes along that is working with a different process.
It seems that you cannot do that by design. The implementor of the classes from the dll you are consuming might have explicitly want to avoid the functionality you are trying to achieve.
You can load each thread in different AppDomain, that would give you different static methods.
Also, ThreadStaticAttribute might be helpful for you. Don't sure if it fits you, but give it a look.
Upd: More info about using AppDomains. Lets assume, that you have 3-rd party class Memory defined as follows. (And you cannot change it, and it uses inner static variables)
// Cannot be changed
public class Memory
{
static int StaticId;
public static void OpenProcess(int id)
{
StaticId = id;
}
public static int GetOpenedId()
{
return StaticId;
}
}
You can write a wrapper, deriving from MarshalByRefObject (that's important):
class MemoryWrap : MarshalByRefObject
{
public void OpenProcess(int id)
{
Memory.OpenProcess(id);
}
public int GetOpenedId()
{
return Memory.GetOpenedId();
}
}
So if you create instances of MemoryWrap not by new keyword, but using AppDomain.CreateInstanceAndUnwrap in another domain, each instance would have it's own static contexts. Example:
class Program
{
static void Main(string[] args)
{
var type = typeof(MemoryWrap);
var domain1 = AppDomain.CreateDomain("Domain 1");
var memory1 = (MemoryWrap)domain1.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
var domain2 = AppDomain.CreateDomain("Domain 2");
var memory2 = (MemoryWrap)domain2.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
memory1.OpenProcess(1);
memory2.OpenProcess(2);
Console.WriteLine(memory1.GetOpenedId());
Console.WriteLine(memory2.GetOpenedId());
Console.ReadLine();
}
}
It would print:
1
2
PS: in that example I didn't do the clean up just for readability (unloading domains with AppDomain.Unload() and other things). Don't forget to do it in you code. + There is some mess with lifetime of objects in another domain, but it is next level of problems)))
I'm not sure I fully understand the question, but I will try to answer anyways.
You could define two new classes:
public class MemoryInstance : Memory
{
private var m_instanceProcessId;
public MemoryInstance(var processId) : base()
{
m_instanceProcessId = processId;
}
public void OpenProcess()
{
Memory.OpenProcess(m_instanceProcessId);
}
}
public class HookInstance: Hook
{
private var m_hookId;
public HookInstance(var hookId) : base()
{
m_hookId = hookId;
}
public void Apply()
{
Hook.Apply(m_hookId);
}
}
Then in your code you could call:
public static void Main(String[] args)
{
MemoryInstance newMemory = new MemoryInstance(processes[1].Id);
HookInstance newHook = new HookInstance(hookId);
newMemory.OpenProcess();
newHook.Apply();
}
See , if the API writers are doing that it must be for some reason , you should consult your API writers for he reason or if they can provide you something at instamnce level.
BUT for circumvent your situation , you can use the method provided The_Smallest above.
or you can make use of Reflection as shown below
Memory m = Activator.CreateInstance("Your Dll Name", true) , here true stands for the calling of private constructor.
But i am not convinced , you should do it , you first call to the API writer to get the reason of doing this.

Categories