c#: why use DLLs? - c#

i'm working on a large c# project,i wonder why people use DLLs in their apps. I know that a dll file ( please correct if i'm wrong) contains some functions, but why don't we put those functions inside our main c# app?
Thanks

Most of it is summed up in the answer to this question, but the basic reasoning is "so you don't have to duplicate code".

Code reuse. Usually dll files contain functions that are useful in more than one app, and to have them in a single compiled file is a lot easier than copying over all that code.

Portability, Reusability, Modularity.
Splitting types and the like into separate assemblies allows you to reuse those types in different projects, maintain those types a modular fashion (e.g. update just one assembly instead of the whole app), and share parts of your code with others.
It also allows you to group common functionality into a single package.

Maintainability. When you need to fix a bug, you can release just the DLL containing the fix, instead of having to re-release the entire application.

This is an interesting question in a modern computing.
Back in the 16bit days DLLs cut down on the amount code in memory.
This was a big issue when 16 meg computers where considered fully loaded.
I find many of the answers interesting as though a DLL is the only way to have a reusable,maintainable and portable library.
Good reasons for dll's are that you want to share code with an external party.
Just as Visual Studio and other library vendors give you dll's this makes there code available to a external consumer. However, at one time they did distribute them in another way.
Patchable, This is true but how often does this really happen. Every company I've worked for has tested products as a unit. I suppose if you need to do incremental patching because of bandwidth or something this would be a reason.
As for all the other reasons including reusable, maintainable, modularity.
I guess most of you don't remember .LIB files which were statically linked libraries.
You can even distribute .LIB files but they have to be introduced at compile time and not runtime. They can help facilitate reusable, maintainable and modularity just like a DLL.
The big difference is that they are linked when the program is compiled not when it is executed.
I'm really beginning to wonder if we shouldn't return to .LIB files for many things and reducing the number of DLL files. Memory is plentiful and there is overhead in load time when you have to load and runtime link a bunch of DLL files.
Sadly, .LIB files are only an option if your a C++ guy. Maybe they will consider them with C# in the future. I"m just not sure the reasons for DLL's still exist in the broad context they are used for today.

In big softwares, you have many teams they work on several different modules of program, and thay can proceed their goals without needing to know what others is doing! So one of the best solutions, is that each team produces own codes in parallel. So,dll comes to scene....

Extensibility - a lot of plugin frameworks use DLLs/Assemblies for plugins.

dll : a dynamic link library :
it is a library.
It contain some functions and data.
Where we use these function?
we use these function and data which are inside the dll,in another application or program.
the most important thing is that dll will not get loaded into memory, when it require , called it is loaded into ram .

One of the best use is, one can integrate many third party functionalities into your application just by referencing the dlls, no need to use every third party tool/application into your system.
For example, you need to send a meeting invite via MS outlook through code, for this simply refer the dlls provided by MS outlook in your application and you can start coding your way to success!

Related

Project can only be used by specified solution [duplicate]

How do I protect the dlls of my project in such a way that they cannot be referenced and used by other people?
Thanks
The short answer is that beyond the obvious things, there is not much you can do.
The obvious things that you might want to consider (roughly in order of increasing difficulty and decreasing plausibility) include:
Static link so there is no DLL to attack.
Strip all symbols.
Use a .DEF file and an import library to have only anonymous exports known only by their export ids.
Keep the DLL in a resource and expose it in the file system (under a suitably obscure name, perhaps even generated at run time) only when running.
Hide all real functions behind a factory method that exchanges a secret (better, proof of knowledge of a secret) for a table of function pointers to the real methods.
Use anti-debugging techniques borrowed from the malware world to prevent reverse engineering. (Note that this will likely get you false positives from AV tools.)
Regardless, a sufficiently determined user can still figure out ways to use it. A decent disassembler will quickly provide all the information needed.
Note that if your DLL is really a COM object, or worse yet a CLR Assembly, then there is a huge amount of runtime type information that you can't strip off without breaking its intended use.
EDIT: Since you've retagged to imply that C# and .NET are the environment rather than a pure Win32 DLL written in C, then I really should revise the above to "You Can't, But..."
There has been a market for obfuscation tools for a long time to deal with environments where delivery of compilable source is mandatory, but you don't want to deliver useful source. There are C# products that play in that market, and it looks like at least one has chimed in.
Because loading an Assembly requires so much effort from the framework, it is likely that there are permission bits that exert some control for honest providers and consumers of Assemblies. I have not seen any discussion of the real security provided by these methods and simply don't know how effective they are against a determined attack.
A lot is going to depend on your use case. If you merely want to prevent casual use, you can probably find a solution that works for you. If you want to protect valuable trade secrets from reverse engineering and reuse, you may not be so happy.
You're facing the same issue as proponents of DRM.
If your program (which you wish to be able to run the DLL) is runnable by some user account, then there is nothing that can stop a sufficiently determined programmer who can log on as that user from isolating the code that performs the decryption and using that to decrypt your DLL and run it.
You can of course make it inconvenient to perform this reverse engineering, and that may well be enough.
Take a look at the StrongNameIdentityPermissionAttribute. It will allow you to declare access to your assembly. Combined with a good code protection tool (like CodeVeil (disclaimer I sell CodeVeil)) you'll be quite happy.
You could embed it into your executable, and extract and loadlibrary at runtime and call into it. Or you could use some kind of shared key to encrypt/decrypt the accompanying file and do the same above.
I'm assuming you've already considered solutions like compiling it in if you really don't want it shared. If someone really wants to get to it though, there are many ways to do it.
Have you tried .Net reactor? I recently came across it. Some people say its great but I am still testing it out.
Well you could mark all of your "public" classes as "internal" or "protected internal" then mark you assemblies with [assembly:InternalsVisibleTo("")] Attribute and no one but the marked assemblies can see the contents.
You may be interested in the following information about Friend assemblies:
http://msdn.microsoft.com/en-us/library/0tke9fxk(VS.80).aspx

