We have been using log4net for logging our asp.net web forms application. Our logging is typically in our business layer and the typical implementation is like this
SomeMethodCall(MethodParams)
{
Log.Start("Starting Some Method");
try
{
//do something
}
catch(Exception ex)
{
Log.Exception("exception in SomeMethodCall" + ex.message);
}
Log.End("End SomeMethod");
}
In my opinon, it is a bit clumsy. Is there a cleaner way of doing it without using AOP ?I am not sure if I would need to have the overhead of adding a framework, just for logging, thought I understand that it would give me a lot of other options (which I do not need)
I am thinking of using some AOP frameworks to do it in a more cleaner way, just by marking the methods with attributes to log and handle exceptions.
There are 2 things I am concerned with AOP (after my initial reading).
Some frameworks inject code into your IL(as per my understanding) and am concerned if it would misguide me. I might be looking at line x, given by my AOP framework, where as it actually might be line y in my application. Is my fear unfounded?
Performance: How much of a performance overhead would be added if using an AOP framework.
Edit: I was also looking into PolicyInjectionApplicationBlock. Unfortunately, I do not have the luxury of changing implementaions inside my business logic
Are you saying that most / all of your methods take this structure? If so, my advice would be to tone down your logging. (I stress that this is advice, and possibly controversial advice as well).
There shouldn't really be a need to use a blanket log of the entry and exit of every single method in this way, instead place your log entries more strategically. I like to ensure that all log messages have a "purpose" - if I can't think of a scenario where that log message would help or aid me in some way while debugging then it has no business being in my code!
You can read this, also read 7 approaches for AOP in .Net, I use AOP in Java and i didn't see performance problem. Anyway check here to be careful....
Additional
Spring.Net AOP
Related
For context, I recently discovered functional programming, and am trying to incorporate it into an existing Web API solution.
So far, I have been reading Functional Programming in C# and I've been trying to create a new controller that would be able to do basic CRUD using the language-ext library.
I'm running into a bit of an obstacle as I am not sure if I am keeping to FP principles when accessing the database.
Here is the code I have so far--please note that I am using Entity Framework Code First, and that for reasons beyond my control I am forced to use surrogate keys with type Guid, which is why there are so many operations involved in the method:
// These functions are injected into the controller constructor
// and are curried where appropriate.
Func<int, Either<Error, Widget>> FetchWidgetById; // Impure
Func<Widget, Widget, Either<Error, Widget>> CloneWidget;
Func<Widget, Either<Error, Widget>> SaveToDb; // Impure
Func<Either<Error, Widget>, IHttpActionResult> CreateHttpResponse
public IHttpActionResult Update(Widget updatedWidget)
=> CreateHttpResponse(
GetWidgetById(updatedWidget.HumanReadableId)
.Bind(CloneWidget(updatedWidget))
.Bind(SaveToDb));
The problem is that I am not sure how to signal that GetWidgets and UpdateDatabase are impure. I have come across the concept of the I/O monad but I don't think such a thing exists in the language-ext API, and I don't have enough FP knowledge to work out if there is an equivalent solution or name for it.
EDIT: I've found some documentation on monads on a similar but older project by the same author of language-ext. It's interesting to note that this project actually includes the I/O monad for which he acknowledges that
The IO monad may be seen as unnecessary in C# where everything has
side-effects...
I'm not an expert in any of this, but I'll give it a shot in any case. My understanding is that if you want to have pure functions for domain logic and handle database access outside of this, you'll have to write quite a lot of boilerplate code. You'll have to have domain logic implemented as free monads, compose functionality using them, and finally have an interpreter to run the code, actually touching the database.
Since you are using language-ext, please refer to its documentation about free monads:
https://github.com/louthy/language-ext/wiki/Thinking-Functionally:-Application-Architecture#free-monad
See also these examples:
https://gist.github.com/louthy/524fbe8965d3a2aae1b576cdd8e971e4
https://gist.github.com/dadhi/59cfc698f6dc6e31b722cd804aae185a
https://gist.github.com/tonymorris/7817335
But, if you are just looking to signal to readers where code has side effects, it is not really possible in C#, because you could do IO anywhere, as was mentioned in your edit. Of course, being systematic and following conventions is possible, but I don't think you can go much beyond that. This applies to free monads as well, since nothing prevents from writing side effects there either in C#.
I would like to log the start and ending of a method, but the code is messy and is hard to read:
void mymethod()
{
LogUtility.EnteringMethod();
//dowork
LogUtility.EXitingMethod();
}
I would like to convert the above to just be
void mymethod()
{
//dowork
}
But at compile/build time, I would like a macro/script to add those LogUtility lines in every one of my methods.
I know there is aspect-oriented programming, but I am looking for something significantly less complex and clunky.
Can you recommend a way to automatically generate code right before a compile/build?
if you want an automatic way, an AOP framework like PostSharp is pretty much the cleanest option.. you could try to automate it yourself with reflection and attributes and IL manipulation, but that is not trivial.
and if you want to really keep it simple and not use 100% automation, you can make use of a wrapper method, with an Action parameter. this is really not a scalable solution and is pretty ugly in terms of production-code-readability.
public void RunMethodWithEntryAndExitLogging(Action methodToExecute)
{
LogUtility.EnteringMethod(); // use methodToExecute.Method.Name if you need it
methodToExecute(); // the method that is the actual work
LogUtility.EXitingMethod();
}
as i said, this is just a quick and simple way. but gets the job done for a specific problem you might be trying to solve.
I know this answer might be late, but one of the solutions for generating code at build time would be to use the T4 Editor.
This happens to be the same engine that Entity Framework and MVC use to generate the c# after interpreting your models and such.
If you would like the official documentation on how it works from microsoft you can also read here Code Generation and T4 Text Templates, Design-Time Code Generation by using T4 Text Templates.
With this you can in theory create, for instance according to attributes you add to your methods, even on build and compile, such a .tt file which can contain logging, authorization or other handy extensions before your methods would run in your classes thus eliminating lots of boiler plate code, but maintenance and debugging might be a complex task.
If you do not want to have the hassle of handling all this yourself then you can use Post Sharp as Raja Nadar pointed out in his answer.
Hope this gives you a place to start.
I need to provide a copy of the source code to a third party, but given it's a nifty extensible framework that could be easily repurposed, I'd rather provide a less OO version (a 'procedural' version for want of a better term) that would allow minor tweaks to values etc but not reimplementation using the full flexibility of how it is currently structured.
The code makes use of the usual stuff: classes, constructors, etc. Is there a tool or method for 'simplifying' this into what is still the 'source' but using only plain variables etc.
For example, if I had a class instance 'myclass' which initialised this.blah in the constructor, the same could be done with a variable called myclass_blah which would then be manipulated in a more 'flat' way. I realise some things like polymorphism would probably not be possible in such a situation. Perhaps an obfuscator, set to a 'super mild' setting would achieve it?
Thanks
My experience with nifty extensible frameworks has been that most shops have their own nifty extensible frameworks (usually more than one) and are not likely to steal them from vendor-provided source code. If you are under obligation to provide source code (due to some business relationship), then, at least in my mind, there's an ethical obligation to provide the actual source code, in a maintainable form. How you protect the source code is a legal matter and I can't offer legal advice, but really you should be including some license with your release and dealing with clients who are not going to outright steal your IP (assuming it's actually yours under the terms you're developing it.)
As had already been said, if this is a requirement based on restrictions of contracts then don't do it. In short, providing a version of the source that differs from what they're actually running becomes a liability and I doubt that it is one that your company should be willing to take. Proving that the code provided matches the code they are running is simple. This is also true if you're trying to avoid license restrictions of libraries your application uses (e.g. GPL).
If that isn't the case then why not provide a limited version of your extensibility framework that only works with internal types and statically compile any required extensions in your application? This will allow the application to continue to function as what they currently run while remaining maintainable without giving up your sacred framework. I've never done it myself but this sounds like something ILMerge could help with.
If you don't want to give out framework - just don't. Provide only source you think is required. Otherwise most likely you'll need to either support both versions in the future OR never work/interact with these people (and people they know) again.
Don't forget that non-obfuscated .Net assemblies have IL in easily de-compilable form. It is often easier to use ILSpy/Reflector to read someone else code than looking at sources.
If the reason to provide code is some sort of inspection (even simply looking at the code) you'd better have semi-decent code. I would seriously consider throwing away tool if its code looks written in FORTRAN-style using C# ( http://www.nikhef.nl/~templon/fortran/fortran_style ).
Side note: I believe "nifty extensible frameworks" are one of the roots of "not invented here" syndrome - I'd be more worried about comments on the framework (like "this code is ##### because it does not use YYY pattern and spacing is wrong") than reuse.
I want to create a log file in my program.
My log pattern should contain: Log type, Datetime, Thread Name, Method Name, Log detail.. etc...
Which log pattern do you suggest?
Does any accepted log pattern for this? For example "trace log pattern", "event log pattern" etc...
Use a logging library such as NLog or Log4Net Then you can tweak the layout & renderers all you want without changing code or recompiling, and have lots of other useful functionality as well (such as rolling logs, db/network/email appenders, filters, log levels etc).
A good comparison of some logging frameworks
I REALLY recommend using Log4net; it supports almost everything you'd possibly want to do, is almost freakishly robust, and very straightforward to put in place.
You can find it here.
Why don't you try a logging framework like Log4Net ? There are plenty of tutorials around...
The Microsoft Application Blocks have some very good boiler plate code you can start with. The Logging Application Block can be used by itself, with other MAB elements or simply as a starting point for rolling your own.
Omar Al Zabir is looking for "a simpler way to do AOP style coding".
He created a framework called AspectF, which is "a fluent and simple way to add Aspects to your code".
It is not true AOP, because it doesn't do any compile time or runtime weaving, but does it accomplish the same goals as AOP?
Here's an example of AspectF usage:
public void InsertCustomerTheEasyWay(string firstName, string lastName, int age,
Dictionary<string, string> attributes)
{
AspectF.Define
.Log(Logger.Writer, "Inserting customer the easy way")
.HowLong(Logger.Writer, "Starting customer insert", "Inserted customer in {1} seconds")
.Retry()
.Do(() =>
{
CustomerData data = new CustomerData();
data.Insert(firstName, lastName, age, attributes);
});
}
Here are some posts by the author that further clarify the aim of AspectF:
AspectF fluent way to put Aspects into your code for separation of concern (Blog)
AspectF (google code)
AspectF Fluent Way to Add Aspects for Cleaner Maintainable Code (CodeProject)
According to the author, I gather that AspectF is not designed so much as an AOP replacement, but a way to achieve "separation of concern and keep code nice and clean".
Some thoughts/questions:
Any thoughts on using this style of coding as project grows?
Is it a scalable architecture?
performance concerns?
How does maintainability compare against a true AOP solution?
I don't mean to bash the project, but
IMHO this is abusing AOP. Aspects are not suitable for everything, and used like this it only hampers readability.
Moreover, I think this misses one of the main points of AOP, which is being able to add/remove/redefine aspects without touching the underlying code.
Aspects should be defined outside of the affected code in order to make them truly cross-cutting concerns. In AspectF's case, the aspects are embedded in the affected code, which violates SoC/SRP.
Performance-wise there is no penalty (or it's negligible) because there is no runtime IL manipulation, just as explained in the codeproject article. However, I've never had any perf problems with Castle DynamicProxy.
On a recent project, it was recommended to me that I give AspectF a try.
I took to heart the idea of laying all the concerns up front, and having the code that does the real work blissfully unaware of all the checks and balances that happened outside of it.
I actually took it a little further, and added a security "concern" that required credentials that were being received as part of a WCF request. It went off to the database and did what it had to. I did obvious validations, and the security check before running the actual code that would return the required data.
I found this approach quite a refreshing change, and I certainly liked that I had the source of AspectF to walk through as I was debugging and testing the service calls.
In the office, some argued that these concerns should be implemented as a decoration on a class / method. But it doesn't really matter where you decorate it, at some point somewhere, you need to say you wish to perform certain actions / checks. I like the fact that it's all laid out in-place, not as another code file, not as some kind of configuration file, and for once, not adding yet another decoration to a class / method.
I'm not saying it's true AOP - and I certainly think there are solutions and situations where it really isn't the best way of implementing your objectives, but given that it's just a couple of K of source files, that makes for a very light-weight implementation.
AspectF is basically a very clever way of chaining delegates together.
I don't think every developer is going to look at the code and say how wonderful it is to look at, indeed in our office it confused some of us! But once you understand what's going on, it's an inexpensive way of achieving much of what can be done by other approaches too.