15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

438 ❘ ChaPTer 18 Assemblies<br />

With Visual Studio 2010, you can configure these<br />

attributes with the project properties, Application settings,<br />

<strong>and</strong> Assembly Information, as you can see in Figure 18-6.<br />

Creating <strong>and</strong> loading assemblies<br />

dynamically<br />

During development time, you add a reference to an assembly<br />

so that it gets included with the assembly references, <strong>and</strong> the<br />

types of the assembly are available to the compiler. During<br />

runtime the referenced assembly is loaded as soon as a type<br />

of the assembly is instantiated or a method of the type is<br />

used. Instead of using this automatic behavior, you can<br />

also load assemblies programmatically. To load assemblies<br />

programmatically, you can use the class Assembly with the<br />

static method Load(). This method is overloaded where you<br />

can pass the name of the assembly using AssemblyName, the<br />

name of the assembly, or a byte array.<br />

figure 18-6<br />

It is also possible to create an assembly on the fly, as shown with the next example. This sample<br />

demonstrates how <strong>C#</strong> code can be entered in a text box, a new assembly is dynamically created by starting<br />

the <strong>C#</strong> compiler, <strong>and</strong> the compiled code is invoked.<br />

To compile <strong>C#</strong> code dynamically, you can use the class CSharpCodeProvider from the namespace<br />

Microsoft.CSharp. Using this class, you can compile code <strong>and</strong> generate assemblies from a DOM tree, from<br />

a file, <strong>and</strong> from source code.<br />

The UI of the application is created by using WPF. You can see the design view of the UI in Figure 18-7. The<br />

window is made up of a TextBox to enter <strong>C#</strong> code, a Button, <strong>and</strong> a TextBlock WPF control that spans all<br />

columns of the last row to display the result, as shown in Figure 18-7.<br />

figure 18-7<br />

To dynamically compile <strong>and</strong> run <strong>C#</strong> code, the class CodeDriver defines the method CompileAndRun().<br />

This method compiles the code from the text box <strong>and</strong> starts the generated method.<br />

using System;<br />

using System.CodeDom.Compiler;<br />

using System.IO;<br />

using System.Reflection;<br />

using System.Text;<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!