Using .NET 4.6 librarieS in unity3d 2017

18-4-2017: Update post for Unity 2017

For a long time it has been a lot of hassle to use existing .NET libraries in Unity3D. Unity3D only supported .NET 2.0/3.5, so more recent libraries (4.0 and up) could not be used without recompiling/rewriting for .NET 2.0/3.5.

Also new C# language constructs (C# 6) could not be used by game developers  Sad smile

At the moment Unity3D is upgrading the Mono version to 4.6. The first beta’s of Unity 2017 with .NET 4.6 support are available for download so let’s take a test drive.

Installation Unity 2017.1.0b1: https://unity3d.com/unity/beta (Released: April 11, 2017)

In the Unity 2017.1.0b1 editor .NET 4.6 is selectable at Edit –> Project settings –> Player –> Other settings –> Configuration

net46

After selecting ‘Experimental (.NET 4.6 Equivalent) Unity has to be restarted  Sad smile 

For the test I’ve created a sample project (https://github.com/bertt/dotnetstandard_and_unity3d) that does the following:

. get a location (latitude, longitude)

. Determine the OpenStreetMap tile on that location using .NET Standard library Tilebelt

. Download and display the tile on a Unity3D Plane GameObject.

Code sample:

===================================================================

void Start()
{
    var coords = new double[] { -84.72, 11.17, -5.62, 61.60 };
    var parent = Tilebelt.BboxToTile(coords);
    StartCoroutine(requestTile(parent));
}

private IEnumerator requestTile(Tile t)
{
    var url = tile2url(t);
    var handler = new DownloadHandlerBuffer();
    var http = new UnityWebRequest(url);
    http.downloadHandler = handler;
    yield return http.Send();

    if (!http.isNetworkError)
    {
        var texture = new Texture2D(10, 5);
        texture.LoadImage(http.downloadHandler.data);
        var tileGO = GameObject.CreatePrimitive(PrimitiveType.Plane);
        var renderer = tileGO.GetComponent<MeshRenderer>();
        renderer.material.mainTexture = texture;
    }
}

private string tile2url(Tile tile)
{
    return $"
https://b.tile.openstreetmap.org/{tile.Z}/{tile.X}/{tile.Y}.png";
}

 

===================================================================

The Tilebelt library (https://github.com/bertt/tilebelt-cs) is a small library with some utility functions for working with the OpenStreetMap tiling scheme. It is compiled for .NET Standard 1.1 with the following dependencies:

  • System.Collections (>= 4.3.0)

  • System.Runtime.Extensions (>= 4.3.0)

  • System.Resources.ResourceManager (>= 4.3.0)

  • System.Runtime (>= 4.3.0)

The dependencies we could get from NuGet or they could be found in the folder C:\Program Files\Unity 2017.1.0b1\Editor\Data\MonoBleedingEdge\lib\mono\unity_aot\Facades

The Tilebelt.dll assembly and dependencies we have to copy manually to the assets folder, unfortunately the NuGet support is not so great yet.

Here a screenshot of the application build for Windows:

image

This is just a small example of using a .NET Standard library in Unity3D. But the concept is working already,now we should be able to use other standard .NET libraries as well Smile

Visualizing terrains with Cesium

Today we did some experiments to visualize terrains in Cesium, using Cesium Terrain Builder (https://github.com/geo-data/cesium-terrain-builder) and Cesium Terrain Server (https://github.com/geo-data/cesium-terrain-server)

Step 1] Get some raster data with height information

For this demonstration we use a raster file from the Dutch AHN2 in tif format with cells 0.5m X 0.5m, it can be obtained from http://www.rijkswaterstaat.nl/apps/geoservices/geodata/dmc/ahn2_05_int/geogegevens/raster/01_09/i09bz1.tif  (500MB)

This image is about a part of Texel:

image

Step 2] Tile the raster with Cesium Terrain Builder

The original tif image is quite big (500MB) so we cut it into tiles using the  Cesium Terrain Builder. We use the tool ‘ctb-tile‘ for tiling inside a Docker container:

$ docker run -v  d:/gisdata/nederland/terrain:/data -ti -i homme/cesium-terrain-builder:latest bash

root@c1412e2fd51c:/# ctb-tile -o /data/tiles /data/i09bz1.tif

image

This takes some time to process (like 10 minutes), so grab a coffee and relax…

In the meantime binary .terrain files are generated for 20 zoom levels.

image

The terrain tiles are encoded in the so called ‘quantized-mesh-1.0 terrain format’, more info about this format at https://github.com/AnalyticalGraphicsInc/quantized-mesh

Step 3: Run the Cesium Terrain Server

If all the tiles are generated we can start the Cesium Terrain Server. We use another Docker command for this:

$ docker run -p 8080:8000 -v d:/gisdata/nederland/terrain:/data/tilesets/terrain geodata/cesium-terrain-server

image

One tile we can retrieve from the server using a wget command:

wget http://localhost:8080/tilesets/tiles/0/0/0.terrain

image[22]

Step 4: Visualize the terrain in Cesium

Cesium is a WebGL globe viewer that runs in a browser, see https://cesiumjs.org/ for more info.

All it takes now is to change in de basic Cesium viewer the index.html so it points to our local terrain server for getting the terrain tiles.

image

Put the Cesium viewer on a webserver (for example caddy https://caddyserver.com/) , open a browser and zoomin to Texel.. If you change the perspective the terrain should become visible:

image

Play with Docker in the browser

Want to experiment with this thing called Docker but don’t want to go through the hassle of installing it? Go to http://play-with-docker.com/ and you are good to go.

In this website you can spin up 5 instances of Linux running for 4 hours. Lets make a webserver running there and see how it all works.

First press ‘Add new Instance’ and a new machine start up.

image

The machine is running on ip number 10.0.240.3. We need this number later on Star.

Now start a Nginx webserver on port 80:

$ docker run –name docker-nginx -p 80:80 -d nginx

image

We need one more thing, we want to test the webserver on some public address. With some Ngrok magic this is possible, but be sure to replace the ip address with your ip address Star.

$ docker run –net host -ti jpetazzo/ngrok http 10.0.240.3:80

image

A new server is started on http://18d73db6.ngrok.io, we can use this address in a browser to test it all.

image

And it all works Smile

More advanced Docker topics are now also possible, like running multiple containers with docker-compose or a cluster with Docker Swarm.

Getting started with ASP.NET Core and Docker

Here a post about getting started with .NET Core and Docker. Goal is to run a .NET webservice inside a Docker container.

Step 1] Get the stuff

a. Install .NET Core SDK

Get the .NET Core SDK at https://www.microsoft.com/net/core#windows

There are installations for Windows, Mac and various Linux machines.

If installation goes well you should be able to run command ‘dotnet‘:

Image

For fun try to run commands like ‘dotnet new‘, ‘dotnet restore‘ and ‘dotnet run‘ and a Hello World app should run:

Image

 

b. Install Yeoman and ASP.NET generator

Yeoman is a command line tool for generating/scaffolding projects. Installation is easy: run ‘npm install -g yo’ (NodeJS should be installed).

After installation run the ‘yo’ command and install the aspnet generator:

image

c. Install Docker player

There are various methods to get Docker running on your machine, but most easiest is installing the Docker for Mac or Windows from https://www.docker.com/products/overview . Warning: on Windows you need to have Windows 10 and Hyper-V enabled.

If installation goes well you can run the ‘Docker’ command:

image

 

Step 2: Create new application

Create a new application by running command ‘yo aspnet’ and choose ‘Web API Application’ option. Give the application a name and the application is created. Change the directory to the new application, run again ‘dotnet restore’ and ‘dotnet run’. Open a browser and navigate to ‘http://localhost:5000/api/values’‘ and the response should be: [“value1″,”value2”]

 

image

 

Step 3: Run from Docker

Now it’s time to run the application from Docker. The ASP.NET generator has also created a sample Dockerfile:


FROM microsoft/dotnet:latest

COPY . /app

WORKDIR /app

RUN ["dotnet", "restore"]

RUN ["dotnet", "build"]

EXPOSE 5000/tcp

CMD ["dotnet", "run", "--server.urls", "http://*:5000"]

Run from the command line the following commands:

$ docker build -t mydemos:aspnetcorehelloworld .

image

A new Docker image is created containing our new application. Now start a new container by the following command:

$ docker run -d -p 8080:5000 -t mydemos:aspnetcorehelloworld

image

The container is started and should be available at port 8080:

image

Voila, we have a new ASP.NET Core application running from Docker!

Unit test Web Api methods with in-memory HttpServer

Here are the steps to test your Web Api methods with an in-memory webserver. We have a simple Web Api project with 1 method:
/api/test returns "hello".

This unit test method can be used in Web API v1. In Web Api v2 there are some other methods (with Owin).

  • Add new class project
  • Add a reference to the Web Api project to be tested
  • Iin the Nuget package window: install-package nunit (or install your favorite unit tester)
  • install-package Microsoft.AspNet.WebApi -version 4.0.30506.0
  • Add reference to System.Web.dll
  • Add a new Class with Unit test code:

    [TestFixture]
    public class UnitTest
    {
        [Test]
        public void Test()
        {
            //arrange
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { routetemplate = "Version", id = RouteParameter.Optional });

            var server = new HttpServer(config);
            var client = new HttpClient(server);

            // act
            var response = client.GetAsync("http://server/api/test").Result;

            //assert
            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            var answer= response.Content.ReadAsStringAsync().Result;
            Assert.IsTrue(answer.Contains("hello"));
        }
    }

