Standardization of Performance Monitoring, Logging And Exception Handling Via A .NET Runtime Wrapper

Several years ago, I wanted to have my own performance monitoring solution, so I could monitor all enterprise applications. Few enterprises implement this core cross-cutting application task across the enterprise in the same way. By the phrases “core” and “cross-cutting” I mean a feature or functionality set that touches all application development; it’s not specific to a single application. I think some functionality that is repeated across the enterprise should be done the same standard way.
 
A common issue for teams building applications within a single department is often departments do their own thing, even calling the same business entity different names. They rarely consult with the established Enterprise Architectural framework, if one even exist. It’s no surprise that they often have different solutions for core processes like performance monitoring, logging, and exception handling. Seemingly, each application, each application layer, and even sometimes different method calls within the same application, often handle cross-cutting functionality differently. Such applications reflect a lack of architectural knowledge, a lack of architectural planning time, and/or, more likely, a deadline that mandates the development team to just "get it done ASAP".
 
I began to research having a common way to monitor application performance across the enterprise. Ideally, I wanted a simple solution that I could use for all enterprise needs. My first thought was an attribute based solution that I could apply to a method that would create a log entry when the method started and when it ended. This would allow me to identify bottlenecks in the execution of my application, at least for individual method calls, but not for sequential groups of method calls.
 
Creating an attribute that would create a performance log entry when the method started was easy, but the later was impossible (to my knowledge), unless you modified the IL in a Post-Build event, which isn’t ideal. And, after doing more research, I decided that reflection was not the best way to accomplish my needs, since the operation of reflection alone would skew my performance results. Also, I would prefer to not perform reflection in a production environment. So, my idea of creating an attribute based solution to accomplish my goals was not acceptable to me. 
 
In this article, I will propose an enterprise level solution to address standardizing exception handling, performance monitoring, and logging. It is implemented in a class called UnitOfWork. It can be used across an entire enterprise and/or application. While this wrapper is called UnitOfWork, do not confuse this with the database concept of a unit of work. This class has nothing to do with a database transaction, however, it would be easy to incorporate such functionality into this class.
 
I will be approaching this solution from a C#.NET point of view; as such, all the code I discuss will be in C# and .NET Core. I won’t discuss this code line by line, so if you don’t know C# or understand lambda expressions, you probably should stop reading now. I will cover a few of the more interesting parts of the code only, I will not cover every single line of code.
 
I acknowledge in advance that this is merely a way to accomplish the goals I have outlined above, and I make no presumption of saying it’s the best way or the only way. Every solution has its own set of issues, including this one. Other technologies do exist the address the same issues I am addressing. I have created this to provide maximum flexibility for any organization that may wish to use it. For instance, if an organization would rather log information (exceptions, logs, performance statistics) to a database, they only need to implement the ILogger interface I have defined to do so, and change their dependency injection configuration to use their own custom logger class. This class supports multiple loggers. I have included a few basic ones as examples. Everything (variables, properties, etc) used is optional and comes with default values. Further still, the entire UnitOfWork class and dependency classes are included in the source code, so feel free to modify it to satisfy your organization’s need. It is not copyrighted, and I only hope others find it as useful as I have.
 
For my solution, I decided a generic wrapper class that doesn’t suffer the performance issues of reflection, but does solve the issues, was my best bet. I could easily pass a lambda expression, or an array of lambda expressions, to my wrapper class, and it could create a log entry, then run the lambda expression(s), then log the duration of execution. This gives me control over the granularity of logging. Also, I have the source code that I can modify to suit any needs I may have in the future. Another perk to this solution is it’s free. ;)
 
It should be noted that the IN and OUT types are the same for all the lambda expressions being run in a single UnitOfWork class instance; however, that doesn’t mean that the IN or OUT couldn’t be a tuple of multiple types, or even an list of tuples of types. Another wonderful thing about lambda expressions is that all the objects that are visible when they are defined are also available inside of the expression itself. For example, if I create a database connection before I instantiate an UnitOfWork class, then the lambda expression(s) that I define for the UnitOfWork has access to that database connection object. The returned OUT type is the result of the last run lambda expression, but I have created two publicly accessible list properties that saves/clones the result of both inputs and outputs after each lambda expression’s execution, if more than one lambda expression is defined. These are serialized using the Json Serializer after each lambda expression’s execution and added to the list; however, only public member values are saved. I clone these IN and OUT values for pretty obvious reasons; think about ByRef and ByVal. I started to use the binary serializer to get all member values, but that requires the type to have the Serializable attribute to be applied to it.
 
