I'm looking for a way to detect broken dependencies before or during app startup, but after compilation.
Suppose MyApplication has a code path that makes a call to Dependency.Foo(), which lives in dependency.dll.
Now suppose that I delete Foo() and deploy the updated dependency.dll without recompiling MyApplication.
MyApplication will start up and work fine until it hits a code path that wants to call Dependency.Foo(). Then it blows up with a MethodNotFoundException.
Is there a way I can detect the broken dependency and make MyApplication fail fast?
I'm thinking of something that would scan the dlls in the bin folder and validate the calls they make to other managed dlls. A coworker mentioned this is easy to do in the java world, but I have no idea what he was talking about...
This feels like a crazy suggestion, but you could look at using libcheck and ship a 'supported' store file for a given version of MyApplication. Then you can validate (not sure if this can be done at runtime) and compare current store with supported store and any API breaks can be reported.
Really, the solution is to control versions via automated builds and quality gateways when shipping the software.
But as #SimonC says, cecil can work too.
You could use reflection to determine if Dependency.Foo exists as MyApplication is loading.
Something along the lines of:
if (typeof(Dependency).GetMethod("Foo") == null)
{
//Fail fast, Dependency.Foo could not be found!
}
The same idea also works for fields and properties, or more generally, for any class member at all.
if (typeof(Dependency).GetMember("Bar").Length == 0)
{
//Fail fast, Dependency.Bar could not be found!
}
For more information:
System.Type on MSDN
If you are developing your own add-in architecture, you will have to follow the other answers. But if you plan to use something more reliable, please consider what Microsoft ships with .NET 4, called Managed Extensibility Framework,
http://msdn.microsoft.com/en-us/magazine/ee291628.aspx
It is a general approach to design add-in contracts and allows you to handle different versions of contracts safely.
Related
Sounds like a dumb question I know, but bear with me :-) I'm currently creating a PoSh module which contains a few custom commands. I had already written a PoSh Advanced Module previously to do what I want to do, but I've decided it's time to take the plunge and learn C# !
One of my commands needs to create an instance of a class which is contained in a third party SDK assembly. That assembly is not contained in the GAC. In my PoSh Advanced Function previously, I would query a registry key to confirm that the SDK was installed (and get the path to it), then I would use System.Reflection.Assembly.LoadFile to load the assembly.
In my C# version, my plan was to do something similar. I've managed to query the registry, confirm that the assembly exists etc and even load it. However, because the assembly isn't referenced in Visual Studio, it just throws loads of intellisense errors when I try to instantiate a class from that assembly. I initially suspected I might need to use something from the Activator class to get around this, but I've been through all the methods there and couldn't find anything that might help.
After a bit more pondering, I wondered if perhaps my approach is wrong, and maybe I shouldn't be doing the "manual" loading but instead allow .net handle all that for me, eg by adding a reference to the assembly. In that case however, how do I reference an assembly in VS without knowing where (or even if) it will be installed on the target/invoking machine ?
Or, if my original approach is correct, how do instantiate the class "manually" (or otherwise) without VS being so unhappy. I did consider adding a "temporary" reference to the assembly on my machine, but I think I'd have to remove that again before doing the retail build. And I'd also have to add temporary using directives I guess.
I have googled this quite a bit, but haven't found anything that might help me at all. So I'd really appreciate any guidance anybody can provide. Maybe I should be looking at something else entirely, like App Domains ?
Thanks in advance
After loading assembly use CreateInstance method and store result in dynamic type variable:
dynamic test = assembly.CreateInstance("Full.Type.Name");
You'll not get intellisense, but compiler will assume that this variable supports any operation. Beware, invalid operations will result in errors only at runtime.
I have to work with an old version of Mono in Unity projects. I find myself recreating some classes and extension methods that exist in later versions of .NET. Should I be marking these with an attribute that will make it easy to take them out at a later point, just wait for the inevitable errors, and delete the duplicate code, or take some other approach I'm not familiar with yet? If the attribute route is the way to go, is there already an appropriate attribute created for this kind of thing?
Here's what I'd like:
[PresentInDotNET(3.5)]
I fill in the version and get alerted when the framework is at that level or higher.
Split them off to a separate assembly, and change the set of assemblies that make up the final delivery based on the .NET version. You need to rebuild your main assembly to refer to the correct assemblies (depending on whether Foo is in MySystem or System), but as long as you keep namespaces identical, that's all. If you are not even interested in keeping compatibility with older versions, you can simply delete classes from this assembly as they become available.
Alternatively, if the classes/extension methods you are recreating are not interesting (in the sense that you gain nothing by having .NET supply them for you), simply put them in their separate namespace and accept that you are duplicating code already present in newer versions. It doesn't matter a whole lot which assembly gets the job done, after all, as long as it happens.
Whatever you do, try to avoid going the route of #ifdefs, runtime discovery, and other conditional code, as this is much harder to maintain.
How about adding "// TODO" comments for places like this? Visual Studio will display these in the Task window and you can get at them pretty easily.
I'm using an external library and I want to make sure I never call some particular functions in the library. I don't have the source code for that library so I'd like to make sure that at compile time it throws an error if I ever accidentally (or one of my developers) ever use that function. Is there a way to do this?
You can't do this easily. You could mark the method as obsolete, but of course that requires access to the external library source code, at which point you could also just remove the methods.
The next best thing I can come up with is to build a facade around the library object:
public class LibraryFacade
{
//All the library methods as pass-through methods
//Except the bad ones!
}
Of course, your developers have to actually use the facade for this to help. If you don't trust them at all, you could get new developers, or put the facade in a separate assembly so the client code doesn't have direct access to the external library.
Obviously thats a lot of work for this kind of feature, but it will get you where you are trying to go.
If you have plenty of extra time you can make a clone of the external assembly and link against your slimmed down version with identical method signatures instead of real one and replace with real assembly at run-time/post compile. Easy for non-signed assemblies, I think you can even do that if other assembly is signed by using delay-sign feature.
Benefits: complete intellisence/refactoring support, perfect build errors.
Drawbacks: picking right subset of methods may be major pain if library uses a lot of dependencies, getting 100% parity may be hard.
I am not sure the best way to explain this so please leave comments if you do not understand.
Basically, I have a few libraries for various tasks to work with different programs - notification is just one example.
Now, I am building a new program, and I want it to be as lightweight as possible. Whilst I would like to include my notification engine, I do not think many people would actually use its functionality, so, I would rather not include it by default - just as an optional download.
How would I program this?
With unmanaged Dlls and P/Invoke, I can basically wrap the whole lot in a try/catch loop, but I am not sure about the managed version.
So far, the best way I can think of is to check if the DLL file exists upon startup then set a field bool or similar, and every time I would like a notification to be fired, I could do an if/check the bool and fire...
I have seen from the debug window that DLL files are only loaded as they are needed. The program would obviously compile as all components will be visible to the project, but would it run on the end users machine without the DLL?
More importantly, is there a better way of doing this?
I would ideally like to have nothing about notifications in my application and somehow have it so that if the DLL file is downloaded, it adds this functionality externally. It really is not the end of the world to have a few extra bytes calling notification("blabla"); (or similar), but I am thinking a lot further down the line when I have much bigger intentions and just want to know best practices for this sort of thing.
I do not think many people would
actually use its functionality, so, I
would rather not include it by default
- just as an optional download.
Such things are typically described as plugins (or add-ons, or extensions).
Since .NET 4, the standard way to do that is with the Managed Exensibility Framework. It is included in the framework as the System.ComponentModel.Composition assembly and namespace. To get started, it is best to read the MSDN article and the MEF programming guide.
You can use System.Reflection.Assembly and its LoadFile method to dynamically load a DLL. You can then use the methods in Assembly to get Classes, types etc. embedded in the DLL and call them.
If you just check if the .dll exists or load every .dll in a plugin directory you can get what you want.
To your question if the program will run on the user's machine without the dlls already being present - yes , the program would run. As long as you dont do something that needs the runtime to load the classes defined in the dll , it does not matter if the dll is missing from the machine. To the aspect you are looking for regarding loading the dll on demand , I think you are well of using some sort of a configuration and Reflection ( either directly or by some IoC strategy. )
Try to load the plugin at startup.
Instead of checking a boolean all over the place, you can create a delegate field for the notification and initialize it to a no-op function. If loading the plugin succeeds, assign the delegate to the plugin implementation. Then everywhere the event occurs can just call the delegate, without worrying about the fact that the plugin might or might not be available.
Ok, so I was wondering how one would go about creating a program, that creates a second program(Like how most compression programs can create self extracting self excutables, but that's not what I need).
Say I have 2 programs. Each one containing a class. The one program I would use to modify and fill the class with data. The second file would be a program that also had the class, but empty, and it's only purpose is to access this data in a specific way. I don't know, I'm thinking if the specific class were serialized and then "injected" into the second file. But how would one be able to do that? I've found modifying files that were already compiled fascinating, though I've never been able to make changes that didn't cause errors.
That's just a thought. I don't know what the solution would be, that's just something that crossed my mind.
I'd prefer some information in say c or c++ that's cross-platform. The only other language I'd accept is c#.
also
I'm not looking for 3-rd party library's, or things such as Boost. If anything a shove in the right direction could be all I need.
++also
I don't want to be using a compiler.
Jalf actually read what I wrote
That's exactly what I would like to know how to do. I think that's fairly obvious by what I asked above. I said nothing about compiling the files, or scripting.
QUOTE "I've found modifying files that were already compiled fascinating"
Please read and understand the question first before posting.
thanks.
Building an executable from scratch is hard. First, you'd need to generate machine code for what the program would do, and then you need to encapsulate such code in an executable file. That's overkill unless you want to write a compiler for a language.
These utilities that generate a self-extracting executable don't really make the executable from scratch. They have the executable pre-generated, and the data file is just appended to the end of it. Since the Windows executable format allows you to put data at the end of the file, caring only for the "real executable" part (the exe header tells how big it is - the rest is ignored).
For instance, try to generate two self-extracting zip, and do a binary diff on them. You'll see their first X KBytes are exactly the same, what changes is the rest, which is not an executable at all, it's just data. When the file is executed, it looks what is found at the end of the file (the data) and unzips it.
Take a look at the wikipedia entry, go to the external links section to dig deeper:
http://en.wikipedia.org/wiki/Portable_Executable
I only mentioned Windows here but the same principles apply to Linux. But don't expect to have cross-platform results, you'll have to re-implement it to each platform. I couldn't imagine something that's more platform-dependent than the executable file. Even if you use C# you'll have to generate the native stub, which is different if you're running on Windows (under .net) or Linux (under Mono).
Invoke a compiler with data generated by your program (write temp files to disk if necessary) and or stored on disk?
Or is the question about the details of writing the local executable format?
Unfortunately with compiled languages such as C, C++, Java, or C#, you won't be able to just ``run'' new code at runtime, like you can do in interpreted languages like PHP, Perl, and ECMAscript. The code has to be compiled first, and for that you will need a compiler. There's no getting around this.
If you need to duplicate the save/restore functionality between two separate EXEs, then your best bet is to create a static library shared between the two programs, or a DLL shared between the two programs. That way, you write that code once and it's able to be used by as many programs as you want.
On the other hand, if you're really running into a scenario like this, my main question is, What are you trying to accomplish with this? Even in languages that support things like eval(), self modifying code is usually some of the nastiest and bug-riddled stuff you're going to find. It's worse even than a program written completely with GOTOs. There are uses for self modifying code like this, but 99% of the time it's the wrong approach to take.
Hope that helps :)
I had the same problem and I think that this solves all problems.
You can put there whatever code and if correct it will produce at runtime second executable.
--ADD--
So in short you have some code which you can hard-code and store in the code of your 1st exe file or let outside it. Then you run it and you compile the aforementioned code. If eveything is ok you will get a second executable runtime- compiled. All this without any external lib!!
Ok, so I was wondering how one would
go about creating a program, that
creates a second program
You can look at CodeDom. Here is a tutorial
Have you considered embedding a scripting language such as Lua or Python into your app? This will give you the ability to dynamically generate and execute code at runtime.
From wikipedia:
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution. These behaviors can be emulated in nearly any language of sufficient complexity, but dynamic languages provide direct tools to make use of them.
Depending on what you call a program, Self-modifying code may do the trick.
Basically, you write code somewhere in memory as if it were plain data, and you call it.
Usually it's a bad idea, but it's quite fun.