Patterns for decorating private methods of a class - c#

In the below class I have a public method called ProcessMessage. This method is responsible for processing the incoming messages. Processing a message involves different stage. I want to decorate this class in such a way that I can publish performance counter values from each stage of the message processing.
I know I can override the ProcessMessage method and rewrite the logic once again with publishing performance counter values. But is there any better way / pattern which I can apply, so that I don’t have to duplicate the logic once again in the decorated class.
public class MessageProcessor
{
public void ProcessMessage()
{
ConvertReceivedMessage();
SendToThirdParty();
ReceiveResponse();
ConvertResponseMessage();
SendResponseToClient();
}
private void ConvertReceivedMessage()
{
//here I want to publish the performance counter value from the decorated class
}
private void SendToThirdParty()
{
//here I want to publish the performance counter value from the decorated class
}
private void ReceiveResponse()
{
//here I want to publish the performance counter value from the decorated class
}
private void ConvertResponseMessage()
{
//here I want to publish the performance counter value from the decorated class
}
private void SendResponseToClient()
{
//here I want to publish the performance counter value from the decorated class
}
}
Thanks.

Use a list of IProcessor objects instead of a bunch of methods. Going this way you are able to add/skip/change call order. In your IProcessor declare Process(PerformanceContext context) method and implement PerformanceContext class to exchange some values like StartTime, NumberOfCalls etc.
Good luck!

Related

Unit Testing a method containing Environment.Exit() call within it

I have a public method say,
public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;
//Process tremination
Environment.Exit();
}
This method terminates whenever it is called. However, it will update the Global Error Count which i'm suppose to test. Is there any way to perform Unit Testing on this method?
I'm Using NUnit Framework for Unit Testing.
This method is designed to be difficult to test!
Most obviously, because it terminates the application when called. But also because it changes a global (I assume static) variable. Both of these things prevent writing a good unit test that calls the method.
Three ways around this:
1. Eliminate the method
2. Don't test the method
3. Modify the method
Option 1. If this method only called exit, then you could simply drop it and call Exit directly. However, that would make some other method difficult to test, so this isn't really a great option.
Option 2. Sometimes a method is so simple that you can avoid testing it. Whether this is such a method depends on how gblErrorCount is used elsewhere. It would appear, however, that incrementing the count has no effect, since the process immediately exits.
Option 3. Modify the method and those methods that call it. One approach would be to use an event handling mechanism and terminate the app in the event handler. You could make this easier to test by injecting a different event handler when running tests.
IOW, this is basically a pretty untestable method. Hopefully, you are in control of the system under test and can change it.
This question contains answers that show how Environment.Exit() can be tested.
Constructor Dependency Injection
One option is to convert it into a dependency by injecting it through an interface :
interface ITerminator
{
void Exit();
}
class RealTerminator
{
void Exit()=>Environment.Exit();
}
public class MyErrorChecker
{
ITerminator _terminator;
public class MyErrorChecker(ITerminator terminator)
{
_terminator=terminator;
}
public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;
//Process tremination
_terminator.Exit();
}
}
The test project will implement a fake terminator class that sets a flag if Exit is called:
class FakeTerminator:ITerminator
{
public bool Called{get;private set;}
public void Exit()
{
Called=true;
}
}
Mocking
Another option is to mock it by extracting the call to a virtual method that can be replaced in a mock class :
public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;
//Process tremination
ForceExit();
}
internal virtual void ForceExit()
{
Environment.Exit();
}
The test project could create a mock error checker class:
class MockErrorChecker:MyErrorChecker
{
public bool Called{get;private set;}
public override void ForceExit()
{
Called=true;
}
}
Function injection
This option isn't included in the linked question. Pass an exit Action as a parameter to ErrorEncounter whose default will be to call Environment.Exit() :
public void ErrorEncounter(Action exitFn=null)
{
var doExit=exitFn ?? (()=>Environment.Exit());
//Global Error Counter
gblErrorCount++;
//Process tremination
doExit();
}
The test could pass its own function that sets a flag:
[Test]
public void Test_Exit_Is_Called
{
bool called;
void fakeExit() { called=true; }
thatClass.ErrorEncounter(fakeExit);
Assert.True(called);
}

Trigger a method before other method execution