Static linking in C#?

The Windows Azure client libraries are very big (several MBs), and I have a fairly small project (on the order of a few hundred KBs) that uses only a few functions from them. Is there a way for me to link in those functions at build time, so that the resultant DLL doesn't get hugely bloated, and I don't have to link the functions in at runtime?
Something like this http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx, but I get the impression that bundles in the whole DLL.
Thanks!
Edit: Because there are external constraints on the size of the final deliverable DLL, inflating it this much is an absolute last resort - the only other option I'm aware of is just to duplicate the code I use verbatim.
In a word: No.
Remember that even though you only use a few functions, there are likely many other function in the library that those functions use, that you don't even know about!
You can't do this, because you don't have access to all the dependencies. Remember also that those dependencies may even reside in another DLL, and you need to include that entire DLL for the same reason.
What you are looking for sounds very like .NET Native.
Unfortunately for you, its only preview and right now works only with Store Apps for devices. Statements like this
We will continue to evolve and improve native compilation for the range of .NET applications
can be found on the internet but nothing specific about web apps\Azure.
Until then, answer is No

Modular System in .NET Able to be Altered at Runtime

Currently I'm working on a .NET hobby project that involves a complex system of objects which work in combination with eachother. However, I encountered a little problem, I am unable to find a mechanism in .NET to support replacing code at runtime, and be able to dispose of the old code, loaded previously. This means replacing a module/object dynamically and almost instantly displaying the changes to the user, for example, when he restarts a procedure, but not the whole program.
I have already taken into account the possibility of having separate AppDomain for each session and loading the necessary assemblies into it but this seems a little bit too expensive. I should also mention that every session benefits from a common base of assemblies, for instance, to connect to a database, so this means loading those classes into every single session. Marshalling data back and forth from the separate AppDomain also represents an additional overhead (could be used when data is sent to the client application through the network, code for this contained in the main AppDomain, which manages the sessions).
Is there a framework or way of replacing/unloading particular parts of code? How is it done in real-world applications? Can there be a workaround? Or have I picked the wrong set of tools?
You need some kind of plugin system with well defined interfaces. Then you load at runtime binaries (your plugin *.dll) and create objects from it and then execute methods on it.
When you create a system where objects from your plugins must be created through your IPluginManager you have no problem with replacing code at runtime. :)
Or
You have something like a folder with *.cs files which will on demand compiled (in memory) and create the objects you want to use from them and call the methods on them.
Which is basically the same like above, without compiling at run time.
From there you can make further improvements.
EDIT:
Like you wrote the only problem without using AppDomain is that once loaded assemblies can't be unloaded. But that's not really a problem.
I don't think you need separate AppDomains: you can dynamically load assemblies within the current AppDomain. And each assembly should probably implement some defined interfaces (depending on your usage). You could use the FileSystemWatcher class, for example, to load/unload assemblies as needed.
See http://msdn.microsoft.com/en-us/library/25y1ya39(v=vs.110).aspx
You can have a look at MEF. It stands for: Managed Extensibility Framework .
Here's another article about it MEF on codeproject.
It is used to load dll's in runtime by composing them. This is what is usually used for plugins or anything else you kinda drop into a folder and expect it to run .
Here's a link to some more tutorials as well: Where can I learn about MEF?
Yes, you're right, it is not possible to simply unload an assembly (only AppDomains). But I think one of the features of ASP.Net vNext is the ability to have just in-memory assemblies and when you simply alter the source code on the drive it gets automatically compiled and loaded. Therefor a mechanism must exist to unload the previous version.
I think they are doing that by simply creating a AppDomain where all assemblies are loaded into again to avoid any cross domain communication. But i don't really know and maybe if you would dig more into the mechanism on how they do this stuff in ASP.NET you maybe find a good solution. More informations about the hot topics from vNext you can maybe also find at Scotts Blog.
Well, I've found 2 solutions that work for me, which I would like to share. The first one is to use CollectibleAssembly and define the types. This is certainly a bit tricky, and a number of restrictions are imposed on this type of dynamic assembies.
The other option is to use a scripting language like IronPython or IronRuby. Also a great feature of the new Roslyn compiler is that it also provides scripting APIs, not previously available in the .NET framework. What's more, the Roslyn scripting languages tend to look very much like their full-blown equivalents (C# or VB). And I've also found a tiny example of its capabilites.

