Order of Classes within an Assembly - c#

What determines the order of classes within an Assembly?
And.. is there a way to change it?
Additional info: you can check the ordering either through reflection yourself, or you can use a tool like ILDASM, disable the alphabetical sorting, and then you will also get the order.
Order seems to be in a strange way determined by the compiler.
I already tried some things.. like renaming the classes (order stays the same), also editing the .csproj file to change the order of the .cs files.
My main focus is VS2008, C#, .net 3.5.
Update: I do have a scenario where the order matters (external program going through my assembly through reflection) - and I need special order there.
Apart from this - you are totally right - order really should not matter.

I'm going to stick my neck out here and say this is an implementation detail and may well be decided by any particular compiler.
Since this is an implementation detail you shouldn't or needn't be concerned. Of course if this really is important (can't see why) you can always write your own IL.
I leave you with the following quote from Eric's blog:
Is compiling the same C# program twice guaranteed to produce the same
binary output?
No.

What determines the order of classes within an Assembly?
The compiler.
And.. is there a way to change it?
Write your own IL directly.
That being said, the order of the types within the assembly really doesn't matter. You can use the types with no regard to their order.

Related

How determine that assembly was compiled from f# project?

What is the difference between c# and f# assemblies? Some flag maybe? I want to determine it using reflection API only
There's no single value to check that would tell you what you need, but there's a good amount of circumstancial evidence that you could look at - IlSpy is your friend if you want to explore it.
I would suggest you check for presence of these two indicators, either of them being present would mean you're likely looking at an F# assembly unless someone is really dedicated to mess things up for you.
FSharpInterfaceDataVersionAttribute on the assembly. This was my initial suggestion, however there are compiler flags that, when set, would prevent this attribute from being emitted: --standalone and --nointerfacedata. I find it highly doubtful either of them would be commonly used in the field, but the fact remains there are openly available ways of opting out from the attribute being emitted right now.
asm.GetCustomAttribute(typeof(FSharpInterfaceDataVersionAttribute))
Presence of StartupCode types. They're an artifact of how F# compiler compiles certain constructs, and it seems they're present even empty, so they should be highly reliable.
asm.GetTypes().Where(fun x -> x.FullName.StartsWith("<StartupCode$"))
In particular looking for a reference to FSharp.Core is not a great idea, as it would be commonly referenced from C# projects as well if you're working with mixed solutions (and there's nothing stopping anyone from just getting it off nuget).

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.

Is there a way to find what Types are referenced by a c# assembly?

The Assembly class has a GetReferencedAssemblies method that returns the
referenced assemblies. Is there a way to find what Types are referenced?
The CLR wont be able to tell you at runtime. You would have to do some serious static analysis of the source files - similar to the static analysis done by resharper or visual studio.
Static analysis is fairly major undertaking. You basically need a c# parser, a symbol table and plenty of time to work through all the cases that come up in abstract syntax trees.
Why can't the CLR tell you at run time? It is just in time compiled, this means that CLR bytcode is converted into machine code just before execution. Reflection only tells you stuff known statically at runtime about your types, and the CLR would only know if a type is referenced when the code is run. The CLR only knows when a type is loaded at execution time - at the point of just in time compilation.
Use System.Reflection.Assembly.GetTypes().
Types are not referenced separately from assemblies. If an assembly references another assembly, it automatically references (at least in the technical context) all the types within that assembly, as well. In order to get all the types defined (not referenced) in an assembly, you can use the Assembly.GetTypes method.
It may be possible, but sounds like a rather arduous task, to scan an assembly for which actual types it references (i.e. which types it actually invokes or otherwise mentions). This will probably involve working with IL. Something like this is best to be avoided.
Edit: Actually, when I think about it, this is not possible at all. Whatsoever. On a quite basic level. The thing is, types can be instantiated and referenced willy-nilly. It's not even uncommon for this to happen. Not to mention late binding. All this means trying to analyze an assembly for all the types it references is something like predicting the future.
Edit 2: Comments
While the question, as stated, isn't possible due to all sorts of dynamic references, it is possible greatly shrink all sorts of binary files using difference encoding. This basically allows you to get a file containing the differences between two binary files, which in the case of executables/libraries, tends to be vastly smaller than either of the actual files. Here are some applications that perform this operation. Note that bsdiff doesn't run on Windows, but there is a link to a port there, and you can find many more ports (including to .NET) with the aid of Google.
XDelta
bsdiff
If you'd look, you'll find many more such applications. One of the best parts is, they are totally self-contained and involve very little work on your part.

Assembly ordering in .net c#

A similar question has been asked in Ordering of reflection requests in dotnet
But I'm hoping for a different answer... I'm writing a plugin for a program that uses reflection to interrogate plugins to find the entry point. Unfortunately it has a bug which means if it encounters an interface declaration during this process it crashes with an unhandled exception. I have spoken to the development team and this is unlikely to be fixed. This is extremely limiting for me for obvious reasons. One workaround I have already thought of is to have my assembly load another assembly with the interfaces in it, but for reasons I won't go into this is not a great solution. It was a while before I encountered this problem because for some reason my entry class always preceded my interfaces in the reflection enumeration order.
My question is, is there any way to influence the ordering of classes and interfaces in the assembly?
Note: I have already tried setting different accessibility levels on my interfaces but that doesn't work for me.
Cheers,
J
I'd bet the code using AppDomain.GetAssemblies() which are then inspected. The implementation of AppDomain.GetAssemblies() leads to an external method, so Reflector is of mostly no help here.
However, without actually trying it and inspecting the result, there are two logical options for the ordering of assemblies in the result:
Load order
Alphabetical order
In the first case you'd probably have to organize references among your assemblies and the load order in such a way that the foreign code finds the right assembly with the entrypoint class and stops. In the second case it would be a pure matter of naming the assemblies in a 'right' way but I doubt it's this case.
(However, the order may be completely different from the two above, e.g. 'mostly' random as well.)
In either case I think sooner or later the buggy code will encounter the problematic assembly and crash anyway. Thus the strong recommendation is: insist on having the bug fixed.

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