In this test a HttpServer is started with the same configuration as the Web Api project, and a HttpClient is created. After that, a request is fired and the response
is analysed.
And the test should work 🙂 However I had some issues to get this working, in the response there was always a HTPP 404 not found result. This is solved by calling in the test first some method of the Web Api project (for example the configuration object).

Create PDF’s with ASP.NET Web Api

This blog describes how to generate PDF’s with ASP.NET Web Api using PdfSharp/MigraDoc.

 

Sample result:

http://servername/api/test.pdf?author=bert generates a pdf with  the authorname as parameter. This sample can be extended to create

complete dynamically  reports.

 

Sample code is available on https://github.com/bertt/DynamicPDF

 

Step 1: Generate new empty ASP.NET project with Visual Studio

image

Step 2: Install Microsoft.AspNet.WebApi from NuGet

image

Step 3: Install ‘PDFsharp-MigraDoc-GDI’ from NuGet:

image

 

Step 4: Change web.config

Add the following to in web.config file in the system.webServer section:

 

<modules runAllManagedModulesForAllRequests="true"/>

 

This is needed because otherwise the IIS webserver will search for a static PDF file and not a dynamic one generated by ASP.NET.

 

Step 5: Add global.asax with the following content:

 

    public class Global : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.Ignore("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
                name: "IdWithExt",
                routeTemplate: "api/{controller}.{ext}");

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);

            var pdfFormatter = new PdfMediaTypeFormatter();
            GlobalConfiguration.Configuration.Formatters.Add(pdfFormatter);
        }
    }

