C#: Loading Dynamic Assemblies Into Other AppDomains

So you have generated a dynamic assembly (like here) and want to load the assembly into a new (or at least another than the current) AppDomain? Well, there’s a catch. You cannot share dynamic assemblies across AppDomains (easily)… Continue reading

Parse Date From String In JavaScript

Suppose you have a string representation of a date, e.g. “2015-05-15T22:43:35.0962104+02:00” or “5/15/2015”, and you need to parse that string into a JavaScript Date object. Here’s how to do it:

// Parse string into the number of milliseconds since January 1, 1970, 00:00:00 UTC.
var ticks = Date.parse("5/15/2015");

// Create an instance of Date using the number of milliseconds.
var date = new Date(ticks);

// Check the value of the Date instance 
console.log(date);
// yields "Mon Oct 05 2015 00:00:00 GMT+0200 (W. Europe Daylight Time)"

In-Memory Code Generation at Run-Time With .NET – Part 5 – Loading

This article is split into 5 posts.

  1. Introduction
  2. Templating Engines
  3. Code Generation From Source
  4. Code Generation From Model
  5. Loading

Loading

The previous articles from this post series have discussed how to generate .NET types at runtime and how to get .NET assemblies that contain these types. This article shows different methods of finding the generated types in a given assembly and creating instances of these types at runtime.

Reflection

The most basic method of using the type we have just created is the utilization of System.Reflection. Since we have generated an assembly, all we need to do is to search all (exported) types in that assembly for a type that implements the interface or base class we are looking for. If you happen not to be familiar with Reflection, here’s an article that sums up all you need to get going.

var csharpCode = @"
    using System;
    using System.ComponentModel.Composition;

    namespace ThisDemo
    {
        public class YouSayHello : ISayHello
        {
            public void SayHello()
            {
                Console.WriteLine(""Hello"");
            }
        }
    }";

// Compile the code into an in-memory assembly.
var generatedAssembly = Compile(csharpCode);

// Get the first type that implements the required interface from the generated assembly.
var generatedType = generatedAssembly.ExportedTypes.First(t => typeof(ISayHello).IsAssignableFrom(t));

// Create an instance of the type.
var sayHello = (ISayHello)Activator.CreateInstance(generatedType);

// Use the instance.
sayHello.SayHello();

The advantage of using this method is that no additional (3rd party) components are required. Only a few lines of code are required to achieve the goal. Also, we control every aspect of the process since we are using a low-level functionality of the .NET framework. The disadvantage, however, is that we must control every aspect of the process since we are using a low-level functionality of the .NET framework.

Dependency Injection

It’s not without good reason that dependency injection (DI) or inversion of control (IoC) is a pattern that is being more and more adopted. I won’t go into details about what DI\IoC is or what the advantages of DI\IoC are, just into how to instantiate and use our generated types in a DI\IoC scenario.

class CodeRunner
{
    ISayHello sayHello;

    public CodeRunnter(ISayHello sayHello)
    {
        this.sayHello = sayHello;
    }

    public void Run()
    {
        this.sayHello.SayHello();
    }
}

