Angular LogService decorator in Typescript

Tested with AngularJS 1.5.x and Chrome 48.

 
export class CustomLogService implements ng.ILogService{
 
    constructor(private $delegate: ng.ILogService) {
    }
 
    public debug: ng.ILogCall = (...args: any[]): void => {
        this.$delegate.debug.apply(this, args);
    }
 
    public error: ng.ILogCall = (...args: any[]): void => {
        this.$delegate.error.apply(this, args);
    }
 
    public info: ng.ILogCall = (...args: any[]): void => {
        this.$delegate.info.apply(this, args);
    }
 
    public log: ng.ILogCall = (...args: any[]): void => {
        this.$delegate.log.apply(this, args);
    }
 
    public warn: ng.ILogCall = (...args: any[]): void => {
        this.$delegate.warn.apply(this, args);
    }
}
 
[...]
 
app.config(["$provide", ($provide: ng.auto.IProvideService) => {
    $provide.decorator('$log', ["$delegate", ($delegate: ng.ILogService) => {
        return new CustomLogService($delegate);
    }]);
}]);   
 
[...]

Minimal sample: Self hosted Nancy using Owin, Unity bootstrapper including xUnit test

Note: Depending on your environment, you might need to make a name space reservation

netsh http add urlacl url=http://+:8080/ user=DOMAIN\username

See also Hosting Nancy with Owin for more details.

Programm.cs

using Microsoft.Owin.Hosting;
 
namespace NancyOwinBox
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "http://+:8080";
 
            using (WebApp.Start(url))
            {
                Console.WriteLine("Running on {0}", url);
                Console.WriteLine("Press enter to exit");
                Console.ReadLine();
            }
        }
    }
}

HomeModule.cs

using Nancy.Owin;
 
namespace NancyOwinBox
{
    public class HomeModule : NancyModule
    {
        public HomeModule(IMessageHelper messageHelper)
        {
            Get["/"] = x =>
            {
                var env = this.Context.GetOwinEnvironment();
                return string.Format(messageHelper.HelloWorld());
            };
        }
    }
}

Startup.cs

using Microsoft.Practices.Unity;
using Nancy.Owin;
using Owin;
 
namespace NancyOwinBox
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            IUnityContainer container = new UnityContainer();
 
            container.RegisterType<IMessageHelper, MessageHelper>();
 
            app.UseNancy(new NancyOptions
            {
                EnableClientCertificates = true,
                Bootstrapper = new NancyOwinBoxBootstrapper(container)
            });
        }
    }
}

NancyOwinBoxBootrapper.cs

using Microsoft.Practices.Unity;
using Nancy.Bootstrappers.Unity;
 
namespace NancyOwinBox
{
    public class NancyOwinBoxBootstrapper : UnityNancyBootstrapper
    {
        private IUnityContainer _container;
 
        public NancyOwinBoxBootstrapper(IUnityContainer container)
        {
            _container = container;
        }
 
        protected override IUnityContainer GetApplicationContainer()
        {
            return _container;
        }
    }
}

xUnit 2.x test file: NancyOwinBoxTests.cs

using Microsoft.Practices.Unity;
using Nancy;
using Nancy.Testing;
using Xunit;
 
namespace NancyOwinBox.Testing
{
    public class NancyOwinBoxTests
    {
        [Fact]
        public void ShouldGetHomeScreen() {
 
            IUnityContainer container = new UnityContainer();
 
            container.RegisterType<IMessageHelper, MessageHelper>();
 
            NancyOwinBoxBootstrapper bootstrapper = new NancyOwinBoxBootstrapper(container);
 
            var browser = new Browser(bootstrapper);
 
            var result = browser.Get("/", with =>
            {
                with.HttpRequest();
            });
 
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
 
            Assert.True(true);
        }
    }
}

package.config – NancyOwinBox

<packages>
  <package id="CommonServiceLocator" version="1.0" targetFramework="net45" >
  <package id="Microsoft.Owin" version="3.0.1" targetFramework="net45" >
  <package id="Microsoft.Owin.Host.HttpListener" version="3.0.1" targetFramework="net45" >
  <package id="Microsoft.Owin.Hosting" version="3.0.1" targetFramework="net45" >
  <package id="Nancy" version="1.1" targetFramework="net45" /&gt;
  <package id="Nancy.Bootstrappers.Unity" version="1.1" targetFramework="net45" >
  <package id="Nancy.Owin" version="1.1" targetFramework="net45" >
  <package id="Owin" version="1.0" targetFramework="net45" >
  <package id="Unity" version="2.1.505.0" targetFramework="net45" >
</packages>

package.config. NancyOwinBox.Testing

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="CsQuery" version="1.3.3" targetFramework="net45" />
  <package id="Nancy" version="1.1" targetFramework="net45" />
  <package id="Nancy.Bootstrappers.Unity" version="1.1" targetFramework="net45" />
  <package id="Nancy.Testing" version="1.1" targetFramework="net45" />
  <package id="Unity" version="3.5.1404.0" targetFramework="net45" />
  <package id="xunit" version="2.0.0" targetFramework="net45" />
  <package id="xunit.abstractions" version="2.0.0" targetFramework="net45" />
  <package id="xunit.assert" version="2.0.0" targetFramework="net45" />
  <package id="xunit.core" version="2.0.0" targetFramework="net45" />
  <package id="xunit.extensibility.core" version="2.0.0" targetFramework="net45" />
  <package id="xunit.runner.visualstudio" version="2.0.0" targetFramework="net45" />
