I am to build a SOA gui framework, and I'd like to autodetect services, and service dependencies from client modules. I have code such as this so far, which works using attributes, placed on class modules:
[ServiceProvider(typeof(DemoService3))]
[ServiceConsumer(typeof(DemoService1))]
I am wondering how I can scan for these automagically, so that people wouldn't forget to add the marker and potentially get null references at runtime. In the code services are registered and fetched via the following commands:
Services.RegisterService(new DemoService1());
Services.FetchService<DemoService3>();
I want to find these calls, and also the types being passed in (both take a type param, implicit for the first one)... the rest of the code for doing my dependencies and construction is already done :)
You will need to analyze the IL at the CLR level, not the C# level to figure this out.
You should be able to leverage Mono Cecil to pull this off.
You can either use Mono.Cecil or .NET reflection to accomplish that.
Mono.Cecil is recommended due to its better performance and flexibility. Here are some samples (Cecil + simple extensions on top) that could get you started:
How to Find Extension Methods Targeting Object?
How to Count Methods With NotImplementedException?
How to ensure that classes marked with ImmutableAttribute are Immutable indeed?
How to Change Namespace of .NET Assembly?
If you're unable to use Mono.Cecil for some reason, you could consider parsing the IL by hand: you'd effectively just need to find call and callvirt instructions, possibly doing static analysis enough to understand the type returned by new DemoService1().
typeof(YourClass).GetMethod("YourMethod").GetMethodBody().GetILAsByteArray() is your friend.
Related
I have some DLL from third party that I need to license. It has some method that I must call from my own DLL. My DLL is referenced in couple of projects and I don't want to make changes to every hoster. Is there any method that I can use within my DLL which will call some method in my DLL? Like add some static class or constructor but without explicit call to that class from hosters? I am not sure if I am explaining it clearly. Please ask questions if needed.
ThirdPartyType license = new ThirdPartyType();
license.Load("license.xml");
This is a piece of licensing code that I want to place in my DLL and call it within the same DLL.
At the low level, the runtime supports "module initializers". However, C# does not provide any way of implementing them, so the closest you can manage is a static constructor ("type initializer") or just a regular constructor.
However, it is probably a bad idea to hook your licencing into either a module initializer or a type initializer, as you don't know when they will run, and it could impact code that wasn't going to access your lib. It is somewhat frowned upon to take someone's app down because your licensing code decided it was unhappy - especially if your library wasn't actively being invoked at the time.
As such: I suggest the most appropriate place to do this is in either a constructor, or a post-construction Initialize(...) method (with the tool refusing to work unless supplied with valid details).
I'm working on a collection of code where there's most of the functionality in a PCL. I want to init members like
class CentralInPCL {
public static Func<string> DefaultPathProvider;
This needs to be assigned a lambda () => Path.GetTempFileName() from an assembly built for one of the platforms.
How do I reliably assign this lambda in another assembly?
Can I guarantee a static constructor of a helper class, in another assembly, will be run before any instances of CentralInPCL might be used?
I may have completely mis-understood something about how a PCL works but we're trying to avoid having user code have to pass parameters to the PCL.
As I understand them, a PCL is a leaf library called by platform-specific assemblies.
You would normally give it access to platform stuff by injecting an object or lambda, typically confirming to an interface defined in the PCL.
However, that injection process is explicit and has to be out there in some platform-specific code, usually user code.
I'm trying to add a bit more magic and have some defaults injected without the user knowing.
An old 2005 answer from Jon Skeet suggests you couldn't do it, at least back then.
I found a recipe for doing it with Fody, weaving in a Module Initializer which is an IL thing not able to be declared in C#.
Failing which, we need to require the user to include a call to setup static defaults somewhere.
Is it possible writing code that generate a class, method, member at runtime using .NET (C#)?
For more details consider this scenario :
create a dynamic workflow program to enable user for creating his own process, activities, and writing dynamic SQL SPs, …, and collect all this stuff together then generate a classes, member variables , member functions , UIs, conditions, … dynamically at run-time ! in other word your own dynamic code factory framework !
Yes, there are various options for this:
Use CodeDOM (the System.CodeDom namespace)
Use the System.Reflection.Emit namespace
Create C# code and then compile it with Microsoft.CSharp.CSharpCodeProvider
For individual methods, create an expression tree and then compile it to a delegate
Use the Roslyn CTP to either compile C# code or create your own AST and compile that
The short response is yes. You have to look and study the following technologies:
CodeDom
Windows Wordflow Foundation
If it is anyway useful can be discussed: One able to "dynamically" program a workflow in a so specific mode will probably prefer to write the code by hand himself.
Another alternative of using strong types in this case, you may consider also using
Dynamic object to allow fully featured dynamic behaviour.
Could be more appropriate then strong typing generated at runtime, in this case.
Quick answer: Yes!
For a detail of how to achieve this you would want to start your learning by looking at Reflection.
The next step would be looking for other resources on the internet and a quick search located this question on SO:
How to create a method at runtime using Reflection.emit
Dynamic Language Runtime may also be worth a look.
In C#, is it possible to restrict who can call a method at compile time?
I've looked into directives, but that didn't work since I can't assign values to symbols.
#define WHO VisualStudioUser.Current // does not work
I also looked into Code Access Security (CAS) but that's runtime enforcement, not compile time.
The requirement is to restrict access to a method at compile time for specific developers given the method exists in a pre-compiled assembly.
here's more details...
I'm building a framework or a series or assemblies for a team of developers. Because of our software license restrictions, I can only allow a few developers to write code to make a call to some restricted methods. The developers will not have access to the source code of the framework but they'll have access to the compiled framework assemblies.
The quick answer will be: No this isn't possible, and if you need to do it, you're Doing It Wrong.
How would this even work? Does it depend who who's running the code or who wrote it?
Edit There's kind of a way using InternalsVisibleTo and restricting accessing in source control to the assemblies that InternalsVisibleTo is specified for. See Jordão's answer
The requirement is to restrict access to a method at compile time for specific developers given the method exists in a pre-compiled assembly.
One way is to mark the method private or internal, it won't be callable by anyone outside the assembly. UPDATE: Also take a look at the InternalsVisibleTo attribute, which is used to define which assemblies can "see" internals of your assembly.
Another way is to divide the code you want to distribute from the code you don't want people to call into separate assemblies. Maybe you just share an assembly mostly of interfaces with your users, that they them compile against; and you have a separate assembly with implementations that they shouldn't reference directly. Your internal team would have access to the implementation assembly. This is just a common form of dependency management, the dependency inversion principle.
Draft:
Compile the restricted code into (obfuscated) DLLs: TypeA.dll, TypeB.dll etc.
Define an interface for each type, and compile them into separate DLLs: ITypeA.dll, ITypeB.dll etc.
Create a "guard assembly", and embed all restricted assemblies into it: Guard.dll. This has a ResolveEventHandler, and methods to instantiate different types defined in the embedded restricted DLLs. Instances are returned through their interface.
Developers get the interface DLLs and the Guard.dll. Each developer can get a Guard.dll with special authentication tokens in it. For example, a Guard.dll can be bound to PC, an IP address, a GUID issued to the developer, anything.
The developer can instantiate those types for which she has the proper authentication code, and uses the object instance through an interface.
Sorry this is a bit fuzzy, because it was more than a year ago when I used these techniques. I hope the main idea is clear.
Can you try using Extensible C# developed by ResolveCorp, some of the links for study and implementation are:
http://zef.me/782/extensible-c
http://www.codeproject.com/KB/architecture/DbCwithXCSharp.aspx
http://weblogs.asp.net/nunitaddin/archive/2003/02/14/2412.aspx
http://www.devx.com/dotnet/Article/11579/0/page/5
Is there a way to use reflection to completely "scan" an assembly to see if System.IO.File or System.IO.Directory is ever used? These are just example classes. Just wondering if there is a way to do it via reflection (vs code analysis).
update:
see comments
As Tommy Carlier suggested, it's very easy to do with Cecil.
using Mono.Cecil;
// ..
var assembly = AssemblyFactory.GetAssembly ("Foo.Bar.dll");
var module = assembly.MainModule;
bool references_file = module.TypeReferences.Contains ("System.IO.File");
The fantastic NDepend tool will give you this sort of dependency information.
Load your dll in NDepend and either use the GUI to find what you want, or the following CQL query:
SELECT TYPES WHERE IsDirectlyUsing "System.IO.File"
and you should get a list of all the types that use this.
I'd suggest looking at Mono Cecil for this. With Cecil, you can enumerate all the classes, methods and even the IL-instructions (including all the methods calls).
I don't remember where, but I found this handy piece of code:
http://gist.github.com/raw/104001/5ed01ea8a3bf7c8ad669d836de48209048d02b96/MethodBaseRocks.cs
It adds an extension method to MethodInfo/ConstructorInfo that parses the ILByteArray into Instruction objects.
So with this, you could loop over every MethodInfo/ConstructorInfo in the assembly, then loop over every Instruction on that MethodInfo/ConstructorInfo, and check if any of those Instruction objects contains an Operand which is an instance of a MemberInfo which has a DeclaringType that is equal to either class.
You can get a list of dependent assemblies via Assembly.GetExecutingAssembly().GetReferencedAssemblies(). I don't believe you can comprehend namespace usage via reflection. Try looking at System.CodeDom. That may help you parse the code.
.NET Reflector can do this, or something close to it. The other day I checked to see where a particular type was used.
ReSharper might also help. I do this with my own symbols all the time - I suppose it would also work for .NET Framework types.