Nice.  Thanks Greg.

On Wed, Jun 18, 2014 at 3:52 PM, Katherine Moss <katherine.m...@gordon.edu>
wrote:

>  PowerShell can also do that.
>
>
>
> *From:* ozdotnet-boun...@ozdotnet.com [mailto:
> ozdotnet-boun...@ozdotnet.com] *On Behalf Of *Greg Keogh
> *Sent:* Sunday, June 15, 2014 7:35 PM
> *To:* ozDotNet
> *Subject:* In praise of CSharpCodeProvider
>
>
>
> Folks, FYI -- on the weekend I hit the situation where I had lots of small
> pieces of similar code and I wanted it to configure their behaviour. I
> could have created a fancy set of parameters and more complicated code to
> apply them, but I decided the most desirable thing was to "script" the
> code. I've seen some apps and tools that compile C# source on-the-fly but
> I've never needed to do it myself until now. I thought it would be really
> difficult, but it's not. Here's the skeleton of my code:
>
>
>
> var provider = new CSharpCodeProvider();
> var parameters = new CompilerParameters();
> parameters.GenerateInMemory = true;
> parameters.ReferencedAssemblies.Add("System.Security.dll");
> parameters.GenerateExecutable = false;
> var results = provider.CompileAssemblyFromSource(parameters, mySourceCode);
> if (results.Errors.HasErrors || results.Errors.HasWarnings) {
>   /* do something with the error numbers and messages */
>   return;
> }
> Type[] types = results.CompiledAssembly.GetTypes();
>
>
>
> So you finish up with an in-memory Assembly and you can use reflection to
> get types and Invoke members. Don't forget to use *dynamic* on the
> reflected types to make your reflection code shorter and more readable.
>
>
>
> Overall, the resulting code is a little bit fiddly, but it's a powerful
> technique that's overlooked by a lot of developers.
>
>
>
> *Greg K*
>



-- 
Dan Cash                                    -- Mob. 0411 468 779
F.A.B. Information Systems Pty Ltd   abn 16 084 146 261

Reply via email to