I have tons of functions in my WinForms project and i'm using NLog for logging. I want to have an ability to wrap each function with nlogger.Info("start") and nlogger.Info("end") so i will know in which place actual exception occurred or where the code currently runs.
Is there a smart way to do it or i will need to place lines from above in all of my functions ?
I believe that PostSharp can do this for you, and can apply at the assembly level (via assembly-level attributes). However, I would be cautious of the potential performance impact. Writing the "aspect" should be pretty minimal.
Ifyou don't want to do it manually - you could consider Aspect Oriented Programming.
To summarise what it is, it matches functions which run and offers 'advice' before, after or around. So you can easily make one which runs at all functions and adds to the log. Never used it for C# but I used it for Java.
You can find a class for .NET. Read this for more info:
http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/
Related
C++ and C# are quite simmilar programming languages, in my opinion. If a C++ code needs to be ported to platform where C# is the only supported platform, how much work will need to be done?
Should I get ready, that most of the C++ code will need to be rewritten to C#? Or, because of language simmilarities, should refactoring be quite easy and straightforward?
I am aware, that it will depend on the application itself, but I am asking in general.
I have done a major port of a C++ application to C# recently. Overall I thought it was a pleasant experience. These are the steps that I took, they might or might not apply to your application.
Get the "scaffolding" in place in C#, design your architecture. This is the time to get in major architecture changes from the existing application if you choose to do so.
Get your tests in place. I can't over-emphasize this one. Since you are porting an existing application you should have a set of tests already in place that verify the correct behavior of your application. You can and should reuse these tests for your C# application. This is the one thing that gives you an edge when porting - you know (and have written) already many of the tests you want. Start porting your test project.
Put in method stubs for your C# methods that reflect the existing C++ methods. Given the framework support in C# some methods might not be needed at all anymore, or are very simplified - this is the time to decide.
Copy and paste. Yes I used copy and paste for most of the C++ code - all the flow statements basically can be reused if you are careful. Once pasted go through line by line, many things like use of pointers etc. must be rewritten to use a equivalent C# type.
Once you have re-written a method in such a way, do the obvious re-factoring given the framework support / helper classes you might have been lacking in C++ but are readily available in C#. Also naming conventions for variables etc. can be changed here, should be straightforward given the built in support for this in VS 2010.
Run your tests! Test early and often that the overall framework you have in place so far produces the exact same output as your C++ application which you can use as a reference. This is also the time to add missing tests.
Refactor, Refactor, Refactor. Every application ages, and so did your C++ application most likely. Look closely at the underlying design and simplify and remove as much as possible. Verify at each step by running your tests.
First thing first, this is porting and not refactoring. Also I think it's an extremely bad idea.
It is true that you could (with a lot of work) port C++ to unsafe C#, but saying that the syntax is very similar is a bit of a stretch. In fact, following the same line of reasoning you could port C++ to any other C derived language, and it would be equally painful.
Again, if you do it expect a shedload of rework. It's more than likely gonna take you more than re-coding it from scratch using the existing code as mere model, which is in my opinion a better and less messy option.
Just compile the C++ code with the /clr compiler option. That will translate the code to IL, it can execute on most any .NET enabled platform. There are very few C++ constructs that cannot be translated, it would have to use non-standard compiler extensions like __fastcall.
However, I suspect that you will find out that the platform requires verifiable code. Which is the common reason why a platform would restrict code to a .NET compliant language. I cannot guess at this since you didn't mention the execution environment. Native C++ translated to IL is not verifiable due to pointer manipulations. If that's the case then you are looking at a pretty drastic rewrite.
I'd be interested to know where C# is the "only supported platform".
The problem of rewriting in a new language can be whether you need to rewrite every single part of the code and cannot use any of the old code at all. Sometimes it is best, even when doing a rewrite, to make it more of a refactor: rewrite some parts of the code, move others. The existing code is known to work and can be tricky to reproduce. And it takes time. There needs to be a good reason to do a full rewrite.
.NET supports a version of C++, and Visual Studio also comes with Visual C++ to build standard C++, so consider whether or not you can make this a phased transformation, and whether or not you really have to rewrite the whole thing.
Porting C++ code to C# will not be that hard, assuming that all your dependent libraries have existing C# counterparts. Lack of dependencies is the most likely pitfall. The core concepts of your program, such as inheritance, heap, references, data structures, should be fairly easily translatable.
This is assuming that you don't invoke any specific low level behaviour such as custom memory management, because C# does not really support that kind of thing and you could have a serious problem there.
I have seen online how C# allows you to compile code on the fly and I think that is a really awesome thing. I need to use this functionality for my project. But here is the problem. I'm not trying to compile a whole function or new program dynamically. I just need to call a single statement to create or delete stuff on the fly.
Is there a way C# can compile and/or run a single code statement and allow that statement to act on variables and objects in the current program's scope?
Thanks
You could compile C# using Microsoft.CSharp.CSharpCodeProvider, but that gets really complicated if you want to do it correctly, since you need to load your code in a separate App Domain to prevent memory leaks.
I'd suggest using IronPython or some other DLR language: http://www.codeplex.com/wikipage?ProjectName=IronPython
Some sample here, not sure how up-to-date it is but the idea's pretty much the same: http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml
To give you an alternative rather than using C# as a scripting language, have a look at Conscript [1].
Conscript is a compiled scripting language for .NET.
[1]: http://www.codeproject.com/KB/cs/Conscript.aspx
"I just need to call a single statement to create or delete stuff on the fly." Statements like these make me shudder down to my bones. What are you trying to accomplish here, really? You want to have your user write C# statements and have your program execute them within its AppDomain? Not only is this an immense security risk, it is also a terrible user experience.
Furthermore, C# is not a scripting language. If you try to shoehorn it into being one, You're Gonna Have A Bad Time (TM).
You can, while using the debugger. At a breakpoint, just type some code into the Immediate Window in VS, and viola.
One of the best debugging features there are!
Scripting static languages comes trade-offs. There are scope and security concerns to consider, but they can be controlled.
If you're looking to execute static code (i.e. C#) from within a managed run time, I'd recommend starting with Mono. The Mono team has made strides creating a safe environment to compile JIT code into native code at run time.
Start with their official post on the subject.
It depends on what you are trying to do ... if you are looking to use it as an embedded scripting language within another application, then my answer doesn't apply, but if you just want to execute random C# statements (or programs if you like) and save them as scripts, LinqPad is awesome for that.
I'd like to have access to the bytecode that is currently running or about to run in order to detect certain instructions and take specific actions (depending the instructions). In short, I'd like to monitor the bytecode in order to add safety control (see EDIT #1 for explanation).
Is this possible? I know there are some AOP frameworks that notify you of specific events, like an access to a field or the invocation of a method, but I'd like to skip that extra layer and just look at all the bytecode myself, throughout the entire execution of the application.
I've already looked at the following questions (...among many many others ;) ):
Preprocessing C# - Detecting Methods
What CLR/.NET bytecode tools exist?
as well as several AOP frameworks (although not in great detail, since they don't seem to do quite what I need) and I'm familiar with Mono.Cecil.
I appreciate alternative suggestions, but I don't want to introduce the overhead of an AOP framework when what I actually need is access to the bytecode, without all the stuff they add on top to make it more user-friendly (... admittedly very useful stuff when you don't want to go low-level).
Thanks :)
EDIT #1: more details on what I want to do.
Basically, I have a C# application and I need to monitor the instructions it wants to run in order to detect read or write operations to fields (operations Ldfld and Stfld) and insert some instructions before the read/write takes place: I may need to acquire locks, or if that fails abort the operation. Also, I may need to update a read log (in case of a read) or write log (in case of a write).
In fact, what I'd really like to do is to replace the read/write instruction with my own custom code, but it that fails I think I could manage just inserting some instructions before and after.
EDIT #2: PostSharp
Dave suggests I use PostSharp
The problem is at compile time I still don't know which classes I'm going to need to weave, so I'd like to delay this until they are loaded. As I understand, this isn't possible with PostSharp? Please correct me if I'm wrong.
I know PostSharp does load-time static weaving, but apparently "there is currently no "off-the-shelf" way to perform it" (notice however that this post is from PostSharp 1.5; maybe this has changed). I guess it would still be easier than just doing everything myself, but I can't find any info on how PostSharp would help me in this case. I guess I'll ask in the PostSharp forums.
What kind of "safety control"? Have you looked into the Code Access Security provided with the .NET framework?
http://msdn.microsoft.com/en-us/library/930b76w0%28VS.80%29.aspx
http://www.codeproject.com/KB/security/UB_CAS_NET.aspx
The answer is no. You can use the (extremely low-level and unmanaged-code-only) Profiling API to receive notifications of certain events, but not of access to fields, which is what I wanted. Plus, it's not supposed to be used in production:
(from the previous link)
Profiling in production environments
with high-availability requirements.
The profiling API was created to
support development-time diagnostics.
It has not undergone the rigorous
testing required to support production
environments.
I have some old C 32 Bit DLLs that are using Oracle's Pro C precompiler library (proc.exe) to expose a hundred or so sproc/func calls to an even older VB6 GUI which references these functions through explicit Declare statements like so:
Declare Function ConnectToDB Lib "C:\windows\system32\EXTRACT32.DLL" (CXN As CXNdets, ERR As ERRdets) As Long
All the structures in the C header files are painstakingly replicated in the VB6 front end. At least the SQL is precompiled.
My question is, is it worth trying to impose a .Net interface (by conversion to an assembly) onto the the C code and upgrade the VB6 to C# or do you think I should just abandon the whole thing and start from scratch. As always, time is of the essence hence my appeal for prior experience. I know that if I keep the Declares in .Net I will have to add lots of complicated marshalling decorations which I'd like to avoid.
I've never had to Convert C to .Net before so my main question if everything else is ignored is are there any porting limitations that make this inadvisable?
... At least the SQL is precompiled.
Is this the only reason you've got code in C? If so, my advice is to abandon that and simply rewrite the entire thing in C# (or even VB6 if that's what your app is written in) ... unless you've profiled it and can prove a measurable difference, you won't be getting any perf benefits from having sql/sproc calls in C. You will only get increased maintenance costs due to the complexity of having to maintain this interop bridge.
You should continue to use the DLL in .NET by creating an assembly around the Declares. That one assembly probably would go a little quicker in VB.NET than C#. Then have your new UI reference that assembly. Once you have that going then you have bought yourself time to convert the C code into .NET. You do this by initially keeping the assembly and replacing the the declares with new .NET code. Soon you will have replaced everything and can refactor it to a different design.
The time killer is breaking behavior. The closer you can preserve the behavior of the original application the faster the conversion will be. Remember there nothing wrong with referencing a traditional DLL. .NET is built on many layers of APIs which ultimately drill down to the traditional DLLs that continue to be used by Windows. Again once you have the .NET UI working then you have more time to work on the core and bring everything into .NET.
I always advise extreme caution before setting out to rewrite anything. If you use a decent tool to upgrade the VB6 to .NET, it will convert the Declare statements automatically, so don't stress about them too much!
It's a common pitfall to start out optimistically rewriting a large piece of software, make good early progress fixing some of the well-known flaws in the old architecture, and then get bogged down in the functionality that you've just been taking for granted for years. At this point your management begin to get twitchy and everything can get very uncomfortable. I have been there and it's no fun. Sounds like your users are already twitchy, which is a bad sign.
...and here's a blog post by a Microsofty that agrees with me:
Many companies I worked with in the early days of .NET looked first at rewriting driven in part by a strong desire to improve the underlying architecture and code structures at the same time as they moved to .NET. Unfortunately many of those projects ran into difficulty and several were never completed. The problem they were trying to solve was too large
...and some official advice from Microsoft UK regarding migrating from VB6 to .NET
Performing a complete rewrite to .NET is far more costly and difficult to do well [than converting] ... we would only recommend this approach for a small number of situations.
Maybe your program is small, and you have a great understanding of the problems it solves, and you are great at estimating accurately and keeping your projects on track, and it will all be fine.
If you move from VB6 to VB.net or C#, throw away the C code and use the appropriate ODP.net classes or LINQ to access those stored procedures. Since the C layer (as I understand it) has no logic other than exposing the stored procedures, it's not useful anymore after the switch. By doing that, you get (at least) much better exception handling (i.e. exceptions at all instead of magic return codes), maintainability etc.
See also: Automatically create C# wrapper classes around stored procedures
Please give me some insight on how to get the best start on applying Aspect Oriented Programming to my C#.net applications?
PostSharp has the added advantage that it does it's AOP by doing IL weaving. In fact it adds code to the Il when/or just after compiling. Which makes the builds slower but it should be faster at runtime.
Some other do this at runtime (the castle project and I think it's windsor in there that does the AOP) which is slower at runtime but faster to build.
I recommend trying Spring.NET. It lets you create "Interceptor" classes that can be wrapped around calls into business objects simply by adding entries into the application's config file.
We've used it to do connection/transaction handling, error logging and authentication. Which keeps all of those "aspects" out of the business logic code.
PostSharp is a fairly straightforward way of adding aspects to your C# code.