Geeks With Blogs
Greg Young Greg.ToString()

Another GREAT question in MS newsgroups today.


I'm using the CSharpCodeProvider to buils some assemblies @ runtime which are
never saved as files (cp.GenerateInMemory = true;).
The generated assemblies are hierachically dependent on each other so I
generate the "bottom" assemblies first.

How do I add a dependency to another previously loaded (generated) assembly?

I would be happy if CompilerParameters.ReferencedAssemblies.Add could take a
System.Reflection.Assembly reference as parameter.

A possible solution would be to generate dll files and reference them but I
like the idea of not having any files to cleanup when my application exits.


I have seen this one a few times before but googling this subject brings up nothing so I will give a quick write up on it.

Often times when generating code for runtime use the assembly is simply created in memory. This prevents us from having to write out a temporary file for the assembly. Since the assembly is intended to have the same lifespan as our appdomain and the assembly is loaded into memory anyways, there is little use in us writing it to a temporary file as well.

A common issue that people run into is that it is rare that the assembly is completely stand-alone. It often times has to reference other assemblies. This is quite straight forward when you are dealing with assemblies that are on disk, just add the assembly as follows

Parameters.ReferencedAssemblies.Add("System.dll");

Sometimes however we want our assembly to reference another dynamically generated assembly. In this case many resort to writing the dependency out to disk as a temp file then reference the disk based tempory assembly when they generate the main assembly. This does not need to be done, all we need to do is assign an OutputAssembly to our first assembly and it will be loaded into our appdomain as that name. As such when the main assembly is loaded it will be seen that the assembly is in fact already in memory and as such accessible.

This method does not always work though. If the assembly that you are generating is to be hosted in another app domain (lets say it is its own process, take the example and make the example generate an executable for the main assembly that it then tries to run). The in memory assembly will only be within the calling appdomain and as such will not be accessible to the new appdomain.

In the sample code two assemblies are generated. The satellite assembly which contains a single class OtherObject that has a static method SomeMethod and the main assembly which a class MainObject with a method Test that calls into OtherObject from the other assembly. You will notice the two key points of the code are in

GenerateSatelliteAssembly : Parameters.OutputAssembly = "inmemoryassembly.dll"
GenerateMainAssembly : Parameters.ReferencedAssemblies.Add("inmemoryassembly.dll");

That said ... Here's the code!


using System;
using System.Reflection;
using System.CodeDom.Compiler;

using Microsoft.CSharp;
namespace TestInMemoryAssemblies
{
 class MainEntryPoint {
  private static void CheckResults(CompilerResults Results) {
   if(Results.Errors.Count > 0) {
    throw new System.Exception("Compile Failed");
   }
  }

  static Assembly GenerateMainAssembly() {
   Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
   ICodeCompiler compiler = codeProvider.CreateCompiler();
   CompilerParameters Parameters = new CompilerParameters(new string[] {"mscorlib.dll"});
   Parameters.ReferencedAssemblies.Add("System.dll");
   Parameters.ReferencedAssemblies.Add("inmemoryassembly.dll");
   Parameters.GenerateExecutable = false;
   Parameters.GenerateInMemory = true;
   string source = "";
   source += "public class MainObject {";
   source += " public void Test() {";
   source += "     System.Console.WriteLine(\"Running in main assembly, calling satellite assembly\");";
   source += "     OtherObject.SomeMethod();";
   source += "     System.Console.ReadLine();";
   source += " }";
   source += "}";
   CompilerResults results = compiler.CompileAssemblyFromSource(Parameters, source);
   CheckResults(results);
   return results.CompiledAssembly;
  }

  static void GenerateSatelliteAssembly() {
   CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
   ICodeCompiler compiler = codeProvider.CreateCompiler();
   CompilerParameters Parameters = new CompilerParameters(new string[] {"mscorlib.dll"});
   Parameters.ReferencedAssemblies.Add("System.dll");
   Parameters.OutputAssembly = "inmemoryassembly.dll";
   Parameters.GenerateExecutable = false;
   Parameters.GenerateInMemory = true;
   string source = "";
   source += "public class OtherObject {";
   source += " public static void SomeMethod() {";
   source += "     System.Console.WriteLine(\"Hello World from other object located in an in memory assembly\");";
   source += " }";
   source += "}";

   CompilerResults results = compiler.CompileAssemblyFromSource(Parameters, source);
   CheckResults(results);
  }
  static void Main(string[] args) {
   //build the satellite assembly
   GenerateSatelliteAssembly();
   //build the main assembly
   Assembly Generated = GenerateMainAssembly();
   //Get the main object
   object o = Generated.CreateInstance("MainObject");
   //Get the type of the main object
   Type t = o.GetType();
   //Request the Test method from the type
   MethodInfo mi = t.GetMethod("Test");
   //call the test method
   mi.Invoke(o, null);
  }
 }
}


*UPDATE*

This only gives the appearance of working properly. This will in fact load the satellite assembly into the appdomain twice.