As I built this wrapper I started to realize that it could encapsulate much more than just my performance monitoring needs. I realized my class could solve another common problem (a common problem, but rarely commonly solved across the enterprises) — exception handling. In most applications, the user is protected from the details of an exception thrown, since that information is pretty useless to the application user, but has very important relevance for the developer and his team that needs to debug the issue. This wrapper logs the much needed detailed exception information for developer debugging, while shielding that information from the application user. As an example, if a SQL exception is thrown, perhaps the only thing the application’s user really needs to see is "The requested operation failed; please try again." Basically, the user friendly message is meaningless to the developer, but shields the user from the devil in the details. The developer wants to see the details behind what happened. 
 
But, sometimes, I don’t want to handle exceptions in certain methods; sometimes I want the exception to bubble up to the caller. So, I added both the exception handling code, as well as the flexibility to specify if you want the class to rethrow the exception to the caller. If you elect to have this wrapper not handle the exception inside of its own TryCatch, then an exception will bubble up like normal.
 
Also, my choice of a class versus a struct or a static method, or even an extension method, was made for several reasons. The benefit of allowing parameters to be set via a class initializer was one reason. While I have provided several constructors for common object creation needs, I often find a class initializer beneficial for class creation to set properties not available in the constructor. Also, to me, class initializers are far easier to read. As far as the overhead of a class being created, I don’t see that as an issue. I considered making this a struct, to avoid garbage collection, but if an instance of UnitOfWork were to be passed as a parameter to other classes, then that could have a very serious impact on the memory stack, as a copy would be made and passed, rather than a reference passed. Garbage collection in .NET is generally faster than the C++ delete method. Class creation is negligible in .NET. It only becomes issue when you create classes inside of a loop with large (millions) quantities of elements. This class uses no unmanaged or disposable resources, but if the methods you pass to it do, then you should dispose of those responsibly yourself. If you modify this class to use unmanaged or disposable resources, you may need to utilize using statements and possibly implement IDisposable and the appropriate methods.
 
3 attributes of interest that are somewhat new to .NET. CallerMemberName, CallerLineNumber, and CallerFilePath attributes are applied to the Execute method. These are defined in the System.Runtime.CompilerServices namespace, and their names pretty much define what they do. I will let you look those up for yourself; they simply provide more information to the person that reviews any exception logging issues. 
 
I have a property called UnitOfWorkName. You should give this a meaningful name because it will appear in the logs. Remember, this name applies to all of the lambda expressions you pass into this class.
 
The last constructor is the only one that is of importance, as it does the work. The last parameter to this constructor is meaningless, so just ignore it. It is only there to provide an unique signature. This is protected scope for obvious reasons, so anyone who inherits from this class can access it. The scope/visibility of everything in this class has a reason. For instance, the Function property get is private, and, again, for obvious reasons, to prevent bypassing the whole purpose of this wrapper class.
 
Ok, next is the exception details. The ExceptionDispatchInfo class defines a few static methods that allow for the capture of an exception’s state. It is part of the System.Runtime.ExceptionServices namespace. I remember the first time I had to debug an error that was throwing an exception but the call stack was gone (what a joy to discover). If you want to have your exceptions bubble up to your calling location (this is the default behavior), then you will get the original exception including its saved call stack. 
 
I have defined several explicit cast operators should you wish to cast this class to a different, more useful type. The meaning of these cast operators is clear. If you read and understand this class, you should understand those easily. I have put comments throughout the code where I thought it would be useful.
 
I have put an extension method that does part of what this wrapper in the code as well, should you be interested in looking at it. Also, I typed up a quick ExecuteTransaction extension method for you to look at if you want the functionality of a database unit of work (included in the code). I prefer to handle database transactions in stored procedures myself, but feel free to use this. Simply select all the code below and paste it into a single C# cs file.
 
