How to load a class from a .cs file - c#

Is it possible to load a class and create Instance of it from It's .cs file?
I want to open a custom class in a .cs file and create instance of it in my application
thanks

in theory yes - it mainly depends on whether you have all dependencies available...
IF so you can use the built-in CSharpCodeProvider to compile the .cs- file to an assembly (can be purely in-memory if need be) and then use Reflection to create an instance/use a class from that assembly...
Since don't provide much detail I would suggest to checkout these links and come back with detail questions if some arrise:
http://support.microsoft.com/kb/304655/en-us
http://www.codeproject.com/KB/cs/codecompilation.aspx
http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Compile-C-or-VB-source-code-run-time.html
http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
http://www.csharp-examples.net/reflection-examples/
http://csharp.net-tutorials.com/reflection/introduction/
http://www.codeproject.com/KB/cs/C__Reflection_Tutorial.aspx
http://www.dotnetperls.com/reflection-field
C# Reflection: How to get class reference from string?
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.aspx
http://msdn.microsoft.com/en-us/library/system.type.aspx

You can use Microsoft.CSharp.CSharpCodeProvider and System.CodeDom to execute code at runtime, there is an article about this code project here and here

Related

What options do I have to dynamically access a class in another assembly?

I have a ASP.NET MVC application and a plugin that needs to write to the web.config file. For various reasons, I've found that the most appropriate way to do this is during compilation using MSBuild configuration, so I have created an executable distributed with my plugin to be called here with appropriate parameters for resolving consumer-application dependencies like the path to the config file.
The plugin is configurable, and the definition for this must be in the consumer application in a specific class.
Now the plugin-executable has to be able to read this class, but we can not have any hard-coded dependencies since the plugin should be distributable and used in many different applications.
I have found this answer here on SO about dynamically loading/unloading DLLs, and my question is if this is the approach to use, while passing in the relevant parameters as arguments to the exe, or do I have any other options?
The answer is Yes but you can do it in two different ways.
If you want to unload the class yes you need to create a new AppDomain, use it and unload it in the end, to do this you need a class that implements MarshalByRefObject it's much more complicated.
If the class can live during the lifetime of the client application you just need to load your plugin to the current AppDomain.
AppDomain.CurrentDomain.CreateInstanceAndUnwrap(assemblyName, typeName);
I strongly recommend that the instance you are loading implements a specific Interface so you can inspect a folder for DLL's like this
var ass = Assembly.LoadFrom(path);
ass.DefinedTypes.Where(t => t.ImplementedInterfaces
.Any(i => i.AssemblyQualifiedName ==
typeof(<Defined Interface>).AssemblyQualifiedName))
this will return a list of types that implement your interface so you just need to use the above code to create one instance.
I think that to work with msbuild you need to take the first approach and do all the load unload and usage inside of the class that implements MarshalByRefObject don't quote me on this one.

How to read properties of a class that is not included in the current project?

I have some classes in a folder.Now in another program I want to read their properties.I can read them as a text but I do not know how to treat with them as a class to write object.GetType().GetProperties() for them.
How to do this?
How to read the properties of an existing class that is not included in the current project?
Given that what you want is a custom code generator, I think it would be a good idea to look over T4 templates and see if you can use them for you purpose.
http://msdn.microsoft.com/en-us/library/ee844259.aspx
Another solution would be to parse those files yourself and generate the code.(Regex or plain text operations)

Is it possible to obtain a type's summary using reflection?

you know how when you go to object browser and you select a type there is a summary below its name?
For example:
public sealed class Activator
Member of System
Summary:
Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited.
Is it possible to obtain that information using Reflection? If so, how is it done? If that's not possible, where is that data stored?
The reason the comments can’t be discovered by reflection alone is because they are not included in the .NET assemblies (.EXE or .DLL files), but are conventionally included as .XML files to accompany the assembly files.
DocsByReflection can be used to get the summary. Refer to the link here for details.
And the answer is:
http://jimblackler.net/blog/?p=49
Looks like it is possible.

Best way to get an accessable class in all of my projects