'ConsoleApplication6.vshost.exe' (Managed): Loaded 'C:\Documents and Settings\Greg Young\My Documents\Visual Studio 2005\Projects\ConsoleApplication6\ConsoleApplication6\bin\Debug\ConsoleApplication6.exe', Symbols loaded.
'ConsoleApplication6.vshost.exe' (Managed): Loaded 'inmemoryassembly', No symbols loaded.
'ConsoleApplication6.vshost.exe' (Managed): Loaded 'wessmgnq', No symbols loaded.
'ConsoleApplication6.vshost.exe' (Managed): Loaded 'C:\Documents and Settings\Greg Young\My Documents\Visual Studio 2005\Projects\ConsoleApplication6\ConsoleApplication6\bin\Debug\inmemoryassembly.dll', No symbols loaded.

The reason that this happens appears to be some oddities with the CSharpCompiler. From poking through some reflectored code it appears that the CSharpCompiler always writes out files and the lifespan of these files is what is controlled by the “in memory” flag. It further appears that by giving an assembly a name you force it to be treated as a normal assembly at some points and an in-mmeory assembly at others as opposed to a normal inmemory assembly :( I probably should have figured out this from the fact that it didn't work with the automagically generated names but the final decision on this is that there is no way to do this.

Posted on Thursday, April 27, 2006 3:14 AM Tips and Tricks , Under the covers | Back to top


Comments on this post: Dependent in memory assemblies

# re: Dependant in memory assemblies
Requesting Gravatar...
Hi Greg,

Thanks alot for your answer on the dotnet.languages.csharp newsgroup.

If I don't give the assemblies filenames they're given names by the compiler. Wouldn't it also be possible to get that name from the compiled assembly and use that for the dependency?

/Jan
Left by Jan on Apr 27, 2006 4:01 AM

# re: Dependant in memory assemblies
Requesting Gravatar...
I tried it and it didn't work :(

Left by Greg Young on Apr 27, 2006 4:09 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Thank you very much for this info!

I would have never thought that setting the OutputAssembly property was of any use, when the compiler generated doesn't work...

Moritz
Left by Moritz on Sep 08, 2006 5:46 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Useful information. Thanks.
Left by Alphakanal on Sep 29, 2008 9:06 AM

# London escorts
Requesting Gravatar...
It is rather interesting for me to read this blog. Thank author for it. I like such topics and everything connected to this matter. I definitely want to read more on that blog soon.
Left by Russian escorts on Nov 21, 2009 2:16 AM

# Best shop ever
Requesting Gravatar...
Keep on posting such themes. I love to read stories like this. Just add more pics :)
Left by SteaveTheMighty on Jan 22, 2010 6:43 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
I am always happy with the amount of info I find to elp me with my programing and this is no exception thank you so much,
Left by Escorts in London on Jan 29, 2010 5:43 AM

# Great post
Requesting Gravatar...
Interesting story you got here. It would be great to read something more about that matter. Thanks for posting that information.
Left by PhillDoc on Feb 11, 2010 11:05 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
A dependant assembly is resolved when a type is needed that is defined in that assembly. So the assembly is loaded on demand.The CLR loader loads and initializes as little as it can get away with
Left by giochi dei casinò online on Apr 10, 2010 1:18 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Great info for Geeks you done it again thank you so much!!!
Left by Escorts in London on Jun 02, 2010 4:31 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
I got really stuck on this code so I am glad that someone finally figured it out!
Left by London Escorts on Jun 07, 2010 6:49 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
thanks so much foryour help.
Left by australian escort on Aug 05, 2010 7:41 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
I appreciate your input. will read again.
Left by dubai escort on Aug 06, 2010 1:23 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
this is well worth another read. thank you
Left by delhi escorts on Aug 10, 2010 7:42 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
Often times when generating code for runtime use the assembly is simply created in memory.
Left by sydney escort on Aug 11, 2010 1:36 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
thankyou for the help for my programming, there is alot of great help on the internet but this has helped the most thankyou.
Left by london escorts on Sep 06, 2010 8:52 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Intresting aricles you place here.
It would be useful to read anything more concerning this topic.
Thnx for tell that information.
With best regards Angela!!
Left by Kiev escort on Sep 16, 2010 8:06 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
this doesn't work. when i set output assembly it generates a dll even if generateexecuteable = false. generateexecutable just means that the dll has an entry point(sub main)
Left by asdfsdf on Oct 02, 2010 12:39 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
nevermind my last comment
apparently you have to set Parameters.GenerateInMemory = True
AFTER!! you set output assembly
Left by asdfasdf on Oct 02, 2010 12:41 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
The Assemblies Website aims to provide high-quality, instant access primary and secondary school assemblies for teachers and others leading collective worship.
Left by Huntsville OB GYN on Oct 06, 2010 12:59 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Intresting aricles you public here.
It will be useful to read anything more concerning this topic.
Thank for giving that information.
With best regards!
Left by Kiev escort on Oct 06, 2010 6:18 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
The Election Commission of India (ECI) has announced the schedule for by-elections in the legislative assemblies of Uttar Pradesh, Assam, Himachal Pradesh, Kerala, Rajasthan, Chattisgarh, and West Bengal and in the House of People from 20 - Firozabad P.C of Uttar Pradesh to fill the vacant seats.
Left by Huntsville OB GYN on Oct 06, 2010 8:10 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
interesting approach, thank you!
Left by tantric massage london on Oct 07, 2010 3:07 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
thankyou for the help for my programming
Left by lpg conversion on Oct 15, 2010 2:54 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
Stock market India is volatile and all those who speculate in market are loosing everyday. Please remember stock market is not for speculation purpose. If one feel investing in stock market is gamble then its better to think again.
One should always note that if they want to invest money they should do proper research be it fundamental research or technical research. Just think how come you can invest
your money without any convincing reason for the same?
Indian stock market is one of the most happening and emerging market. Major Indian stock exchanges are BSE and NSE and both are of world class standards.
So grab good stocks and invest that’s the bottom line.
We hope to see you in major profits.