I think any experienced C# developer should be able to read the code and understand it. For that reason, I have not discussed the code itself. It is below for your perusal. UnitOfWork is a flexible, free, and modifiable generic class wrapper that solves many core enterprise issues. In this case, performance monitoring, logging, and exception handling were addressed. I can think of other things that could be added to this to be of benefit to specific enterprises. Authentication and authorization, to name two, but I leave this to implement for yourself, since that is pretty different for each enterprise.
  1. /* 
  2.  * Written by Lee McGraw (in my personal free time), Enterprise Architect/Developer US DoD 
  3.  * Feel free to modify this code to suit your own needs. 
  4.  * An article accompanies this code, titled "Standardization of Performance Monitoring, Logging, and Exception Handling via a .NET Runtime Wrapper" 
  5.  * Google it if you are interested. 
  6.  */  
  7.   
  8.   
  9. using System;  
  10. using System.Collections.Generic;  
  11. using System.Diagnostics;  
  12. using System.IO;  
  13. using System.Runtime.CompilerServices;  
  14. using System.Runtime.ExceptionServices;  
  15. using System.Runtime.Serialization.Json;  
  16. using System.Text;  
  17. using static System.Console;  
  18. using static System.String;  
  19.   
  20.   
  21. namespace CoreConsoleAppLee  
  22. {  
  23.     public class MyReferenceClass  
  24.     {  
  25.         public string Name { getset; }  
  26.     }  
  27.     class Program  
  28.     {  
  29.         public string InstanceMethod(int num)  
  30.         {  
  31.             return "Inside of Instance Method. " + num.ToString();  
  32.         }  
  33.         public static string StaticMethod(int num)  
  34.         {  
  35.             return "Inside of Static Method. " + num.ToString();  
  36.         }  
  37.   
  38.   
  39.         static void Main(string[] args)  
  40.         {  
  41.             var myProgram = new Program();  
  42.             var uow = new UnitOfWork<intstring>(r =>  
  43.             {  
  44.                 return "Inside of Statement Lambda. " + r.ToString();  
  45.             })  
  46.             {  
  47.                 UnitOfWorkName = "Demostration of Unit of Work usage."  
  48.             };  
  49.             uow.AddFunction(r => "Inside of Expression Lambda." + r.ToString());    
  50.             uow.AddFunction(r => StaticMethod(r));  
  51.             uow.AddFunction(r => myProgram.InstanceMethod(r));  
  52.             var input = 10;  
  53.             uow.Execute(input);  
  54.   
  55.   
  56.             Console.WriteLine("\nInputs to calls...");  
  57.             uow.Inputs.ForEach(r =>  
  58.             {  
  59.                 Console.WriteLine(r.ToString());  
  60.             });  
  61.             Console.WriteLine("\nOutputs to calls...");  
  62.             uow.Outputs.ForEach(r =>  
  63.             {  
  64.                 Console.WriteLine(r.ToString());  
  65.             });  
  66.               
  67.             var uow2 = new UnitOfWork<MyReferenceClass, MyReferenceClass>(r =>  
  68.               {  
  69.                   r.Name = r.Name.ToUpper();  
  70.                   return r;  
  71.               });  
  72.             uow2.AddFunction(f =>  
  73.             {  
  74.                 f.Name = f.Name.ToLower();  
  75.                 return f;  
  76.             });  
  77.             var res = uow2.Execute(new MyReferenceClass { Name = "Daffy Duck" });  
  78.   
  79.   
  80.             Console.WriteLine("\nInputs to calls...");  
  81.             uow2.Inputs.ForEach(r =>  
  82.             {  
  83.                 Console.WriteLine(r.Name.ToString());  
  84.             });  
  85.             Console.WriteLine("\nOutputs to calls...");  
  86.             uow2.Outputs.ForEach(r =>  
  87.             {  
  88.                 Console.WriteLine(r.Name.ToString());  
  89.             });  
  90.   
  91.   
  92.             var i = 0;  
  93.         }  
  94.     }  
  95.   
  96.   
  97.     /// <summary>  
  98.     /// This class encapsulates the performance timing, exception handling, and logging of a method and/or a group of methods.    
  99.     /// Do NOT be confused by the name of the class.  It is NOT a database UnitOfWork, although that support could easily be added.    
  100.     /// The purpose of this class is to handle a measurable unit of work, as well as a logical endpoint for exception handling.  
  101.     /// </summary>  
  102.     /// <typeparam name="IN">Type being passed as input the method; this is not necessarily a single object, because it could be a collection.</typeparam>  
  103.     /// <typeparam name="OUT">Type being returned by the method; this is not necessarily a single object, because it could be a collection or a tuple of many types.</typeparam>  
  104.     public class UnitOfWork<IN, OUT>  
  105.     {  
  106.         private const string defaultUnitOfWorkName = "UnitOfWork";  
  107.  
  108.  
  109.         #region Members  
  110.   
  111.   
  112.         protected Dictionary<UnitType, Stopwatch> stopWatch { getset; }  
  113.         protected Exception exception { getset; }  
  114.         protected List<ILogger> Loggers { getset; } = new List<ILogger>();  
  115.  
  116.  
  117.         #endregion Members          
  118.  
  119.  
  120.         #region Properties  
  121.         private string CallerMethodName { getset; }  
  122.         private int CallerLineNumber { getset; }  
  123.         private string CallerFilePath { getset; }  
  124.         public string UnitOfWorkName { getset; } = defaultUnitOfWorkName;  
  125.         private string MethodName { getset; }  
  126.         public bool UseStopwatch { getset; } = true;  
  127.         public bool UseTryCatch { getset; } = true;  
  128.         public bool RethrowExceptions { getset; } = true;  
  129.   
  130.   
  131.         //private get below to prevent the developer using this to bypass the operational logic of the execute method, thereby negating the intension of this completely.  
  132.         public List<Func<IN, OUT>> Functions { private getset; } = new List<Func<IN, OUT>>();  
  133.         public Func<IN, OUT> Function { private getset; }  
  134.         public List<IN> Inputs { getprivate set; }  
  135.         public List<OUT> Outputs { getprivate set; }  
  136.  
  137.  
  138.         #endregion Properties  
  139.  
  140.  
  141.         #region Constructors  
  142.   
  143.   
  144.         public UnitOfWork(  
  145.             Func<IN, OUT> function,  
  146.             string unitOfWorkName = defaultUnitOfWorkName,  
  147.             bool useStopwatch = true,  
  148.             bool useTryCatch = true,  
  149.             bool rethrowExceptions = true,  
  150.             ILogger logger = null)  
  151.             : this(new Func<IN, OUT>[] { function }, unitOfWorkName, useStopwatch, useTryCatch, rethrowExceptions, logger, true) { }  
  152.   
  153.   
  154.         public UnitOfWork(  
  155.             Func<IN, OUT>[] functions,  
  156.             string unitOfWorkName = defaultUnitOfWorkName,  
  157.             bool useStopwatch = true,  
  158.             bool useTryCatch = true,  
  159.             bool rethrowExceptions = true,  
  160.             ILogger logger = null,  
  161.             bool uniqueSignaturePurposesOnly = true)  
  162.         {  
  163.             //the uniqueSignaturePurposesOnly parameter is only there to make this constructor have a unique signature, and can be ignored as it is not used.  
  164.             if (functions == null || functions.Length == 0)  
  165.             {  
  166.                 throw new ArgumentException("The value of functions can not be null or empty!");  
  167.             }  
  168.             InitParameters();  
  169.             InitStopwatch();  
  170.             InitLoggers();  
  171.   
  172.   
  173.             void InitParameters()  
  174.             {  
  175.                 Function = functions[0];  
  176.                 AddFunction(functions);  
  177.                 UnitOfWorkName = unitOfWorkName ?? defaultUnitOfWorkName;  
  178.                 //if the parameter was null, then perhaps it was set in the constructor already, else use the Method name  
  179.                 MethodName = Function.Method.Name;  
  180.                 UseStopwatch = useStopwatch;  
  181.                 UseTryCatch = useTryCatch;  
  182.                 RethrowExceptions = rethrowExceptions;  
  183.             }  
  184.             void InitLoggers()  
  185.             {  
  186. #if DEBUG  
  187.                 Loggers = new List<ILogger>();  
  188.                 Loggers.Add(logger ?? new ConsoleLogger());  
  189. #endif  
  190.                 if (logger != null)  
  191.                 {  
  192.                     Loggers = Loggers ?? new List<ILogger>();  
  193.                     Loggers.Add(logger);  
  194.                 }  
  195.   
  196.   
  197.             }  
  198.             void InitStopwatch()  
  199.             {  
  200.                 if (useStopwatch)  
  201.                 {  
  202.                     stopWatch = new Dictionary<UnitType, Stopwatch>();  
  203.                     stopWatch.Add(UnitType.UnitOfWork, new Stopwatch());  
  204.                     stopWatch.Add(UnitType.Method, new Stopwatch());                    
  205.                 }  
  206.             }  
  207.         }  
  208.  
  209.  
  210.         #endregion Constructor  
  211.  
  212.  
  213.         #region Methods          
  214.   
  215.   
  216.         public void AddFunction(params Func<IN, OUT>[] functions) => Functions.AddRange(functions);  
  217.         public void AddLogger(params ILogger[] loggers) => Loggers.AddRange(loggers);  
  218.   
  219.   
  220.         public OUT Execute(  
  221.             IN input,  
  222.             [CallerMemberName] string callerMethodName = "",  
  223.             [CallerLineNumber] int callerLineNumber = 0,  
  224.             [CallerFilePath] string callerFilePath = ""  
  225.             )  
  226.         {  
  227.             OUT result = default(OUT);  
  228.             CallerMethodName = callerMethodName;  
  229.             CallerLineNumber = callerLineNumber;  
  230.             CallerFilePath = callerFilePath;  
  231.             if (Functions.Count > 1)  
  232.             {  
  233.                 Inputs = Inputs ?? new List<IN>();  
  234.                 Outputs = Outputs ?? new List<OUT>();  
  235.             }  
  236.             if (UseTryCatch)  
  237.             {  
  238.                 try  
  239.                 {  
  240.                     Run();  
  241.                 }  
  242.                 catch (Exception e)  
  243.                 {  
  244.                     ExceptionDispatchInfo.Capture(e);  
  245.                     exception = e;  
  246.                     Loggers.ForEach(log =>  
  247.                         log.WriteError($@"  
  248. An ERROR has occurred!  
  249. {UnitOfWorkName}-{MethodName}",  
  250. Concat($@"  
  251. Caller Info:  
  252. Method={CallerMethodName}  
  253. Line={CallerLineNumber}   
  254. Path={CallerFilePath}  
  255. ", ((ExceptionManager)exception).ToString())  
  256.                         )  
  257.                     );  
  258.                     if (RethrowExceptions) ExceptionDispatchInfo.Throw(e);  
  259.                 }  
  260.                 finally  
  261.                 {  
  262.                     End(UnitType.UnitOfWork);  
  263.                 }  
  264.             }  
  265.             else  
  266.             {  
  267.                 Run();  
  268.             }  
  269.             return result;  
  270.             void Run()  
  271.             {  
  272.                 Start(UnitType.UnitOfWork);  
  273.                 Functions?.ForEach(f =>  
  274.                 {  
  275.                     Function = f;  
  276.                     MethodName = f.Method.Name;  
  277.                     Start();  
  278.                     Inputs?.Add(Clone(input));  
  279.                     result = (f != null ? f.Invoke(input) : result);  
  280.                     Outputs?.Add(Clone(result));  
  281.                     End();  
  282.                 });  
  283.                 End(UnitType.UnitOfWork);  
  284.             }  
  285.         }  
  286.         protected virtual void Start(UnitType unitType = UnitType.Method)  
  287.         {  
  288.             if (!UseStopwatch) return;  
  289.             Loggers.ForEach(log =>  
  290.                 log.WriteInfo(  
  291.                     generateSource(unitType),  
  292.                     generateMessage(unitType, $"Starting at {System.DateTime.Now.ToString()}!")  
  293.                 )  
  294.             );  
  295.             if (stopWatch[unitType].IsRunning) stopWatch[unitType].Reset();  
  296.             stopWatch[unitType].Start();              
  297.         }  
  298.         protected virtual void End(UnitType unitType = UnitType.Method)  
  299.         {  
  300.             if (!UseStopwatch) return;  
  301.             stopWatch[unitType].Stop();  
  302.             Loggers.ForEach(log =>  
  303.                 log.WriteInfo(  
  304.                     generateSource(unitType),  
  305.                     generateMessage(unitType, Concat("Ran in ", stopWatch[unitType].ElapsedMilliseconds.ToString(), $"ms. Ending at {System.DateTime.Now.ToString()}!"))  
  306.                 )  
  307.             );  
  308.         }  
  309.   
  310.   
  311.         private string generateSource(UnitType unitType)  
  312.         {  
  313.             return Concat(unitType.ToString(), "|", unitType == UnitType.UnitOfWork ? UnitOfWorkName : MethodName);  
  314.         }  
  315.         private string generateMessage(UnitType unitType, string postFix = "")  
  316.         {  
  317.             return Concat("(", unitType == UnitType.UnitOfWork ? UnitOfWorkName : MethodName, ")", postFix);  
  318.         }  
  319.         /// <summary>  
  320.         /// Perform a deep Copy of the object, using Json as a serialization method.   
  321.         /// NOTE: Private members are not cloned using this method.  
  322.         /// Serializable attribute is not required, but if it's an object, the class needs a parameterless constructor.  
  323.         /// </summary>  
  324.         /// <typeparam name="T">The type of object being copied.</typeparam>  
  325.         /// <param name="source">The object instance to copy.</param>  
  326.         /// <returns>The copied object.</returns>  
  327.         private T Clone<T>(T source)  
  328.         {  
  329.             var result = default(T);  
  330.             var jsonString = "";  
  331.             using (var stream = new MemoryStream())  
  332.             {  
  333.                 var serializer = new DataContractJsonSerializer(typeof(T));  
  334.                 serializer.WriteObject(stream, source);  
  335.                 byte[] json = stream.ToArray();  
  336.                 jsonString = Encoding.UTF8.GetString(json, 0, json.Length);  
  337.             }  
  338.             using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))  
  339.             {  
  340.                 var serializer = new DataContractJsonSerializer(typeof(T));  
  341.                 result = (T)serializer.ReadObject(stream);  
  342.             }  
  343.             return result;  
  344.         }  
  345.  
  346.  
  347.         #endregion Methods  
  348.  
  349.  
  350.         #region Cast Operators  
  351.   
  352.   
  353.         public static explicit operator Func<IN, OUT>(UnitOfWork<IN, OUT> unitOfWork)  
  354.             => unitOfWork.Function;  
  355.         public static explicit operator List<Func<IN, OUT>>(UnitOfWork<IN, OUT> unitOfWork)  
  356.             => unitOfWork.Functions;  
  357.         public static explicit operator UnitOfWork<IN, OUT>(List<Func<IN, OUT>> functions)  
  358.             => new UnitOfWork<IN, OUT>(functions.ToArray());  
  359.         public static explicit operator UnitOfWork<IN, OUT>(Func<IN, OUT> function)  
  360.             => new UnitOfWork<IN, OUT>(function);  
  361.  
  362.  
  363.         #endregion Cast Operators  
  364.     }  
  365.   
  366.   
  367.     public enum UnitType  
  368.     {  
  369.         Method,  
  370.         UnitOfWork  
  371.     }  
  372.     public static class Extender  
  373.     {  
  374.         public static void ExecuteTransaction(this System.Data.IDbConnection connection, params System.Data.IDbCommand[] commands)  
  375.         {  
  376.             using (connection)  
  377.             {  
  378.                 if (connection.State != System.Data.ConnectionState.Open) connection.Open();  
  379.                 using (var transaction = connection.BeginTransaction())  
  380.                 {  
  381.                     try  
  382.                     {  
  383.                         foreach (var command in commands)  
  384.                         {  
  385.                             command.ExecuteNonQuery();  
  386.                         }  
  387.                         transaction.Commit();  
  388.                     }  
  389.                     catch  
  390.                     {  
  391.                         transaction.Rollback();  
  392.                     }  
  393.                 }  
  394.             }  
  395.         }  
  396.         public static OUT Execute<IN, OUT>(this IN toThat,  
  397.             bool useTryCatch = true,  
  398.             params Func<IN, OUT>[] doThis)  
  399.         {  
  400.             var result = default(OUT);  
  401.             if (toThat == null && doThis == nullreturn result;  
  402.             if (useTryCatch)  
  403.             {  
  404.                 try  
  405.                 {  
  406.                     foreach (var function in doThis)  
  407.                     {  
  408.                         result = function(toThat);  
  409.                     }  
  410.                 }  
  411.                 catch  
  412.                 {  
  413.                     throw;  
  414.                 }  
  415.             }  
  416.             else  
  417.             {  
  418.                 foreach (var function in doThis)  
  419.                 {  
  420.                     result = function(toThat);  
  421.                 }  
  422.             }  
  423.             return result;  
  424.         }  
  425.   
  426.   
  427.         public static void With<T>(this T toThat, Action<T> doThis) where T : class  
  428.             => doThis?.Invoke(toThat);  
  429.         public static OUT With<IN, OUT>(this IN toThat, Func<IN, OUT> doThis)  
  430.             => doThis.Invoke(toThat);  
  431.     }  
  432.  
  433.  
  434.     #region EventViewerLogger  
  435.   
  436.   
  437.     /// <summary>  
  438.     /// You need the .NET Core compatibility nuget package, if you use this in .NET Core, to write to the EventViewer.  
  439.     /// Search NuGet for package named Microsoft.Windows.Compatibility.  
  440.     /// This could have been accomplished via a delegate too, but that would add overhead,  
  441.     /// and if this used enterprise wide, that's the LAST thing we want.  
  442.     /// </summary>  
  443.     public class EventViewerLogger : ILogger  
  444.     {  
  445.         public EventViewerLogger() { }  
  446.         public virtual void WriteInfo(string source, string message)  
  447.         {  
  448.             EventLog.WriteEntry(source, message);  
  449.         }  
  450.         public virtual void WriteError(string source, string message)  
  451.         {  
  452.             EventLog.WriteEntry(source, message);  
  453.         }  
  454.     }  
  455.  
  456.  
  457.     #endregion EventViewerLogger  
  458.  
  459.  
  460.     #region ConsoleLogger  
  461.     public class ConsoleLogger : ILogger  
  462.     {  
  463.         public ConsoleLogger() { }  
  464.         public virtual void WriteInfo(string source, string message)  
  465.         {  
  466.             WriteLine(source + "-" + message);  
  467.         }  
  468.         public virtual void WriteError(string source, string message)  
  469.         {  
  470.             WriteLine(source + "-" + message);  
  471.         }  
  472.     }  
  473.  
  474.  
  475.     #endregion ConsoleLogger  
  476.  
  477.  
  478.     #region ILogger  
  479.   
  480.   
  481.     /// <summary>  
  482.     /// To implement your own logger, implement this interface.    
  483.     /// </summary>  
  484.     public interface ILogger  
  485.     {  
  486.         void WriteInfo(string source, string message);  
  487.         void WriteError(string source, string message);  
  488.     }  
  489.  
  490.  
  491.     #endregion ILogger  
  492.   
  493.   
  494.     public struct ExceptionManager  
  495.     {  
  496.         private Exception exception;  
  497.         private ExceptionManager(Exception exception)  
  498.         {  
  499.             this.exception = exception;  
  500.         }  
  501.   
  502.   
  503.         public override string ToString()  
  504.         {  
  505.             var sb = new StringBuilder();  
  506.             sb.Append("**********\n");  
  507.             do  
  508.             {  
  509.                 sb.Append($"Message:{exception.Message}");  
  510.                 sb.Append($"\nSource:{exception.Source}");  
  511.                 sb.Append($"\nTargetSite:{exception.TargetSite}");  
  512.                 sb.Append($"\nStackTrace:{exception.StackTrace}");  
  513.                 sb.Append($"\nHelpLink:{exception.HelpLink}");  
  514.                 exception = exception.InnerException;  
  515.                 if (exception != null) sb.Append("\n----------");  
  516.             } while (exception != null);  
  517.             sb.Append("\n**********\n");  
  518.             return sb.ToString();  
  519.         }  
  520.         public static explicit operator Exception(ExceptionManager exceptionManager)  
  521.         {  
  522.             return exceptionManager.exception;  
  523.         }  
  524.         public static explicit operator ExceptionManager(Exception exception)  
  525.         {  
  526.             return new ExceptionManager(exception);  
  527.         }  
  528.         public static explicit operator string(ExceptionManager exceptionManager)  
  529.         {  
  530.             return exceptionManager.ToString();  
  531.         }  
  532.     }  
  533. }