How to make a "Call stack diagram" - c#

Creating a call stack diagram
We have just recently been thrown into a big project that requires us to get into the code (duh).
We are using different methods to get acquainted with it, breakpoints etc. However we found that one method is to make a call tree of the application, what is the easiest /fastest way to do this?
By code? Plugins? Manually?
The project is a C# Windows application.

With the static analyzer NDepend, you can obtain a static method call graph, like the one below. Disclaimer: I am one of the developers of the tool
For that you just need to export to the graph the result of a CQLinq code query:
Such a code query, can be generated actually for any method, thanks to the right-click menu illustrated below.

Whenever I start a new job (which is frequently as I am a contractor) I spend two to three days reading through every single source file in the repository, and keep notes against each class in a simple text file. It is quite laborious but it means that you get a really good idea how the project fits together and you have a trusty map when you need to find the class that does somethnig.
Altought I love UML/diagramming when starting a project I, personally, do not find them at all useful when examining existing code.

Not a direct answer to your question, but NDepend is a good tool to get a 100ft view of a codebase, and it enables you to drill down into the relationships between classes (and many other features)

Edit: I believe the Microsoft's CLR Profiler is capable of displaying a call tree for a running application. If that is not sufficient I have left the link I posted below in case you would like to start on a custom solution.
Here is a CodeProject article that might point you in the right direction:
The download offered here is a Visual
Studio 2008 C# project for a simple
utility to list user function call
trees in C# code.
This call tree lister seems to work OK
for my style of coding, but will
likely be unreliable for some other
styles of coding. It is offered here
with two thoughts: first, some
programmers may find it useful as is;
second, I would be appreciative if
someone who is up-to-speed on C#
parsing would upgrade it by
incorporating an accurate C# parser
and turn out an improved utility that
is reliable regardless of coding style
The source code is available for download - perhaps you can use this as a starting point for a custom solution.

You mean something like this: http://erik.doernenburg.com/2008/09/call-graph-visualisation-with-aspectj-and-dot/

Not to be a stuck record, but if I get it running and pause it a few times, and each time capture the call stack, that gives me a real good picture of the call structure that accounts for the most time. It doesn't give me the call structure for things that happen real fast, however.

Related

Exclude other methods, variables and classes that are not needed for your method to work