var csharpCode = @"
    using System;

    namespace ThisDemo
    {
        public class YouSayHello : ISayHello
        {
            public void SayHello()
            {
                Console.WriteLine(""Hello""
            }
        }
    }";

// Compile the code into an in-memory assembly.
var generatedAssembly = Compile(csharpCode);

// Get the first type that implements the required interface from the generated assembly.
var generatedType = generatedAssembly.ExportedTypes.First(t => typeof(ISayHello).IsAssignableFrom(t));

// Register the type with the DI container.
container.Register<ISayHello>(generatedType);

// Use DI container to build an object graph.
// The object graph will contain an instance of the generated type.
// Assuming that the type CodeRunner has been registered with the container earlier.
var codeRunner = container.Resolve<CodeRunner>();

// Use the object graph, eventually calling the generated type.
codeRunner.Run();

The code above shows that we still need to find the type in the generated assembly ourselves before registering it with the DI container. There might be DI frameworks that are able to search assemblies for types themselves (such as Autofac, if I remember correctly), but even then we’ll need to tell the DI container what type of types to search for (i.e. by defining a base class or interface or by providing a filter delegate).

The DI\IoC pattern is best suited for scenarios where types are added once but not changed for the rest of the application’s life time.

Managed Extensibility Framework

Enter MEF, Microsoft’s Managed Extensibility Framework. There are lots of articles on the internet about the difference between MEF and DI frameworks and about the pros and cons of choosing either one, so I won’t get into details here. But I do want to point out that MEF plays very well in scenarios with dynamic assemblies, since MEF is made for dynamic type and dependency discovery at runtime. So let’s look at some code:

using System.ComponentModel.Composition;

class CodeRunner
{
    [Import]
    ISayHello sayHello;

    public void Run()
    {
        this.sayHello.SayHello();
    }
}


var csharpCode = @"
    using System;
    using System.ComponentModel.Composition;

    namespace ThisDemo
    {
        [Export(typeof(ISayHello))]
        public class YouSayHello : ISayHello
        {
            public void SayHello()
            {
                Console.WriteLine(""Hello"");
            }
        }
    }";

// Compile the code into an in-memory assembly.
var generatedAssembly = Compile(csharpCode);

// Initialize MEF to search in the generated assembly.
var catalog = new AssemblyCatalog(generatedAssembly);
var container = new CompositionContainer(catalog);

// Instantiate the root of the object graph.
var codeRunner = new MefCodeRunner();

// Use MEF container to build-up the object graph.
// The object graph will contain an instance of the generated type.
container.ComposeParts(codeRunner);

// Use the object graph, eventually calling the generated type.
codeRunner.Run();

Notice the Export attribute in the C# code above. This is what tells MEF to consider this type. Remember to add this attribute to the generated code or else MEF won’t discover the generated type.

MEF is intended for plugin architectures and supports adding and removing of used types during runtime.

Fix Visual Studio 2013 Razor CSHTML Intellisense in Class Library or Console Application

sdeu's Blog

I tried to use a .cshtml file and the razor syntax in a console application. I was able to build the project, but the intellisense and the error tab complaint about “The name ‘Model’ does not exist in the current context“:

error

The usual fixes, like throwing in a web.config, didn’t work. But then I found a fix to solve that problem. Here are the steps:

  • make sure you have the Microsoft ASP.NET MVC nuget package and its dependecies installed
  • clean and build your project, close your .cshtml-files
  • copy the following DLLs from Debug (or the mode you’re in) right to the bin folder
    • Microsoft.Web.Infrastructure.dll
    • System.Web.Helpers.dll
    • System.Web.Mvc.dll
    • System.Web.Razor.dll
    • System.Web.WebPages.Deployment.dll
    • System.Web.WebPages.dll
    • System.Web.WebPages.Razor.dll

fix

  • open your .cshtml file
  • it should work

Reason: I guess it’s because in a normal web project there is only a bin folder, no Debug or Release. Visual Studio seems to look directly into that folder for…

View original post 39 more words

C#: Getting Installer Product Data From Hosted Web PI GUI

The previous post explained how to get event notification from a running WPI installer instance. This post will describe how to get information about the products being installed by WPI and about the installation status itself. Continue reading

C#: Getting Feedback From Hosted Web PI GUI

The previous post explained how to host the Microsoft Web Platform Installer (WPI) in an own Windows Forms application. It’s nice that we can do that, but it only really makes sense when you need to perform special actions depending on the parameters determined by WPI during installation. Continue reading

C#: Hosting Web PI GUI In Own Application

The Microsoft Web Platform Installer (WPI) is a very cool tool for installing frameworks, programs and web application. It automatically resolves installs dependencies, which makes it my top choice for deploying my own applications.

In some cased, I need to install multiple applications and update their local configuration to contain data of other applications (e.g., the web site URL of one application gets written to the web.config of another application). The installer application internally uses WPI to perform the dependency resolving and the actual installation. The installer application itself performs the cross-application configuration and installs other components not installable via WPI.

This post shows how to integrate WPI’s GUI into a custom application. Continue reading