</packages>

Download sample solution including all sources:
NancyOwinBox.zip – Visual Studio 2013

Output text to console, xUnit 2.x / Visual Studio 2013

Latest version of xUnit (2.x) eats up any Debug/Trace messages. Use ITestOutputHelper to log to the output section of the test result pane.

using Xunit;
using Xunit.Abstractions;
 
namespace XUnitTestBox
{
    public class OutputTest
    {
        private readonly ITestOutputHelper _output;
 
        public OutputTest(ITestOutputHelper output)
        {
            _output = output;
        }
 
        [Fact]
        public void MethodWithSomeOutputTest()
        {
            _output.WriteLine("Some dummy output text");
            Assert.True(true);
        }
    }
}

Add a document to ElasticSearch using NEST and PowerShell

Create the PowerShell script addperson.ps1. Make sure you have the necessary DLLs for NEST, Elasticsearch.NET and Newtonsoft.Json on hand.

addperson.ps1:

[Reflection.Assembly]::LoadFile("C:\estest\Nest.dll")
[Reflection.Assembly]::LoadFile("C:\estest\Elasticsearch.Net.dll")
[Reflection.Assembly]::LoadFile("C:\estest\Newtonsoft.Json.dll")
 
$uri = New-Object System.Uri("http://localhost:9200");
$settings = New-Object Nest.ConnectionSettings($uri, "acme");
$client = New-Object Nest.ElasticClient($settings);
 
Add-Type -Language CSharp @"
public class Person
{
    public string Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string City {get;set;}
}
"@;
 
$person = new-object Person;
$person.Id = "1";
$person.Firstname = "Alan";
$person.Lastname = "Smithee";
$person.City = "Arakis";
 
$indexRequest = new-object "Nest.IndexRequest[Person]"($person);
 
$index = $client.Index($indexRequest);

Usage:

1. Open a PowerShell
2. execute

> powershell .\addperson.ps1

Note: Run the script in its own application context otherwise you have to re-open a new PowerShell window after changes to the person contract.

Check whether a polygon is complex for Unity3D/C#

Story: A player in a game shall dynamically create a fence by placing some poles.

complexA wire is attached to the poles from the very beginning. To avoid any intersections of the wire, the polygon (fence) built by the poles must be either convex or concave. The situation of a complex polygon must be avoided, otherwise it will lead into a short circuit.

Using the Faster Line Segment Intersection algorithm from a previous post, the implementation is rather simple by checking all connections for intersections.

static bool IsPolygonComplex(Vector2[] polygon) {
 
    for (int i = 0; i < polygon.Length - 2 ; i++) {
 
        int n = i + polygon.Length - 2;
 
        if (i >= 2) {
            n -= (i - 1);
        }
 
        for (int j = i + 2; j <= n; j++)  {
            if (FasterLineSegmentIntersection(polygon[i], polygon[i+1], polygon[(j)%polygon.Length], polygon[(j+1)%polygon.Length])) {
                return true;
            }
        }
    }
 
    return false;
}

Note: It’s very possible, that this rather empirical solution is not the optimal algorithm. So if you know it, please drop a note.

 

See also : Complex Polygons on Wikipedia.

Faster Line Segment Intersection for Unity3D/C#

This method tests whether two lines are intersecting each other. The code is based on the algorithm described by

Faster Line Segment Intersection
Franklin Antonio, Graphics Gems III, 1992, pp. 199-202
ISBN: 0-12-409673-5

The implementation tests only the intersection and will not calculate any possible intersection point.

static bool FasterLineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) {
 
    Vector2 a = p2 - p1;
    Vector2 b = p3 - p4;
    Vector2 c = p1 - p3;
 
    float alphaNumerator = b.y*c.x - b.x*c.y;
    float alphaDenominator = a.y*b.x - a.x*b.y;
    float betaNumerator  = a.x*c.y - a.y*c.x;
    float betaDenominator  = alphaDenominator; /*2013/07/05, fix by Deniz*/
 
    bool doIntersect = true;
 
    if (alphaDenominator == 0 || betaDenominator == 0) {
        doIntersect = false;
    } else {
 
        if (alphaDenominator > 0) {
            if (alphaNumerator < 0 || alphaNumerator > alphaDenominator) {
                doIntersect = false;
            }
        } else if (alphaNumerator > 0 || alphaNumerator < alphaDenominator) {
            doIntersect = false;
        }
 
        if (doIntersect && betaDenominator > 0) {
            if (betaNumerator < 0 || betaNumerator > betaDenominator) {
                doIntersect = false;
            }
        } else if (betaNumerator > 0 || betaNumerator < betaDenominator) {
            doIntersect = false;
        }
    }
 
    return doIntersect;
}