Intraday Tips
Left by Commodity Tips on Oct 18, 2010 1:26 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Useful information.
Left by lpg conversion on Oct 19, 2010 9:00 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Thanks for the great share.
Left by diecast cars on Oct 26, 2010 11:09 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Paris thanks you with all of its heart
Left by happy on Nov 30, 2010 2:42 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
Paris thanks you with all of its heart you know
Left by annaferrini on Nov 30, 2010 2:43 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
I appreciate your input. will read again.
Left by London Escort on Dec 01, 2010 4:28 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
C# is not anymore a viable solution nowadays but I really appreciate you're sharing with us all these, thanks a lot!
Left by Protein Powders on Dec 06, 2010 11:05 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Thanks for the effort you have put on your blog I really like your post . Keep on posting !!!
Left by RGGALAK on Dec 08, 2010 5:03 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Great insight and very uplifting
Left by Paris escort on Feb 08, 2011 4:28 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
When the current application looks for assemblies, it looks in several locations (bin folder, gac, etc..) if it can not find one, then the developer needs to manually tell the application where to look. You can do this by intercepting the AssemblyResolve event, and using the event args to tell the CLR where your assembly is.

Thank you,
Intraday Trading Tips || Trading Tips
Left by Intraday Tips on Feb 15, 2011 1:39 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
This does not need to be done, all we need to do is assign an OutputAssembly to our first assembly and it will be loaded into our appdomain as that name.
Left by Watches on Feb 17, 2011 10:08 AM

# eatcity
Requesting Gravatar...
Great topic, please keep it up...
Left by Brazilian Escorts on Mar 09, 2011 8:21 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
London escort agency which provides genuine female escort models in Central London area.
Left by escorts london on Mar 30, 2011 9:19 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Great question and a very good answer, thank you
Left by LPG Suppliers on Mar 30, 2011 9:40 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
If you are looking for European escorts Bestescort4U is the best place in London
Left by London escorts on Apr 01, 2011 3:22 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Bentley's International Models is a London escort agency providing elite top class
Left by Elite London escorts on Apr 03, 2011 5:45 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Asian Classic is a highly rated London escorts service in Central London
Left by Asian London escorts on Apr 03, 2011 10:03 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
Elite Club International is very selective and work only with ladies who really can provide an excellent escort service experience.
Left by Elite escorts on Apr 03, 2011 4:03 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
Bunny Planet is an Exclusive Online Gentlemen's Club filled with Adult Stars, Adult Entertainers, Centerfolds and Erotic Models who want to meet you in person now!
Left by Porn Star Escorts on Apr 06, 2011 2:40 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
We provide honest, discreet, confidential UK and worldwide high class escorts services for gentlemen of taste who interested in elegant and sexy companionship.
Left by London escort agency on Apr 08, 2011 6:28 AM

# Transsexual dating
Requesting Gravatar...
Transsexual dating website for transsexuals and gays with videos, forum, webcams and announcements.
Left by Lijana on Feb 20, 2012 6:07 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
very interesting, thx
Left by mayaescorts on Aug 21, 2012 11:37 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
very usefull,
Left by londonladies on Aug 21, 2012 11:37 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
very interesting, thx you
Left by paddington4u on Aug 24, 2012 12:36 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
great article, you make a good job
Left by paddington4u on Aug 25, 2012 12:50 AM

# re: Dependent in memory assemblies
Requesting Gravatar...
nice blog, thanks you very much for this
Left by london richmond escorts on Nov 11, 2012 5:50 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
Very interesting article, you're a great blogger.. take care
Left by richmond escorts on Jan 17, 2013 5:27 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
Great website, you find very usefull informations.. thank you
Left by hotel london escorts on Jan 24, 2013 1:08 PM

# re: Dependent in memory assemblies
Requesting Gravatar...
You clearly know what you are doing. It’s good to see this information in your article.
Left by london escorts on Feb 25, 2013 3:33 PM

Your comment:
 (will show your gravatar)


Copyright © Greg Young | Powered by: GeeksWithBlogs.net | Join free