Is there a way to call a method to be executed before another method, like a trigger?
Something like an attribute that indicates the method to be executed, like this:
[OnBefore(MethodToBeExecutedBefore)]
public void MethodExecutedNormally()
{
//method code
}
I have a situation that I need to call a check method very often, and most of the time, they are before methods that take too long to execute.
There is no built in way to achieve this result, if you are using a dependency injection mechanism you can use the interception facilities if the DI framework supports this. (Ex: Unity, NInject)
If you want to go low level you can also use Reflection.Emit to create a derived class at runtime, that overrides methods with a particular attribute that invokes any extra functionality you want, but that is more difficult.
What you are talking about is called AOP or Aspect Oriented Programming.
There are no built-in options in C#. While Attributes exists, there is no mechanism to take any actions with them. You always need a piece of code that reads those attributes and then does something. Attributes themselves are only metadata and markers.
As far as external tools go, Postsharp is the de-facto standard AOP postcompiler for .NET, but it's not free (at least not for real use, there is a free version you may want to try, maybe it's enough for your use-case).
I think you should consider an event driven approach.
You could create an interface and some base classes to handle the event, then have your long running classes inherit from it. Subscribe to the event and handle accordingly:
public delegate void BeforeMethodExecutionHandler<TArgs>(ILongRunningWithEvents<TArgs> sender, TArgs args, string caller);
public interface ILongRunningWithEvents<TArgs>
{
event BeforeMethodExecutionHandler<TArgs> OnBeforeMethodExecution;
}
public class LongRunningClass<TArgs> : ILongRunningWithEvents<TArgs>
{
private BeforeMethodExecutionHandler<TArgs> _onBeforeMethodExecution;
public event BeforeMethodExecutionHandler<TArgs> OnBeforeMethodExecution
{
add { _onBeforeMethodExecution += value; }
remove { _onBeforeMethodExecution -= value; }
}
protected void RaiseOnBeforeMethodExecution(TArgs e, [CallerMemberName] string caller = null)
{
_onBeforeMethodExecution?.Invoke(this, e, caller);
}
}
public class ConcreteRunningClass : LongRunningClass<SampleArgs>
{
public void SomeLongRunningMethod()
{
RaiseOnBeforeMethodExecution(new SampleArgs("Starting!"));
//Code for the method here
}
}
public class SampleArgs
{
public SampleArgs(string message)
{
Message = message;
}
public string Message { get; private set; }
}
Sample usage:
public static void TestLongRunning()
{
ConcreteRunningClass concrete = new ConcreteRunningClass();
concrete.OnBeforeMethodExecution += Concrete_OnBeforeMethodExecution;
concrete.SomeLongRunningMethod();
}
private static void Concrete_OnBeforeMethodExecution(ILongRunningWithEvents<SampleArgs> sender, SampleArgs args, string caller)
{
Console.WriteLine("{0}: {1}", caller ?? "unknown", args.Message);
}
The message SomeLongRunningMethod: Starting! will be output before the long-running method executes.
You could add the caller name to the args. I whipped this out real quick to illustrate.
UPDATE: I see you added tags for ASP.NET MVC. The concept still applies to controllers as controllers are just classes.

First experience of using interfaces in C#?

