Optional reference in Dot Net - c#

I hope it may be a advanced concept in .Net
My question is
How to setup a program with optional reference?
For example: Consider this case,
I've certain program which is capable exporting data to Excel.
This feature needs reference to Microsoft Office Excel (Some specific version)
Is there any way to write a program which run whether or not Excel installed, but some particular option (like reading or writing Excel) will be done only if Excel installed.
Program should run even when Excel is not installed.
Thanks.

There are two basic approaches.
Assembly.Load allows you to load arbitrary assemblies are runtime, inspect their contents, instantiate objects, call methods and so on. You would normally hide that behind things like an interface, a default implementation, a factory method and so on. Dependency Injection may rely on techniques like this.
You can use the Microsoft Managed Extensibility Framework, which does all this and more. See http://msdn.microsoft.com/en-AU/library/dd460648%28v=vs.110%29.aspx.
Excel is a bit of a special case, because it's accessible through COM automation, which provides some other opportunities and can add some other complications. You can usually build and run the program because the wrapper assemblies will be present, and handle execution failures at run-time if Excel is not.
Whichever way you go there can be quite a bit of code to write. There is not enough detail in the question to say much more, but it's not just a matter of setting an 'optional' flag.

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

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.

Writing COM servers for the windows API in C#, where to begin?

I am trying to write some plugins to work with the Terminal Services Session Broker Plugin Interface. I am very fluent in C# but I have not done any C++ since the late 90's. For the plugin I am writing I plan on communicating with a database and I would prefer to use System.Data.SqlClient to talk to it as I know it's ins and outs fairly well. I have the Windows SDK which has provided my with the .idl file for the interface (tssbx.idl). The SDK also provides a C header file (tssbx.h) and a C source file (tssbx_i.c).
I have never written a COM server before, and I have been having a lot of trouble finding resources on learning how to read a IDL file and turn it in to C#. Everything I find says "Use TlbImport" but that requires things like the block library to be in the IDL which tssbx.idl does not (nor its dependents) implement.
What would be my best option:
Find a tool for C# that is the equivalent to MIDL for parsing a .idl file in to a .cs file.
Learn IDL (I have been having trouble finding good guides to learn it) and write the whole thing in C# by hand.
Write a helper dll using the C files provided and have that call in to my C# dll for my .NET parts.
Re-learn C++, use the provided .h and .c files, and use the CLR to make my .NET calls.
Some other option I have not thought of.
The way to do what you're trying to do is to translate the IDL definitions into C# interfaces, then implement those interfaces as C# classes. You apply the appropriate attributes (mostly ComVisible, ClassInterface, and ProgId) to the classes you want to expose to COM, and use the regasm tool to register your assembly as a COM server.
Translating IDL into C# is actually not that complex; for the most part it maps pretty directly from IDL keywords to C# keywords and/or MarshalAs attributes. I have a series of blog posts on how to do COM interop w/out tlbimp, including one on how to read IDL. I don't know of any tools, specifically, that do a good job of this, but if its part of the Windows SDK you should always check pinvoke.net first in case someone else did it for you.
As far as your other options, 3 and 4 both amount to about the same thing. You cannot call managed code directly from unmanaged code unless it's done via COM Interop or a mixed-mode C++ library. In the first case, you'd still have to solve all of the problems of getting your C# assembly registered with COM for your C dll to call, so you may as well skip the middle-man. For the second, you are basically doing manually the same things that the runtime's interop code does for you, and using a language you're less familiar with to boot, which seems like a net loss to me.
Be aware, though, that loading .NET assemblies into an unmanaged context isn't always possible; for example, managed shell extensions are explicitly not support in Windows 2008. I don't know if the TSSBX interface will allow you to load managed assemblies as COM objects or not, so you'll have to be aware of that possibility. If you can't, then none of your options are going to work, and you'll have to avoid using the .NET Framework at all and use some other database access technology and write the entire project in unmanaged C++.
I am posting this as an answer because it is too long for a comment
From what I gather writing such plugins in .NET might raise problems later on - esp. in a scenario where more than one .NET-based plugin has to be loaded and the two (or more) plugins use different .NET versions (such problems has been expressly mentioned in the context of shell extenstions - I am just taking the reasons from that scenario as a basis for my suspicion...).
As to your option IDL itseld can't implement anything - it is an interface description language.
I would suggest using something similar to option #3 with some modification:
Implement the .NET part as a Windows Service and communicate between the C and the .NET via IPC - I would recommend using shared memory which is extremely fast and well supported with .NET4 .