You load a foreign code example with libraries attached to it in Visual Studio. Now there is a method that you want to reuse in your code. Is there a function in VS that lets you strip the code from all unnecessary code to only have code left that is necessary for your current method to run?
It is not about the library. Loading a .sln or .csproj and having classes over classes when you just want one method out of it is a waste of performance, ram and space. It is about code you can easily omit or references(what I call libraries) you can easily omit. A part-question of this is: Which "using" statement do you need that is only necessary for your current method and the methods that pass paramaters to it? In short, showing relevant code only. Code that is tied to each other.
Let's use an example: You go to github and download source code in c#. Let's call the solution S. You open S in Visual Studio. You don't disassemble, you just load the source code of S, that is there in plain text. Then you find a method M - in plain text - that you want to use. M contains some objects whose classes were defined somewhere in the project. The goal is to recreate the surrounding only for this method to copy & paste it into my own solution without having red underlined words in almost every line within the method
after reading the question and the comments, I think I have a vague idea what you are referring to.
In case we ignore the context of the method you are referring, you can extract any code piece from a "library" by using a .NET decompiler and assembly browser.
There are many of them for free, such as:
dotPeek,
ILSpy
...
This will allow you to see the method's code. From there on, you can proceed as you like. In case your copy the method to your code base, you might still have to change it a bit in order to adapt it to work with your objects and context. If you don't, this will give you insight on how the method works and might help you to understand the logic, so you can write your own.
Disclaimer: With this post, I am pointing out that it is possible to extract code from an assembly. I am not discussing the ethics or legal perspective behind such actions.
Hope this helps,
Happy Coding!
If it`s just one method, look at the source code and copy it to your libarary. Make sure you make a comment where you obtained the code and who has the copyright! Don't forget to include the licence, which you should have done with a libary reference anyway.
That said it is currently not (official) possible to automaticly remove unused public declared code from a library (assembly). This process is called Treeshaking by the way. Exception: .NET Native.
But .NET Native is only available for Windows Store Apps. You can read more about it here.
That said, we have the JIT (Just in Time)-Compiler which is realy smart. I wouldn't worry about a few KB library code. Spend your time optimizing your SQL Queries and other bottlenecks. The classes are only loaded, when you actualy use them.
Using some unstable solutions or maintaining a fork of a library, where you use more then one method (with no documentation and no expertise, since it is your own fork) isn't worth the headache, you will have!
If you realy want to go the route of removing everything you do not want, you can open the solution, declare everything as internal (search and replace is your friend) and restore the parts to public, which are giving you are Buildtime error / Runtime error (Reflection). Then remove everything which is internal. There are several DesignTime tools like Resharper, which can remove Dead Code.
But as I said, it's not worth it!
For .NET Core users, in 6-8 weeks, we have the .NET IL Linker as spender has commented, it looks promising. What does this mean? The .NET framework evolves from time to time. Let it envolve and look at your productivity in the meantime.

Parsing C# and VB.Net code to automate the code review process

The customer has million lines of code (VB.Net and C#), and wants us to develop a tool to estimate the quality of the code.
What the information the customer wants to know include:
1)how many lines of comments in one code file
2) how many functions implemented in one class
3) whether all possible exception has been wrapped by a try/catch block
4) how many attributes attached to one function
5) ... (the customer said that the tool we provide should be configured and extensible so that they can implement more ideas later)
We plan to write a VS.Net add-on, which can parse the code of the opening project in time. seems the interesting thing in here is that we need to parsing the code of C# and VB.Net.
Please kindly provide some tips about how to start this interesting task.
Thanks in advanced!
You ask a very broad question, but you should begin by studying existing parser's APIs.
Once you do that you're golden.
For example look at this SO question which provides some parsers for C#. Of course you could write your own but I don't find any reason to since the task isn't very easy.
So you get your AST and once you do that you have all the information you want.
Keep in mind that if you reference a type that isn't in the file you must have to get it from another one, and it could also be a type from .NET. So there is definitely more work to be done.
To go through your list:
1)how many lines of comments in one code file: You could find it through your C# parser of choice. They recognize comment aswell
2) how many functions implemented in one class: Likewise, should be very easy
3) whether all possible exception has been wrapped by a try/catch block: Likewise, just find exception throws (the parser is likely to have a special type for language keywords, so looking for throw should be easy).
4) how many attributes attached to one function: and... Likewise
5) ... (the customer said that the tool we provide should be configured and extensible so that they can implement more ideas later): Shouldn't differ from any other project. Just make sure you're using good design principles, keeping everything abstract, using interfaces wisely, make your work in layers, etc. etc...
You can use Roslyn. For C# you can also use NRefactory.
Have a look at Stylecop, you may be able to add rules get the information you want?
http://stylecop.codeplex.com/

How to analyse usage of my C# code (and some SQL code also) - in terms of number of methods/classes and number of times they are called

On high level my problem is -
We have couple of applications which have millions of lines of legacy code (C# and SQL). I need to figure out code areas which are being used most?
It may not be possible to find exact figures (especially in apps when code is being called based on user's action in GUI).
However, to get some rough figures few thoughts I have are to find out:
1) Find out List of Classes and Methods
2) Find out number of time they are called from within the code. (by means of direct method calls/delegates etc)
3) Find out all the stored procs/db functions (this would be bit staright forward)
4) Find out all the calls to stored procs
Could you please let me know - if you are aware of any tools to achive this?
Or any other idea to fetch above 4 details? Also, apart from these any other way to to do this analysis?
Thanks in advance!
I have used Red Gate's ANTS Profiler before:
http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/
It's powerful and very easy to use (comes with a visual studio plugin). 14 days free!
One way you could achieve this is using Aspect Oriented Programming (AOP). I have used this previously in Java with the Spring Framework, but haven't used it before on .NET projects.
You could check out something like;
http://blogs.msdn.com/b/morgan/archive/2008/12/18/method-entry-exit-logging.aspx
This will give you an idea of how frequently methods are being called. Your will need simply need to collate the data in the logs into some form giving you an overall idea of usage patterns of the codebase.
Edit:
Further information on using this method can be found on other SO posts;
Logging entry and exit of methods along with parameters automagically?
https://stackoverflow.com/a/25825/685760

Preprocessing C# - Detecting Methods

I require the ability to preprocess a number of C# files as a prebuild step for a project, detect the start of methods, and insert generated code at the start of the method, before any existing code. I am, however, having a problem detecting the opening of a method. I initially tried a regular expression to match, but ended up with far too many false positives.
I would use reflection, but the MethodInfo class does not reference the point in the original source.
EDIT: What I am really trying to do here is to support pre-conditions on methods, that pre-condition code being determined by attributes on the method. My initial thought being that I could look for the beginning of the method, and then insert generated code for handling the pre-conditions.
Is there a better way to do this? I am open to creating a Visual Studio Addin if need be.
This is a .NET 2.0 project.
Cheers
PostSharp or Mono.Cecil will let you do this cleanly by altering the generated code without getting into writing a C# parser which is unlikely to be core business for you...
Havent done anything of consequence with PostSharp but would be guessing its more appropriate than Mono for implementing something like preconditions or AOP. Alternately you might be able to do something AOPy with a DI container like Ninject
But of course the applicability of this idea Depends - you didnt say much other than that you wanted to insert code at the start of methods...
EDIT: In light of your desire to do preconditions... Code Contracts in .net 4 is definitely in that direction.
What sort of a tool do you have? Whats wrong with having a single Mono.Cecil.dll DLL shipped? Either way something other than a parser is the tool for the job.
I am sure there is an easier way but this might be a good excuse to take MGrammer for a spin.

How do you programmatically identify the number of references to a method with C#

I've recently inherited C# console application that is in need of some pruning and clean up. Long story short, the app consists of a single class containing over 110,000 lines of code. Yup, over 110,000 lines in a single class. And, of course, the app is core to our business, running 'round the clock updating data used on a dynamic website. Although I'm told my predecessor was "a really good programmer", it obvious he was not at all into OOP (or version control).
Anyway... while familiarizing myself with the code I've found plenty of methods that are declared, but never referenced. It looks as if copy/paste was used to version the code, for example say I have a method called getSomethingImportant(), chances are there is another method called getSomethingImortant_July2007() (the pattern is functionName_[datestamp] in most cases). It looks like when the programmer was asked to make a change to getSomethingImportant() he would copy/paste then rename to getSomethingImortant_Date, make changes to getSomethingImortant_Date, then change any method calls in the code to the new method name, leaving the old method in the code but never referenced.
I'd like to write a simple console app that crawls through the one huge class and returns a list of all methods with the number of times each method was referenced. By my estimates there are well over 1000 methods, so doing this by hand would take a while.
Are there classes within the .NET framework that I can use to examine this code? Or any other usefull tools that may help identify methods that are declared but never referenced?
(Side question: Has anyone else ever seen a C# app like this, one reeeealy big class? It's more or less one huge procedural process, I know this is the first I've seen, at least of this size.)
You could try to use NDepend if you just need to extract some stats about your class. Note that this tool relies on Mono.Cecil internally to inspect assemblies.
To complete the Romain Verdier answer, lets dig a bit into what NDepend can bring to you here. (Disclaimer: I am a developer of the NDepend team)
NDepend lets query your .NET code with some LINQ queries. Knowing which methods call and is called by which others, is as simple as writing the following LINQ query:
from m in Application.Methods
select new { m, m.MethodsCalled, m.MethodsCallingMe }
The result of this query is presented in a way that makes easy to browse callers and callees (and its 100% integrated into Visual Studio).
There are many other NDepend capabilities that can help you. For example you can right click a method in Visual Studio > NDepend > Select methods... > that are using me (directly or indirectly) ...
The following code query is generated...
from m in Methods
let depth0 = m.DepthOfIsUsing("NUnit.Framework.Constraints.ConstraintExpression.Property(String)")
where depth0 >= 0 orderby depth0
select new { m, depth0 }
... which matches direct and indirect callers, with the depth of calls (1 means direct caller, 2 means caller of direct callers and so on).
And then by clicking the button Export to Graph, you get a call graph of your pivot method (of course it could be the other way around, i.e method called directly or indirectly by a particular pivot method).
Download the free trial of Resharper. Use the Resharper->Search->Find Usages in File (Ctrl-Shift-F7) to have all usages highlighted. Also, a count will appear in the status bar. If you want to search across multiple files, you can do that too using Ctrl-Alt-F7.
If you don't like that, do text search for the function name in Visual Studio (Ctrl-Shift-F), this should tell you how many occurrences were found in the solution, and where they are.
I don't think you want to write this yourself - just buy NDepend and use its Code Query Language
There is no easy tool to do that in .NET framework itself. However I don't think you really need a list of unused methods at once. As I see it, you'll just go through the code and for each method you'll check if it's unused and then delete it if so. I'd use Visual Studio "Find References" command to do that. Alternatively you can use Resharper with its "Analize" window. Or you can just use Visual Studio code analysis tool to find all unused private methods.
FXCop has a rule that will identify unused private methods. So you could mark all the methods private and have it generate a list.
FXCop also has a language if you wanted to get fancier
http://www.binarycoder.net/fxcop/
If you don't want to shell out for NDepend, since it sounds like there is just a single class in a single assembly - comment out the methods and compile. If it compiles, delete them - you aren't going to have any inheritance issues, virtual methods or anything like that. I know it sounds primitive, but sometimes refactoring is just grunt work like this. This is kind of assuming you have unit tests you run after each build until you've got the code cleaned up (Red/Green/Refactor).
The Analyzer window in Reflector can show you where a method is called (Used By).
Sounds like it would take a very long time to get the information that way though.
You might look at the API that Reflector provides for writing add-ins and see if you can get the grunt work of the analysis that way. I would expect that the source code for the code metrics add-in could tell you a bit about how to get information about methods from the reflector API.
Edit: Also the code model viewer add-in for Reflector could help too. It's a good way to explore the Reflector API.
I don't know of anything that's built to handle this specific case, but you could use Mono.Cecil. Reflect the assemblies and then count references in the IL. Shouldn't be too tough.
Try having the compiler emit assembler files, as in x86 instructions, not .NET assemblies.
Why? Because it's much easier to parse assembler code than it is C# code or .NET assemblies.
For instance, a function/method declaration looks something like this:
.string "w+"
.text
.type create_secure_tmpfile, #function
create_secure_tmpfile:
pushl %ebp
movl %esp, %ebp
subl $24, %esp
movl $-1, -8(%ebp)
subl $4, %esp
and function/method references will look something like this:
subl $12, %esp
pushl 24(%ebp)
call create_secure_tmpfile
addl $16, %esp
movl 20(%ebp), %edx
movl %eax, (%edx)
When you see "create_secure_tmpfile:" you know you have a function/method declaration, and when you see "call create_secure_tmpfile" you know you have a function/method reference. This may be good enough for your purposes, but if not it's just a few more steps before you can generate a very cute call-tree for your entire application.

Categories