How to reliably init C# static members in PCL from other Assemblies? - c#

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.

Related

Is there any way to auto run some code in DLL?

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).

How to replace a static class at runtime

I know you cant override or inherit from a static class and why. That is clear.
I am looking for some advice on how to replace that static class with my own static class. Any hackish or wildest attempts please.
I am basically writing a MOD for a game and the way the game writer wrote one class in particular, he set it as static and put the implementation in there. So when we write our own DLL with this thing, the only way to execute a calculation on the pixel grid is when his code calls this particular calculation in his static class. Both classes are static but I only need to change one.
That is great for him but I want my thing to do another calculation and make it more awesome. I used ILspy and can see all the code in that static class of the base game, so I can copy and paste it and I only need to modify two or three lines.
But now I want to nuke the games core static class and make mine the only implementation.
I want to force replace that static class at runtime, before the static class is ever called and after loading my mod, how? There must be a way to swap static classes?
I read about creating a proxy DLL that redirects all methods to the old DLL and my method to my DLL but that would require gamers to replace a core game DLL and that is even dirtier than just telling people what my mod does. I am changing thas implementation for this mod, if you dont like don use my mod. That is more reasonable.
I will assume you don't have access to the source and thus can't modify it directly.
You COULD (probably shouldn't) use microsoft fakes since it is mainly for testing. You could create a fakes assembly based on the original author's dll, and override just the type you want. It even supports overriding static classes. Again, I am not saying that you necessarily SHOULD do this, but you COULD.
Here is the page for isolating code under test, it includes an example for shimming a static class (DateTime) https://msdn.microsoft.com/en-us/library/hh549175.aspx
A few options ...
Review how the original developer said to modify the game
You could use something like JustDecompile to get their code.
Use Fakes as suggested above
Create your own assembly that calls into their assembly and hack the IL dynamically
This seems pretty close to this question: Can I redirect .NET method calls to a new method at runtime?
One of the answers to this post suggests looking at a library called Moles which seems to be similar to Detours and may help
Moles allows to replace any .NET method with a delegate. Moles supports static or non-virtual methods

In C#, how to restrict who can call a method at compile time

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

Any way to avoid creating a huge C# COM interface wrapper when only a few methods needed?

Greetings all,
I’m working on a C# program that requires being able to get the index of the hot item in Windows 7 Explorer’s new ItemsView control. Fortunately, Microsoft has provided a way to do this through UI Automation, by querying custom properties of the control.
Unfortunately, the System.Windows.Automation namespace inexplicably does not seem to provide a way to query custom properties! This leaves me with the undesirable position of having to completely ditch the C# Automation namespace and use only the unmanaged COM version. One way to do it would be to put all the Automation code in a separate C++/CLI module and call it from my C# application. However, I would like to avoid this option if possible, as it adds more files to my project, and I’d have to worry about 32/64-bit problems and such.
The other option is to make use of the ComImport attribute to declare the relevant interfaces and do everything through COM-interop. This is what I would like to do. However, the relevant interfaces, such as IUIAutomation and IUIAutomationElement, are FREAKING HUGE. They have hundreds of methods in total, and reference tons and tons of interfaces (which I assume I would have to also declare), almost all of which I will never ever use. I don’t think the UI Automation interfaces are declared in any Type Library either, so I can’t use TLBIMP.
Is there any way I can avoid having to manually translate a bajillion method signatures into C# and instead only declare the ten or so methods I actually need? I see that C# 4.0 added a new “dynamic” type that is supposed to ease COM interop; is that at all relevant to my problem?
Thanks
The most important thing (from the perspective of calling a COM method from C#) is that the methods appear in the interface in the right order. If you're not using a method, you can just declare it as void and nothing bad will happen (unless you actually call it!). This saves you from having to work out the correct signatures and define all the other types, etc. For example,
[ComImport, Guid("30cbe57d-d9d0-452a-ab13-7ac5ac4825ee"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IUIAutomation
{
void CompareElements();
void CompareRuntimeIds();
void GetRootElement();
// 50 or so other methods...
// ... define only the signatures for the ones you actually need
}
The methods should be defined in exactly the same order they appear in UIAutomationClient.h (in the Windows SDK).

How can I scan MSIL code to find certain function calls

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.

Categories