I want to separate platform-independent logic of my C# program into a shared project. Now I would like to hide repositories, service classes and such from my platform-specific projects. What access modifier can I use? internal doesn't seem to work, as they are compiled into the same executable (I think) and I don't want to go tag all my classes with InternalsVisibleToAttribute.
Is there a way to make classes in my shared project invisible to my platform-specific code?
There's only one place where you need to know the real type you're trying to instance - the platform provider. Everyone else should just use the interfaces that are platform-invariant.
All the platform-specific implementations can then be private or internal for all you care - you just need to ensure the provider has access. Your application will use the platform-specific provider to get the platform-specific instances, while only ever using the platform-invariant interfaces.
As for "being compiled into a single executable", that's not really important. Most likely you care entirely about compile-time checking, and that's still present regardless of how the final executable is packaged. There's some restrictions on reflection in a partial trust environment, but by that point you shouldn't care - you're only in it for the compile checks, not the runtime safety.
No, there is no such feature in C#. If you consider marking every other project with InternalsVisibleToAttribute an option, that would do the trick.
If possible, you could split off those other files (repositories, service files) to another assembly, which is not included in your shared project.
Related
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
i joined a new project where they use c#.
I noticed that several dll's were being add in the references
From my knowledge and the e-learning that i have done, after building a class(which has some Methods & data), a DLL is generated.
Now in a new project, the class that just got converted into a DLL is added as a reference so that the functions defined in it could be called.
So, now my question is:
1) what is the need for converting the class file into a DLL file. Even it were a Class file, I could still be calling the functions defined in it by adding its namespace at the top of the code
2) If After adding the reference of the DLL , I deleted the entire contents of the project, leaving only the dll untouched(and in the same place), would the class using this dll still work
Separating your code into different projects (each of which will create a separate assembly) has various benefits:
It makes the structure of your code clear. For example, it can separate your storage layer from your business logic, and also from your user interface.
It allows reuse: two different user interfaces can refer to the same assembly containing the business logic, for example.
It allows greater encapsulation: classes which are only needed within their own assemblies can be declared as internal (which is the default for top-level classes in C# anyway) which means code in other assemblies won't even know about them. If all your code is in a single assembly, all those classes will "know about" each other.
Now choosing just how many projects to have is a balancing act - I've certainly seen applications where this has gone much too far, with lots of assemblies containing just a single class. If you have a large number of assemblies, that becomes a headache in terms of project and reference management. However, having too few assemblies makes it harder to reuse that code cleanly.
In addition to Jon Skeets answer, I'd like to add "updateability" as well. For me, this has two benefits
one is that the build time becomes smaller if only one project needs to be rebuilt
and second, pushing to "release" could be limited to a few dlls instead of one major .exe.
The first might not be a big deal in C# since projects build pretty fast, but for instance switching to C++ would be a big impact, since C++ code take a long time to compile.
The benefit of Separating is that it lets you change the internal implementation without breaking client code. It doesn't protect you if you decide that you need to change the interface to your code, but that's a different matter.
they can reuse their code. but if they use classes every time they need to implement these classes ( in the best way copy and paste all codes )
when they use dlls in instead of classes they can update all project easily by just Update one or more dll although if you use class in multiple projects you suould modify all classes in all projects.
I might add that a class is a language construct while an assembly is a deployment package.
Already in UML those are two totally different things.
http://en.wikipedia.org/wiki/Package_(UML)
When approaching the new idea of subdividing a solution, projects may be seen as "places" in which to put namespaces (i.e. folders) and classes (i.e. files).
It will take some time until you realize that a project best fits the concept of stratum (or layer) which is an architectural separation of a system.
When stratifying a system, you'll realize that the most crucial problem to tackle are the dependencies between strata (which would be the references to projects or dlls).
There cannot be loops but more important, you should study OCP (Open-Closed principle) and ISP (Interface Segregation Principle) and DIP (Dependency Inversion Principle) of SOLID:
http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
At that point a new question will emerge. How can you know which classes depend on each other or do not? You may draw class diagrams, but there is a conceptual approach to the problem. Over the years it becomes a "practice" of designing systems. The concepts are described for educational purposes in GRASP:
http://en.wikipedia.org/wiki/GRASP_(object-oriented_design)
The most important parts of GRASP for stratification are "Low Coupling" and "High Cohesion". In other words, you should batch functionally very similar classes in a stratum and separate through the stratification classes that functionally are not very much related to each other.
Okay, I have a solution I am working on that has 4 different projects in it. One of my projects (a console application) is trying to make reference to some of the classes defined in another project (a library); the only problem is, those called are defined as Internal in the library.
How can I use these Internal classes in other assemblies/projects in the same solution? I added references to the library, but that did not help. It is saying that the protection level is too high (because it is internal, it is only available in that assembly).
You generally shouldn't access something that's internal. That defeats the purpose of declaring it so in the first place. If, however, you do need to...
If you can change the assembly with internal things, either:
Make the classes public, or
Use the InternalsVisibleToAttribute to expose it to just the assemblies you want to.
If you cannot change it, or decide not to, then you can use reflection to access the internal classes. For some portions of what you then do with the class, you should be able to use the dynamic keyword to make access easier and faster than with reflection.
You must use reflection to access the internal classes in other assemblies, but it will be significantly slower and not generally optimizable by the compiler. It's also somewhat complicated.
It is recommended that you expose a public class that wraps your internal classes and methods from the other assembly, or simply switch the internal classes in the other assembly over to public.
I want to implement a plug-in system in my .net application, without the use of MEF.
My application loads and creates instances of types, that are contained in the DLLs.
There is an interface (IPluginContract) that the main application assembly uses to load dll types, and this very same interface is used by the dll projects (the plug-ins) to implement it.
So different projects need access to the same interface.
I can realize this requirement by pushing the interface class into a separate Class Library, that both main app and the plug-ins will reference.
Is it a correct way to work around the described problem?
Yes, pushing your interfaces out into a shared library is a preferred solution. You then only need to distribute this library to plugin developers, which could be considered as lightweight, but the plugin will be coupled to an exact version of the interface.
Another solution is a convention based solution, where plugin writers have types that "conform" to an interface e.g. have appropriate methods on a class which they can point to via a config file. You can then use reflection, IL generation, etc, to wire this up to a concrete internal interface\proxy. The benefit here is that plugins are then not hard-wired to a specific interface version, so there is more flexibility in versioning.
You could also consider versioning by maintaining all versions of your interface e.g. IPlugin_1, IPlugin_2, etc. It's then up to plugin writers to implement whichever version, and for you to be able to handle each version.
We have successfully taken two different approaches to this issue depending on the circumstances at the time (time to market, implementation difficulty, internals exposure concerns, etc):
1) Move the interface into its own DLL. This works well if the plugins don't need any other support objects/functions/data embedded in your main application DLL or if you don't want to expose public members in your main DLL to plugin writers.
2) Leave the interface in the main DLL. We have primarily used this when the refactoring cost to move the interface and associated classes was too high or when the plugins were completely self-contained (i.e. we author them for customers).
I'm interested in creating a desktop application composed of modules such that the source code to those modules is embedded in the application itself, allowing the user to edit the application as they are running it and have the updated modules put into use without restarting the application. Can anyone suggest a good architecture for this?
I'm looking to use Microsoft.Net and C# for this. DLR is not an option.
Thanks!
It's not easy to suggest a good architecture for this in a short posting.
At first, i'd define a contract (an Interface) every module the user writes/modifies must implement. It should contain at least an Execute method.
Then I'd create a Wrapper-Class for these modules which:
loads the source code from a file
The wrapper compiles the file and also makes sure it implements the contract
Contains an indicator of whether the file could be compiled sucessfully
It should also implement the contract, for easy calling and handling
Then I'd have some kind of shell which contains a collection of all the module-wrappers. Any wrapper that sucessfully compiled would then let the Shell call the Execute method of the module interface.
When it comes to compiling and executing code on the fly, this link should provide all the information you need:
http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
Well, a dynamic language certainly would have been the best fit...
You can use the types in the System.Reflection.Emit namespace to dynamically create assemblies.
However, it's going to be really painful because you'd need to load those dynamic assemblies into custom AppDomains because otherwise you'll not be able to unload them again.
This again means that you must address marshalling and assembly resolution issues related to cross-AppDomain communication.
What you are probably looking for is the concept of Dependency Injection.
Dependency Injection means that instead of having module X use module Y directly, module X only relies on an interface, and the application tells module X which implementation should use for it, e.g. using module Y.
There are several ways of implementing Dependency Injection. One is to have references to the interfaces in each of your modules, and explicitly let the application configure each of its modules with the right implementation of the interface.
The second wahy of implementing it (and probably the most useful in your case) is by using a central registry. Define all the interfaces that you want to have in your application. These are the interface for which you want to dynamically change the implementation. Then define identifications for these interfaces. These could be strings or integers or GUID's.
Then make a map in your application that maps the identifications to the interfaces, and fill the map with the correct implementations of the interfaces. In a C++ application (I'm not very skilled in C# yet) this could work like this:
std::map<std::string,IInterface> appInterfaces;
appInterfaces["database"] = new OracleDatabaseModule();
appInterfaces["userinterface"] = new VistaStyleUserInterface();
Make all modules go to this central registry whenever they want to use one of the modules. Make sure they don't access the modules directly, but they only pass via the registry. E.g.
MyModule::someMethod()
{
IDatabaseInterface *dbInterface = dynamic_cast<IDatabaseInterface *>(appInterfaces["database"]);
dbInterface->executeQuery(...);
}
If you now want to change the implementation for an interface in the application, you can simply change the entry in the registry, like this:
IInterface *iface = appInterfaces["database"];
if (iface) delete iface;
appInterface["database"] = new SqlServerDatabaseInterface();