In the Global.asax we register the PDF Mediatypeformatter, defined in the next step.

 

Step 6: Add a Mediatype formatter for PDF 

Add a new class ‘PdfMediaTypeFormatter’. This class overrides from MediaTypeFormatter. Important is the ‘SupportedType’, only controllers

who return the SupportedType will use this formatter. Another important parameter is the ‘object value’ in the WriteToStreamAsync method. This parameter

contains the specified PDF parameter (in our case the author name).

 

   public class PdfMediaTypeFormatter : MediaTypeFormatter
    { 
       private static readonly Type SupportedType = typeof(Person); 

       public PdfMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/pdf"));
            MediaTypeMappings.Add(new UriPathExtensionMapping("pdf", "application/pdf"));
        } 

       public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
        { 
           var taskSource = new TaskCompletionSource<object>(); 
           try 
           { 
               var person = (Person)value; 

               var doc = PdfGenerator.CreatePdf(person.Name); 
               var ms = new MemoryStream();

                doc.Save(ms, false); 

               var bytes = ms.ToArray();
                writeStream.Write(bytes, 0, bytes.Length);
                taskSource.SetResult(null);
            } 
           catch (Exception e)
            {
                taskSource.SetException(e);
            } 
           return taskSource.Task;
        } 

       public override bool CanReadType(Type type)
        { 
           return SupportedType == type;
        } 

       public override bool CanWriteType(Type type)
        { 
           return SupportedType == type;
        }

Step 7:  Add a simple test controller class.

 

 

This controller returns a Person class, which will be rendered using the PDF Media Type.

    public class TestController:ApiController
    {
        public HttpResponseMessage GetTest(string author)
        {
            var person=new Person{Name=author};
            return Request.CreateResponse(HttpStatusCode.OK,person);
        }
    }
 

Step 8: Add a Person class

    public class Person
    {
        public String Name { get; set; }
    }

Step 9: Add code to generate a PDF (class PdfGenerator).

 