Is it possible to decompile the whole .NET application?

I know that .NET apps are difficult to protect. I use RedGate Reflector and know that generally speaking you can get source code from many .NET dlls.
however my question is - is it actually feasible to decompile the whole application?
I mean - create a workable VS solution so the pirate can just press F5 and get the exactly same result as if the author on his machine?
Reflector have few plugins that allows to dump assembly into code:
http://www.denisbauer.com/home/reflectorfiledisassembler
http://filegenreflector.codeplex.com/
But I'm not sure that can create a project file.
For a small application, it is both possible AND feasible. You have to decompile the classes one by one and copy/paste the code into Visual Studio.
For a large application, while possible, it's not really feasible since the copy/paste process becomes extremely tedious.
It really depends on what kind of code you are writing. If you use a lot of the new features in C# 3 and above like lambda expressions, automatic properties, and yield, the decompiled source code is not runnable and requires quite a bit of work to get it to compile.
Even without those features though, I have usually experienced at least some problems compiling the decompiled source code of a full winforms application.
There are many obfuscators these days that protect your .NET applications from decompilation. One such obfuscator is http://www.red-gate.com/products/smartassembly/index.htm . They try to make your well structured .NET IL code into spegatti code (which still works) that decompilers cannot generate original code. It's not like 100% sure piraters cannot get the recompilable code but it will not be easy for them to decompile when using obfuscator.
I don't think there's anything that fully automates this for an app made up of multiple assemblies, but I can say that it's really not that hard to stitch the pieces together into a solution yourself. Perhaps a bit tedious for a large app, but if you really want to it's certainly doable.
Fortunately, I don't worry about it that much.
Yes, you simply Export from Reflector and get a complete runnable Project for your assembly.
I've done it a couple of times.
Usually, I have to migrate the project to my version of VS and some times it requires some minor fixes, but in general it works.

When to create your own dll what should be in it

I as of yet, have not had a need to create a dll in .NET as my programs tend to be distinct from one another (and I haven't programmed for too long). However I am starting to gather a library of regularly used methods now which tend to have copies in lots of my programs (or similar methods that could be made more generic).
As I understand it a dll should be created to share common methods between programs.
So I can put my methods in the dll, what about things like custom dialog boxes and common forms. I currently have a custom error form and a print preview dialog which are used in almost all my programs. Is it good practice to put these in a dll?
"Good practice" in this case really relies on how much code-duplication you're cutting down on. If these dialogues are used throughout a lot of your programs and they take up a lot of code, then yes, it's probably a good idea to move them to a shared space.
But don't be tempted to throw everything in there. You'll find yourself having to override it and by that point you're probably writing more code than you were before. Keep things simple. Keep them generic. Keep them useful.
Before you start, though, be aware that you are creating a dependency tree. If you update your library chances are you'll have to put in some time maintaining your apps that use it... But this is no different from using a third-party lib.
To create a new dll, you just add new project (library) to your solution, and add it as a project reference to your main programme.
It is possible to put anything you want to this project. All dialog boxes, user controls, etc. are just classes, so you can share them as easily as any other class. I think it is good practise to share as much as possible.
Sure why not?
What you're building here is actually a small framework, pretty much like the .Net framework itself. Everything that you think is common between your applications can be put in the assemblies: forms, methods, business logic, exceptions, common data access.
When your framework grows you might want to split up that common DLL. For example if you have common forms in a DLL and you also develop batch applications then they don't need to reference to the DLL containing the WinForms specific classes.
Alternatively you can put the source files for these methods in a common place and just add them as links when you include them in your project/solution.

Categories