Can a certain piece of code be executed with a certain dll? - c#

I have an issue where Newtonsoft.Json is loaded twice in my solution, with two different versions. This is because I am creating an Add-In in Revit, which loads by default version 9.0.0 of Newtonsoft.
The idea is that, when (de)serializing, the operation works well when I use version 11.0.0, but doesn't if I use version 12.0.0 - which I actually want to use. Hence, the option of downgrading just to make the deserialization work is excluded for now.
What I am wondering is; is there any possibility that I could execute version 11.0.0 only on a certain portion of the code? For example, something like this:
execute Newtonsoft.Json.dll version 11.0.0
{
var model = JsonConvert.Deserialize<ModelType>(json);
}
// the rest works with version 12.0.0
While the problem might not be this one, I am still curious if this is possible to achieve. Basically, I want a certain piece of code to be executed using a certain module, except for the one that is already referenced.

Related

Umbraco 9 - How to get up and running with Examine

Is Examine up and running yet for Umbraco 9? If so does anyone have any example code so I can try and get up and running and test it?
I am looking for the equivalent of how we used to do it for Umbraco 8.
So something similar to the below. Adding a custom field into the search index etc.
The Composer/Component way works really well for packages because you can register it without having to have the end-user change their Startup.cs file to call your methods. But in my own project, I'd just add calls to Startup.cs.
That said, I updated the Our.Umbraco.GraphQL package last week, and while it doesn't do custom indexes, it does query Examine. I didn't find I needed to change much of anything except perhaps some namespace references. I did have to update the maxResults parameter to instead pass in the ExamineOptions class with skip/take, as Stuart mentions at https://our.umbraco.com/forum/umbraco-9/106215-examine-skiptake, but otherwise, the same v8 code seemed to work fine in v9.

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.

How to handle your code that later versions of the framework include?

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.

c# check if library/namespace/class exists (at compile time)

I've written some code in c# that uses a library, but I want to share it and want it to work regardless of whether that library exists,
basically I want to check in my code whether the library exists, and if it doesn't, I use alternate code to do what the library was supposed to do.
So how would you do that?
I thought maybe I could use Preprocessor Directives, but to be honest I have little experience with these and can't seem to find how to this.
EDIT :
Just found out a similar question had already been asked:
Checking for the existence a reference/type at compile time in .NET
(I had actually searched before posting, but somehow missed this)
But there doesn't seem to be a satisfying answer.
Is there really no way to do this?
Edit2 :
Sorry for not specifying this sooner,
but the code I wrote is for usage in a Unity3D project, it's a bunch of scripts basically.
Let's assume your project is called A:
Create a new project, B, and then add the sources files from A to B (see http://blogs.msdn.com/b/saraford/archive/2008/11/26/did-you-know-how-to-add-a-linked-item-to-a-project-365.aspx) for details of how to do this.
In project A's properties, under Build add a Conditional compilation symbol, eg USE_LIBRARY.
For each source file that uses the library, modify the using statements to something like:
#if USE_LIBRARY
using Lib.Xxx
#else
using DummyLib.Xxx
#endif
Then create DummyLib with the alternative code.
That way A.dll will be dependent on the library and B.dll won't be. You can then distribute B.dll without the library.

Is there a good reason for preferring reflection over reference?

Going over some legacy code, I ran into piece of code that was using reflection for loading some dll's that their source code was available (they were another project in the solution).
I was cracking my skull trying to figure out why it was done this way (naturally the code was not documented...).
My question is, can you think about any good reason for preferring to load an assembly via reflection rather than referencing it?
Yes, if you have a dynamic module system, where different DLLs should be loaded depending on conditions at runtime. We do this where I work; we do a license check for different optional modules that may be loaded into our system, and then only load the DLLs associated with each module if the license checks out. This prevents code that should never be executed from being loaded, which can both improve performance slightly and prevent bugs.
Dynamically loading DLLs may also allow you to drastically change functionality without changing any source code. The main assembly may for instance set in motion a discovery process where it finds all classes that implement some interface, and chooses which one to use depending on some runtime criterion.
These days you'll typically want to use MEF for this kind of task, but that's only been around since .NET 4.0, so there are probably many codebases out there that do it manually. (I don't know much about MEF. Maybe you have to do this part manually there as well.)
But anyway, the answer to your question is that there certainly are good reasons to dynamically load DLLs using reflection. Whether it applies in your case is impossible to say without more details.
Without knowing you specific project, noone here can tell you why it was done that way in your case.
But the general reasons are:
updateability: You can simply recompile and replace the updated libary instead of having to recompile and replace the whole application.
cooperation: if the interface is clear, that way multiple teams can work together. one for the main application and others for the dlls
reusability: sometimes you need the same functionality in multiple projects, so the same dll can be used again and again
extensability: in some cases you want to be able to later extend your program with plugins that where not present at shipment time. This can be realized using dlls.
I hope this helps you understand some of your setup..
Reason for loading an assembly via reflection rather than referencing it?
Let us consider a scenario, where there are three classes with method DoWork() this method returns string, you are accessing it by checking the condition (strong type).
Now you have two more classes in two different DLL's how would you cope up the change?
1)You can add reference of new DLL's , change the conditional check and make it work.
2)You can use reflection , pass on condition and assembly name at run time, this allows you to add any number of functionality at runttime without any change of code in primary appliation.

Categories