I have an interface:
interface ISqlite
{
void insert();
void update();
void delete();
void select();
}
And custom service class:
class SqliteService
{
public SQLiteDatabase driver;
public SqliteService() {
SqliteConnection(new SQLiteDatabase());
}
public void SqliteConnection(SQLiteDatabase driver)
{
this.driver = driver;
}
public void select(ISqlite select) {
select.select();
}
public void insert(ISqlite insert) {
insert.insert();
}
public void delete(ISqlite delete)
{
delete.delete();
}
}
And last class Pacients that realizes ISqlite interface:
class Pacients: ISqlite
{
public List<ClientJson> pacients;
public Pacients() {
this.pacients = new List<ClientJson>();
}
public void add(ClientJson data) {
this.pacients.Add(data);
}
public void insert()
{
throw new NotImplementedException();
}
/* Others methos from interface */
}
I try to use my code like as:
/* Create instance of service class */
SqliteService serviceSqlite = new SqliteService();
/* Create instance of class */
Pacients pacient = new Pacients();
pacient.add(client);
serviceSqlite.insert(pacient);
As you can see above I send object pacient that realizes interface ISqlite to service. It means that will be called method insert from object pacient.
Problem is that I dont understand how to add data in this method using external class: SQLiteDatabase()? How to get access to this.driver in service class from object pacient?
Edit 1
I think I must move instance of connection new SQLiteDatabase() to db inside Pacients class is not it?
Generally speaking, I would favor a solution where the data objects themselves don't know anything about how they're stored, i.e. they have no knowledge of the class that communicates with the database. Many ORMs do just that.
Of course it might not be easy depending on the specifics of your situation... Try to examine what your methods on each object actually need; generally speaking they need the values of properties, and what column each property corresponds to, right? So any external class can do this if it knows these bits of information. You can specify the name of the column with a custom attribute on each property (and if the attribute isn't there, the column must have the same name as the property).
And again, this is the most basic thing that ORMs (Object Relational Mappers) do, and in addition they also manage more complicated things like relationships between objects/tables. I'm sure there are many ORMs that work with SqlLite. If you're OK with taking the time to learn the specifics of an ORM, that's what I would recommend using - although they're not silver bullets and will never satisfy all possible requirements, they are in my opinion perfect for automating the most common day to day things.
More to the point of the question, you can of course make it work like that if you pass the SQLiteDatabase object to the methods, or keep it in a private field and require it in the constructor or otherwise make sure that it's available when you need it; there's no other simple solution I can think of. And like you pointed out, it implies a certain degree of coupling.
You can change the signature of interface's methods to pass an SQLiteDatabase object.
interface ISqlite
{
void insert(SQLiteDatabase driver);
void update(SQLiteDatabase driver);
void delete(SQLiteDatabase driver);
void select(SQLiteDatabase driver);
}
Example call from the service:
public void insert(ISqlite insert)
{
insert.insert(driver);
}
I think you can figure out the rest by yourself.

How can I get the function/action name that custom attribute is attached to while it is executing?

Ideally, I want to create a filter that inherits from ActionFilterAttribute that I can apply in Global.asax that will create performance counters for all the actions in my application. That problem is easy, but the issue is that I want the performance counters to have the method signature of the action that they are attached to in their name. However, I can't find a way to extract the method name of the method that an attribute is attached to during construction. This is causing me to have to apply the attributes to each action individually and pass in their signature as a parameter. However, this poses obvious problems (i.e. updates to method signature not automatically synchronized with perf counter naming).
To simplify the problem, if I attach an attribute to a method of any kind, can I access the name/signature of the method that it is attached to? I'm looking for a generic solution that works for attributes that don't derive from ActionFilterAttribute also.
public class SomeAttribute : ActionFilterAttribute
{
public string FunctionSignature { get; set; }
public SomeAttribute()
{
this.FunctionName = { HOW DO I GET THE NAME OF THE METHOD I'M ON WITHOUT PASSING IT IN AS AN INPUT ARGUMENT? }
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Some code to update perf counter(s) with recorded time that will use string.Format("{0}: Avg. Time or Something", this.FunctionSignature).
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Some code to record time.
}
}
[SomeAttribute]
public void SomeMethod()
{
// Some code.
}
Find the name of executing action:
var actionName = filterContext.ActionDescriptor.ActionName;
or alternatively
var actionName = filterContext.RouteData.Values["action"] as string
Find parameters (Name, Type, DefaultValue):
var parameters = filterContext.ActionDescriptor.GetParameters();
Find parameters values:
var value= filterContext.ActionParameters["parameterName"];
As I understand, you want generic solution for that, not related to ActionFilterAttribute or asp.net at all. Then you can use Aspect Oriented Programming, and best implementation of that for .NET is PostSharp. Free version of that library is enough to achieve your goal. For example:
class Program
{
static void Main(string[] args)
{
Test();
Console.ReadKey();
}
[Measure]
public static void Test() {
Thread.Sleep(1000);
}
}
[Serializable]
public sealed class MeasureAttribute : OnMethodBoundaryAspect
{
private string _methodName;
[NonSerialized]
private Stopwatch _watch;
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) {
base.CompileTimeInitialize(method, aspectInfo);
// save method name at _compile_ time
_methodName = method.Name;
}
public override void OnEntry(MethodExecutionArgs args) {
base.OnEntry(args);
// here you have access to everything about method
_watch = Stopwatch.StartNew();
}
public override void OnExit(MethodExecutionArgs args) {
base.OnExit(args);
if (_watch != null) {
_watch.Stop();
Console.WriteLine("Method {0} took {1}ms", _methodName, _watch.ElapsedMilliseconds);
}
}
public override void OnException(MethodExecutionArgs args) {
base.OnException(args);
// do what you want on exception
}
}
Here we create MeasureAttribute which you can apply on any method and intercept method invocation in many points. Even more, you can even apply it dynamically to all methods based on some condition (i.e. all methods in given class or whole assembly, or whatever). It also allows you to save some information in compile time, to increase perfomance. In example above we save method name once during compilation.
PostSharp (and AOP in general) can do much more than that.
I assume that your method name will be the same as filterContext.ActionDescriptor.ActionName.
And you can get the Controller instance from filterContext.Controller.
So having class and method name you can get the signature, however not in the constructor.
I can imagine two alternatives. You could reflect on all the types in classes in loaded assemblies - not very direct but works. Problem is - I'm not sure if the interesting assemblies are even loaded in time - you might have to proactively load them using config information as a guide.
The attributes can be queries on the various MethodInfo/PropertyInfo objects that you can interrogate reflectively. Then, the attributes are queried with MemberInfo.GetCustomeAttributes.
Alternatively, instead of global.asax, you could have the interesting types register themselves for inspection during their static initialization.

Force object to run/execute methods in sequence

I have a class which takes multiple collections, and then needs to perform calculations on these collections in a particular order. E.G.
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void CalcCols(){
//here, I will 'zip' col1/col2 to create List<double> for each
}
public void CalcStep2(){
//this is dependent on the results from CalcCols()
}
public void CalcNonDependent(){
//this can be called at any stage
}
}
The constructor forces the client to supply the relevant data, so there's an obvious ways to do this, by calling the methods in the constructor, this way, I know that everything will be populated. But, this doesn't seem like a clean solution, especially when I want to unit test parts of the code.
If I want to unit test CalcNonDependent(), I need to fully initialize the object, when I might not even require the result of the other two calculations.
So, my question, is there a pattern that can be used for this particular scenario; I have looked at Chain of Responsibility & Command Pattern, but wondered if anyone has any suggestions
Have you looked at Template? Not sure if it applies to your situation 100% but you would have a base class which defines 3 abstract methods and then calls them in the correct order.
class SomeBaseClass
{
public abstract void CalcCols();
public abstract void CalcStep2();
public abstract void CalcNonDependent();
public void DoAllCalculations()
{
CalcCols();
CalcStep2();
CalcNonDependent();
}
}
Then you inherit from this class and provide concrete implementations of your calculation methods.
I recommend concentrating on code coverage rather than method coverage. This way you can make the methods private and expose a single method that calls all 3 methods providing 100% coverage for the class. If you are concerned with dividing the tests for performance reasons then you can further subdivide the tests into groups which perform nightly long running tests vs daily/with every checkin tests.
The command pattern isn't going to solve much in the way of making the class more test-able. I would use such a pattern if you needed runtime workflow adaptation (E.G. M1(), M2(), then M2(), M1(), then M2(), M3() etc).
For example,
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void DoWork()
{
//Run methods in order.
}
private void CalcCols(){
//here, I will 'zip' col1/col2 to create List<double> for each
}
private void CalcStep2(){
//this is dependent on the results from CalcCols()
}
private void CalcNonDependent(){
//this can be called at any stage
}
}
You seem to be making a complicated problem out of nothing. Just change the class to:
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void CalcCols()
{
//here, I will 'zip' col1/col2 to create List<double> for each
CalcStep2();
}
public void CalcNonDependent()
{
//this can be called at any stage
}
private void CalcStep2()
{
}
}
If for CalcStep2 it is necessary that CalcCols has been executed, why not keep a flag to keep track of it, and include in CalcStep2 something like
if (!CalcColsHasBeenDone)
CalcCols();
Of course, don't forget to set CalcColsHasBeenDone to true at the end of CalcCols :)
You might want to extract an interface for your public operation, and expose only a single public method through it.
Using this in conjunction with e.g. P.Brian.Mackey's answer will make the other methods invisible from a clients perspective, while they can still be public in the implementing class, thus allowing for unit testing if needed.

Categories