This code creates an in-memory PDF and returns it.

 

    public static class PdfGenerator
    {
        public static PdfDocument CreatePdf(string author)
        {
            var document = new Document();
            var sec = document.Sections.AddSection();
            sec.AddParagraph("Author:" + author);
            return RenderDocument(document);
        }

        private static PdfDocument RenderDocument(Document document)
        {
            var rend = new PdfDocumentRenderer {Document = document};
            rend.RenderDocument();
            return rend.PdfDocument;
        }
    }

 

Step 10: Test!

Run the project and open http://localhost:64118/api/test.pdf?author=piet

A PDF file with the specified authorname will be returned if all goes well

 

image

Consuming webservices with Portable Class Library (PCL)

This a sample to consume a webservice using Portable Class Library (PCL). In this sample we are retrieving some geographical information from the

http://geonames.org site. Because we use portable class libraries, we can reuse this code on the different .NET platforms: Silverlight, .NET Framework 4.5, Windows Phone 7.5/8 and Windows 8 Store Apps.

Support for PCL is coming for platforms like Mono, Xamarin.iOS and Xamarin.Android. Write once, run everywhere!

 

Step 1/5: Create Portable Class Library project in Visual Studio 2012

File –> New-> Project –> Visual C# –> Portable Class Library

Be sure to select .NET Framework 4.5:

image

 

Set target frameworks as follows:

image

 

Step 2/5: Install nuget packages

In the NuGet package manager console type:

1: ‘install-package microsoft.net.http –pre’ : installs the PCL version of HttpClient

Result should be (without license text):

PM> install-package microsoft.net.http -pre

Attempting to resolve dependency ‘Microsoft.Bcl (≥ 1.0.16-rc)’.

Attempting to resolve dependency ‘Microsoft.Bcl.Build (≥ 1.0.0-rc)’.

Successfully installed ‘Microsoft.Bcl.Build 1.0.0-rc’.

Successfully installed ‘Microsoft.Bcl 1.0.16-rc’.

Successfully installed ‘Microsoft.Net.Http 2.1.3-beta’.

Successfully added ‘Microsoft.Bcl.Build 1.0.0-rc’ to PortableClassLibrary4.

Successfully added ‘Microsoft.Bcl 1.0.16-rc’ to PortableClassLibrary4.

Successfully added ‘Microsoft.Net.Http 2.1.3-beta’ to PortableClassLibrary4.

 

2: ‘install-package newtonsoft.json – pre’: installs the PCL version of JSON.NET

 

image

 

Step 3/5: Write some code in the PCL

In this sample we are retrieving some information about earthquakes:

http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt

Copy the json result of the earthquakes in a new c# file. Use paste –> paste special –> paste JSON as classes.

 

image

Results should be:

Geonames models

 

Now write the code to request the webservice and parse the results:

GeoNames Webservice Client Api

 

public Earthquake[] GetEarthquakes() {

var client = new HttpClient();

client.BaseAddress = new Uri(http://api.geonames.org/);

var response = client.GetAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt").Result;

var earthquakesJson = response.Content.ReadAsStringAsync().Result;

var rootobject = JsonConvert.DeserializeObject<Rootobject>(earthquakesJson);

return rootobject.earthquakes;

}

 

Step 4/5:  Add a Windows 8 client

Add a Windows 8 client to the solution

Solution-> Add new Project… –> Windows Store –>  Blank App Xaml

Add a reference to the portable class library:

Select Project –> add reference –> select the new portable class library

 

Step 5/5: Add 1 line of code to the Windows 8 client

Open the mainpage.xaml.cs file and add to the OnNavigatedTo method:

var earthquakes = new GeonamesApi().GetEarthquakes();

if everything works ok, there will be some earthquakes coming back. Or there are no earthquakes in this area Glimlach . Otherwise inspect with

Fiddler to see whats going on.

image

 

Next step is to put the results somewhere in the user interface but I’ll leave that for another post. Good candidate for this is the MVVM Cross Library:

https://github.com/slodge/MvvmCross

 

Code:

TypeScript and JQuery example

This is an example of using TypeScript and JQuery.

Steps:

1] Install TypeScript from here: http://www.typescriptlang.org/

2] Create typescript file hello.ts:

see typescript file

3] Get a JQuery TypeScript definition
file jquery.d.ts, for example here: https://github.com/borisyankov/DefinitelyTyped#readme

4] Compile to javascript
using command tsc:

tsc hello.tsc

5] Inspect javascript file
A javascript file hello.js is generated

see javascript file

6] Create html page
Now we can use the javascript in a html page:

see html file

7] Result
Result should be: ‘hallo bert’

Complete code: