Xamarin: Failed to create JavaTypeInfo for class … due to System.NullReference Exception

In my Xamarin\Android project, I wanted to use a WebView and add a JavascriptInterface to enable communication between my app and the JavaScript inside the WebView. I found an example here which was quite easy and straight forward. To explore things a little bit more, I wanted to add a JavaScript-callable method that accepts a parameter of type System.Object, call it with random objects from JavaScripts and see what these JavaScript objects transform to in the .NET world. Continue reading

VS2017 Failed To Install – Setup Failed To Detect Shared Configuration

Today, I tried to install Visual Studio 2017. As with too many Microsoft products lately, after paying a significant amount of money for the product, it failed on the first usage (during installation, that is) 😦

A click on “View log” revealed the following information:

The product failed to install the listed workloads and components due to one or more package failures.
[...]
Package 'Microsoft.VisualStudio.WebDeploy.Msi,version=15.0.26208.0,chip=x64' failed to install.
[...]
    Details
        MSI: C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualStudio.WebDeploy.Msi,version=15.0.26208.0,chip=x64\webdeploy_x64.msi, Properties:  REBOOT=ReallySuppress 
        Return code: 30001
        Return code details: Setup failed to detect shared configuration.

But wait! “Shared configuration” is an IIS feature. So what’s wrong here? To check that, I opened up the IIS administration console and to my surprise, I was asked to re-enter the credentials for localhost. So apparently the administration console was not able to connect to IIS. Well if IIS was not running properly, that could possibly explain why the shared IIS configuration could not be detected. So I removed and re-added the “Internet Information Service” Windows feature (restart in between required):

After that, I retried installing VS 2017 and voila – it worked 🙂

TLDR: Reinstall the “Internet Information Service” Windows feature.

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