Terminology for allowing patches/modifications to a C# game

I need to be able to allow mods/patches to a very simple game. Essentially I need to allow a folder full of DLL files to be loaded and have their functions override those of the original application.
I know the basics of a hook system where a line of code can be placed throughout the application source to "bring in" code from outside variables and the likes.
I have tried to search for this, however as I am not sure of the terminology I have ended up sifting through about 30 sites and coming back to gaming websites with instructions on how to specifically mods their games. This information was helpful but I need a little assistance
My question is: Is there an common term for what I am trying to achieve that will assist me in google searches?
You should probably look for .NET plug-in/add-in framework. .NET Fx since 3.5 contains its own add-in framework but that may be overkill for your requirement. As such what you want to achieve is quite simple in .NET - here's the broad outline of it:
Define various interfaces (hooks) that need to be implemented by third party. Package them in a separate dll with documentation.
Create a configuration item (a config entry) that will accept the fully qualified type name implementing the requisite interface.
In your program, load the type using the above config entry. You can use reflection for that (see Activator.CreateInstance). Cast the object to interface and use it.
Third party is supposed to provide implementation of these interfaces and place the dll under application folder. And modify config entry to put the type name.
Not sure, but given .NET context, MEF (Managed Extensible Framework) or System.AddIns could work.

Can you create applications in Excel?

My friend said he was going to create an application inside of Excel. I told him that maybe he meant macros but he seemed convinced he could create a typical CRUD application INSIDE of Excel.
Is this true?
You're both right. You can use VBA inside Excel and some form functionality to create a fully functional CRUD process with a UI inside of Excel, and you could persist that data to your workbook or to some other storage area (text, XML, Access, another DBMS). It would not be a full application, per se, as it is limited to running inside of the Excel app, but it would be something more than a simple macro of "do these pre-defined steps in order."
Sure. Why would you want to?
The short answer is that using VBA, you can create background worker methods that can interface with other Office apps, or with .NET/COM code. However, if you want to add complex business logic to an Excel presentation layer, my first thought would be to create the application in C#, and use the .NET Framework wrappers for Office interop. The first advantage is that you use Excel SOLELY for presentation, supporting an MVC-ish software design. Second, you keep the code where you expect to find it; in code, not embedded in a document.
You might use Excel/VBA because:
You have VBA--a fully-loaded programming language (though the OO needs work).
Scalar functions are overloaded to work with arrays.
A decent IDE and debug facility.
Excel provides a rich event-driven platform and extends VBA's capabilities with spreadsheet behaviour that "just happens" but would take a lot of coding in a conventional language.
Form widgets that you can put anywhere, not just on a form.
Simple but adequate vector graphics.
Charts, charts and more charts--all dynamic.
Automatic persistence or, if it's called for, interfaces to just about every file and database medium, including XML and cloud services.
Relational tables are a native structure.
If it weren't past midnight, I'm sure I could think of some more good reasons, but hey....
Sure you can.... use VBA and populate cells with data from a DB, when the cells change values update the database
But why would you is the bigger question here
It is true. VBA can summon COM, which can do pretty powerful things. I used an excel file for receiving reports built by a macro inside, that searches many remote databases to group and aggregate information. You can modify the registry, make it run programs, make it restart the PC, show messages, create and edit files, make it use Word or Access, call .NET functionality. Anything that doesn't require complex rendering of something.

Categories