I need to declare an attribute for coverage exclusion in my code, the issue is that i have a project group and i wish to create it somewhere where i can access it from all projects when i need it, right now i have it outside of the namespaces so it would be easier to use, and its declared in each project like:
public class CoverageExcludeAttribute : Attribute
{
}
is there any better way to achieve this goal in a way it could be access anywhere in my project group and declared only once, without having to add its namespace (e.g by using the global namespace) to each file i use the attribute in?
Thank you
While I actually agree with P.Brian.Mackey, I think the only way to do it is exactly as DjKraze said:
Create a new micro-project of type ClassLibrary, add a single .cs file with your Coverage(..) class and ensure that class is inside no namespaces block. Then build it and for each one of the other projects do a Add-Reference to that micro-project you just created.. That way it will surely work, and you will have a handy place to put any further 'common code' to be available everywhere.
However, each project will have to be updated with the reference. This is the minimum requirement - all in all, if you want to use anything instead of copying, it must be referred..
Sorry, almost no other options for such thing!
The other way is to .. ugh, copy. You can easily set up a simple pre-build script that will copy given .cs file to each one of your projects, but "adding" the file to the .csproj's build list is a bit harder, still possible with use of some Ruby or Python or friends...
Hm.. saying that, It may be possible to write a pre-build script to inject a reference to the micro-project automatically.. But I wont know if this is worth doing. Do you have more than 50-100 projects? Else, probably it's not worth..
This only applies to VS2010 and above
If you want some source code defined in each of your projects, but without a project reference, take a look at some of the functionality provided by NuGet, especially Source Code Transformations. These allow the addition of some source code to the project when you add the NuGet package to the project.
You can use Dependency Injection
http://en.wikipedia.org/wiki/Dependency_injection
The most popular are: Microsoft Unity, Ninject, NHibernate, StructureMap, Autofac.
Good luck!

Equivalent to PHP's include in C#

What is the equivalent command to PHP's include() in C# ?
For example, PHP's include is used as so : include("ex.php");
Can I do the same in C#?
If you mean in ASP.Net using C# you can create a user control (.ascx) and add it in your .aspx page.
If you are doing MVC you can create a partial view.
The closest thing I can think of would be after creating an ascx user control named "MyUserControl"
in your page_load or pre_render :
MyUserControl cont = new MyUserControl();
this.Controls.Add(cont);
There is no such thing in C#. It's not a scripting language, so including a block of script wouldn't make sense.
What are you trying to accomplish? There are ways to do similar things in C#.
There is no direct equivalent. You use references to "link" with other CLR assemblies (access their type information), and the using directive to import namespaces.
For example, the FontCollection class is in the System.Drawing.dll assembly, and the System.Drawing.Text namespace. So you would add System.Drawing as a reference, and add the line:
using System.Drawing.Text;
I'm not sure, if this is what you want to do. But just for the case, maybe you have a look at:
<%
Response.WriteFile( "YourFile.whatever" )
%>
In addition to previous answers mentioning the using Directive and adding references to assemblies to your project (or at command line when compiling) there is a way to load other compiled .NET assemblies at runtime.
Assembly.Load will load an assembly (compiled c# file/.dll) into memory, allowing you to find and use types within that assembly. This can be used when building a plugin architecture. You publish an assembly with an interface for a plugin contract. Plugin makers can link to that that assembly and implement your interface. Your application can then load plugin assemblies, check for any types implementing your plugin interface and load and use those types into your application.
The only thing comparable in C# is using, which imports namespaces defined in assemblies referenced from the project. You cannot "include" a file in the sense that you dump the content right into your code.
For example, if your project references the System.Xml assembly, then the following code would allow you to access all of the classes in that namespace without fully qualifying their names:
using System.Xml;
This will let you use the type System.Xml.XmlDocument, for example, by specifying it as XmlDocument instead of its full type name System.Xml.XmlDocument.
There is no such thing in C#.
You're going to want to create an instance of a C# class and use that to invoke methods/attributes from other 'packages' (C# classes).
You can also use a using direction to be able to references assemblies from other projects.
Using is vaguely similar. It references another class that can then be used from that file, but it doesn't include the contents of that file directly inline.
using system;
(right at the beginning of a file)
Use this for c#
#RenderPage("header.cshtml")
This is taken from here:
http://www.w3schools.com/aspnet/showfile_c.asp?filename=try_webpages_cs_002
Although I know this post is old, but people stubming to this post can refer to it.
Well, here is what I did ... not sure if this is the right way, but it works...
In the .ascx File, specify a div as container to received the contents of included file.
<div id="containerForSomeMarkup" runat="server"></div>
In the .ascx.cs file, initialise this in the onInit() method or other methods as required...
containerForSomeMarkup.InnerHtml = File.ReadAllText("Full path of file to be included");
Coming from PHP world, for me, this approach helps keep the markup organized and intelligble...
The using keyword is what you're looking for.

Categories