Log all function invocations to console - c#

It occurs pretty often that I start debugging a class by logging every function call to console and looking for differences in the bugged cases.
Is there some attribute that I can apply to a class to enable such a tracing? It's pretty exhausting to have to enter these
Console.WriteLine("classname: methodname")
to every method and to remove them afterwards (removing can be done by conditional compilation, but it is not very nice to look at the code when you have all this redundance)

There was an add-on tool someone mentioned to me, using Attributes. Let's see if I can find it.
I think it was PostSharp:
Article
http://www.postsharp.org/

You can use PostSharp to intercept all method calls and print them even with all arguments and it does not require source code changes. This CodeProject article shows how to do logging with PostSharp.
Just to note, PostSharp is an aspect-oriented programming (AOP) framework and there are some more.

If log4net is as good as log4j, then you are all set
http://logging.apache.org/log4net//index.html

In the dim dark ages of software engineering, one often used a profiling tool to achieve that since profiling injected extra code at entry and exit of all functions, although I must say that this is a pretty dismal approach to debugging and when I used it, it was a desperation move not front line. Debugging by print statement is fairly slow and ineffective.

AOP is supported also by http://www.springframework.net/

Related

identify classes referencing unnecessary interfaces [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have to refactor a large C# application, and I found a lot of functions that are never used. How can I check for unused code, so I can remove all the unused functions?
Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.
As pointed Jeff the tool NDepend can help to find unused methods, fields and types.
To elaborate a bit, NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection
Basically such a rule to detect unused method for example looks like:
// <Name>Dead Methods</Name>
warnif count > 0
from m in Application.Methods where !m.MethodsCallingMe.Any()
select m
But this rule is naive and will return trivial false positives. There are many situations where a method is never called yet it is not unused (entry point, class constructor, finaliser...) this is why the 3 default rules are more elaborated:
Potentially dead Types (hence detect unused class, struct, interface, delegate...)
Potentially dead Methods
Potentially dead Fields
NDepend integrates in Visual Studio 2022, 2019, 2017,2015, 2013, 2012, 2010, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements. NDepend has also a VS Team Services extension.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
Disclaimer: I work for NDepend.
I would also mention that using IOC aka Unity may make these assessments misleading. I may have erred but several very important classes that are instantiated via Unity appear to have no instantiation as far as ReSharper can tell. If I followed the ReSharper recommendations I would get hosed!
ReSharper does a great job of finding unused code.
In the VS IDE, you can right click on the definition and choose 'Find All
References', although this only works at the solution level.
The truth is that the tool can never give you a 100% certain answer, but coverage tool can give you a pretty good run for the money.
If you count with comprehensive unit test suite, than you can use test coverage tool to see exactly what lines of code were not executed during the test run. You will still need to analyze the code manually: either eliminate what you consider dead code or write test to improve test coverage.
One such tool is NCover, with open source precursor on Sourceforge. Another alternative is PartCover.
Check out this answer on stackoverflow.
I have come across AXTools CODESMART..Try that once.
Use code analyzer in reviews section.It will list dead local and global functions along with
other issues.
FXCop is a code analyzer... It does much more than find unused code. I used FXCop for a while, and was so lost in its recommendations that I uninstalled it.
I think NDepend looks like a more likely candidate.

FxCop custom rule requiring validation of parameters

I'm trying to make a custom FxCop rule that will test for calls to the indexer getter of Request.QueryString without a previous call (in the same method) to a certain validation method from our project's Utilities module.
The documentation I've found is not in-depth enough to get me where I need to go. Is there some doc that I'm missing? Or is it time for trial and error?
What I've seen:
http://www.binarycoder.net/fxcop/
http://blog.tatham.oddie.com.au/2010/01/06/custom-code-analysis-rules-in-vs2010-and-how-to-make-them-run-in-fxcop-and-vs2008-too/
http://blogs.msdn.com/b/codeanalysis/
http://msdn.microsoft.com/en-us/magazine/cc163930.aspx
As well as all SO posts tagged FxCop with the word custom.
Any ideas?
There is no official SDK for FxCop rules. The most complete single resource is http://www.binarycoder.net/fxcop/. Pretty much all the available resources are geared toward helping one get started with the "wrapper" mechanics of creating rules. None of them really cover the finicky details of how to create specific rule logic. For that sort of thing, your best bet is to grab a decompiler like Reflector so that you can see how the Microsoft-supplied rules are built. Another helpful technique is to run your embryonic rules under the debugger so that you can see the objects and properties that are available at runtime. If you get stuck with some particular part of a rule implementation, you can always ask about it either here or on the FxCop forum maintained by Microsoft.

using c# like script in runtime

I want to learn if there is any library in .net to write c# scripts. Let me describe you with more detail, for example I have an application. When I run it, a c# editor will be opened end user will write some c# codes and when click run, this code should be evaluated and dom should be created after interpret my run time c# code will run. this is brief description of my mind...
I put together a little app called SimpleDevelop which uses CSharpCodeProvider to do what you describe. My understanding is that this (CodeDom) is deprecated and generally discouraged; however, it seems to work just fine for simple scenarios.
Basically, you want to use something like the CSharpCodeProvider. The Razor view engine in MVC essentially uses this to compile your code into an executable to run. If you want your user to be able to write code and then have it interpreted, you would start here. Please note though, this is an incredibly complicated and time intensive feat to get right; plus, linking in and executing foreign code dynamically is a security nightmare. Just be safe.
Are you looking for a test bench sort of?
I use LinqPad for that.
It is mostly a test bench for Linq queries, but I find it very useful for C# statements and mini programs and such.
Check out the System.CodeDom namespace.
This article contains lots of useful information: http://www.developerfusion.com/article/4529/using-net-to-make-your-application-scriptable/2/
You can use the Compiler namespace and compilate the code at runtime. Take a look here for an explanation on how to do it.
I have created an application which will run c# like script without using visual studio.
It is on https://sourceforge.net/projects/csharpquickcode/

Lex/Yacc for C#?

Actually, maybe not full-blown Lex/Yacc. I'm implementing a command-interpreter front-end to administer a webapp. I'm looking for something that'll take a grammar definition and turn it into a parser that directly invokes methods on my object. Similar to how ASP.NET MVC can figure out which controller method to invoke, and how to pony up the arguments.
So, if the user types "create foo" at my command-prompt, it should transparently call a method:
private void Create(string id) { /* ... */ }
Oh, and if it could generate help text from (e.g.) attributes on those controller methods, that'd be awesome, too.
I've done a couple of small projects with GPLEX/GPPG, which are pretty straightforward reimplementations of LEX/YACC in C#. I've not used any of the other tools above, so I can't really compare them, but these worked fine.
GPPG can be found here and GPLEX here.
That being said, I agree, a full LEX/YACC solution probably is overkill for your problem. I would suggest generating a set of bindings using IronPython: it interfaces easily with .NET code, non-programmers seem to find the basic syntax fairly usable, and it gives you a lot of flexibility/power if you choose to use it.
I'm not sure Lex/Yacc will be of any help. You'll just need a basic tokenizer and an interpreter which are faster to write by hand. If you're still into parsing route see Irony.
As a sidenote: have you considered PowerShell and its commandlets?
Also look at Antlr, which has C# support.
Still early CTP so can't be used in production apps but you may be interested in Oslo/MGrammar:
http://msdn.microsoft.com/en-us/oslo/
Jison is getting a lot of traction recently. It is a Bison port to javascript. Because of it's extremely simple nature, I've ported the jison parsing/lexing template to php, and now to C#. It is still very new, but if you get a chance, take a look at it here: https://github.com/robertleeplummerjr/jison/tree/master/ports/csharp/Jison
If you don't fear alpha software and want an alternative to Lex / Yacc for creating your own languages, you might look into Oslo. I would recommend you to sit through session recordings of sessions TL27 and TL31 from last years PDC. TL31 directly addresses the creation of Domain Specific Languages using Oslo.
Coco/R is a compiler generator with a .NET implementation. You could try that out, but I'm not sure if getting such a library to work would be faster than writing your own tokenizer.
http://www.ssw.uni-linz.ac.at/Research/Projects/Coco/
I would suggest csflex - C# port of flex - most famous unix scanner generator.
I believe that lex/yacc are in one of the SDKs already (i.e. RTM). Either Windows or .NET Framework SDK.
Gardens Point Parser Generator here provides Yacc/Bison functionality for C#. It can be donwloaded here. A usefull example using GPPG is provided here
As Anton said, PowerShell is probably the way to go. If you do want a lex/ yacc implementation then Malcolm Crowe has a good set.
Edit: Direct Link to the Compiler Tools
Just for the record, implementation of lexer and LALR parser in C# for C#:
http://code.google.com/p/naive-language-tools/
It should be similar in use to Lex/Yacc, however those tools (NLT) are not generators! Thus, forget about speed.

Find unused code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have to refactor a large C# application, and I found a lot of functions that are never used. How can I check for unused code, so I can remove all the unused functions?
Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.
As pointed Jeff the tool NDepend can help to find unused methods, fields and types.
To elaborate a bit, NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection
Basically such a rule to detect unused method for example looks like:
// <Name>Dead Methods</Name>
warnif count > 0
from m in Application.Methods where !m.MethodsCallingMe.Any()
select m
But this rule is naive and will return trivial false positives. There are many situations where a method is never called yet it is not unused (entry point, class constructor, finaliser...) this is why the 3 default rules are more elaborated:
Potentially dead Types (hence detect unused class, struct, interface, delegate...)
Potentially dead Methods
Potentially dead Fields
NDepend integrates in Visual Studio 2022, 2019, 2017,2015, 2013, 2012, 2010, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements. NDepend has also a VS Team Services extension.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
Disclaimer: I work for NDepend.
I would also mention that using IOC aka Unity may make these assessments misleading. I may have erred but several very important classes that are instantiated via Unity appear to have no instantiation as far as ReSharper can tell. If I followed the ReSharper recommendations I would get hosed!
ReSharper does a great job of finding unused code.
In the VS IDE, you can right click on the definition and choose 'Find All
References', although this only works at the solution level.
The truth is that the tool can never give you a 100% certain answer, but coverage tool can give you a pretty good run for the money.
If you count with comprehensive unit test suite, than you can use test coverage tool to see exactly what lines of code were not executed during the test run. You will still need to analyze the code manually: either eliminate what you consider dead code or write test to improve test coverage.
One such tool is NCover, with open source precursor on Sourceforge. Another alternative is PartCover.
Check out this answer on stackoverflow.
I have come across AXTools CODESMART..Try that once.
Use code analyzer in reviews section.It will list dead local and global functions along with
other issues.
FXCop is a code analyzer... It does much more than find unused code. I used FXCop for a while, and was so lost in its recommendations that I uninstalled it.
I think NDepend looks like a more likely candidate.

Categories

Resources