Part 1: Publish to an Azure DevOps Repository

In this series I’m going to use the free Visual Studio 2017 Community Edition and the free Azure DevOps to target a full-blown CI/CD pipeline to deploy a web application to Azure.  So in addition to those tools make sure you have an Azure subscription. Last, I’ve got the latest Git for Windows installed (v2.19.1.windows.1). So let’s get started after the jump.

Continue reading “Part 1: Publish to an Azure DevOps Repository”

ASP.NET Core 2.1 Web API Using Multiple Authentication Schemes

There’s very little guidance from Microsoft on writing your own custom authentication handlers for Core 2. If you look at the documentation you’ll find detailed guidance on the built-in Core Identity model that they want you to use. They also provide links to third-party open-source providers like Identity Server which is what I use in this example. There is an article on custom cookie authentication. But generally speaking because security is hard and it’s way too easy to screw up Microsoft would rather you did not roll your own. It’s best to stick to the prescriptive guidance Microsoft offers. Now that I’ve said that I’m going to ignore completely my own advice. Read on if you’re with me.

Continue reading “ASP.NET Core 2.1 Web API Using Multiple Authentication Schemes”

Microservices with IdentityServer4 and Ocelot Fronting a .NET Core API

Well just like the title says I want to show a complete microservice-based architecture using the lightweight IdentityServer4 for authentication and Ocelot as an API gateway. Ocelot will act as a reverse proxy for a secured internal ASP.NET Core Web API. Everything here is open-source .NET Core 2.0 or later.

The main source of guidance I consulted for this architecture is the eShopContainers project and the white paper they published (which I read cover-to-cover at my favorite coffee shop and I recommend you do the same). There are a few helpful blog posts out there too. Dan Patrascu-Baba wrote a couple posts (here and here), Scott Brady wrote a helpful intro to IdentityServer4, and Catcher Wong wrote a nice series on Ocelot. But I couldn’t find a “complete picture” presentation of the whole architecture so I decided to write it myself. My goal here is to present a bare bones framework in one place to help bootstrap a serious microservices project.

I’ve organized this post into three parts: (1) The Big Picture; (2) The Configuration; and (3) The Deep Dive. Let’s get started right after the jump…

Continue reading “Microservices with IdentityServer4 and Ocelot Fronting a .NET Core API”

A Simple CQRS Pattern Using C# in .NET

For years in my apps I’ve used a Data Mapper pattern or even the Repository pattern to mediate between the business domain and the database. One thing I’ve learned is that something like this interface is no help at all:

public interface IEntity
{
    int ID { get; set; }
}

public interface IRepository where T : IEntity
{
    T Get(int id);
    IEnumerable GetAll();
    int Add(T item);
    bool Update(T item);
    bool Delete(T item);
}

In all but the most trivial app it proves too inflexible to be useful. This is because no two entities are alike. In one case calling a Get() function and passing in an ID is just fine. But I might have a two-part key for another entity. Or I might need GetByLastName() instead. So I end up adding extra functions to the concrete repository class. But If I’m adding functions outside the contract then I might as well not use the contract at all. Another problem with a non-trivial app is the repository even for a single entity quickly becomes a big ball of mud (if you’re lucky) or a God class if several developers are working together and there’s no discipline. If I have to wade through 30 fetch functions to get to the one I want that’s not maintainable. There are other growing pains that emerge a few years down the road. But others — notably Ayende — have documented those problems so I won’t rehash that here. Instead I want to describe a simple CQRS pattern as an alternative that I’ve found to be flexible and maintainable over the long haul.

Continue reading “A Simple CQRS Pattern Using C# in .NET”

Polymorphic Associations in Entity Framework

In this post I’m going to show how to use EF 6.1 Code First to model polymorphic associations between a base class and two derived classes. In EF this is called “table-per-type” (TPT) inheritance. Microsoft has a walkthrough on using EF to map TPT inheritance in a domain model. Unfortunately it was written before EF Code First and is now dated. A search turned up some information here and there but it too was dated. It took me the better part of an afternoon to get it working in EF Code First so I thought I should post the solution. More after the jump…

Continue reading “Polymorphic Associations in Entity Framework”

AuthorizationAttribute with Windows Authentication in MVC 4

With MVC 4 the Visual Studio team released the SimpleMembershipProvider. I’ve used it and I’m not so sure “simple” is the word I’d use for it. 🙂 In any case it works great for a forms authentication scenario. And if you really want to deep dive into it I highly recommend Long Le’s blog. My solution is after the jump…

Continue reading “AuthorizationAttribute with Windows Authentication in MVC 4”

Generics and Nullable Types

It is often useful in OR mapping to analyze a value type that might be null prior to setting it in a business entity. For instance, SqlDateTime type (in System.Data.SqlTypes namespace) is a value type that is nullable. You can call IsNull to check and Value to retrieve the underlying DateTime type:

SqlDateTime d = new SqlDateTime();
if (d.IsNull)
{
    Trace.WriteLine("SqlDateTime is null");
}

d = DateTime.Now;
Trace.WriteLine(string.Format("SqlDateTime is {0}", d.Value.ToString()));

This is useful when fetching data from SQLServer. DataSets allow nullable values but strongly-typed classes do not. So if I’m instantiating a business entity, I often call TryParse first to protect against null:

//instantiate SqlCommand cm here
SomeBusinessEntity obj = new SomeBusinessEntity();
DateTime dt = new DateTime();
SqlDataReader dr = cm.ExecuteReader();
if (dr != null) 
{
    while (dr.Read()) 
    {
        obj.ID = (DBNull.Value != dr["ID"]) ? Convert.ToInt32(dr["ID"]) : 0;
        if (DateTime.TryParse(dr["ApprovalDate"].ToString(), out dt))
        obj.ApprovalDate = dt;
    }
}

Wouldn’t it be great to have a DateTime struct in C# that allows for null? A bunch of folks have gnashed their teeth over this issue since the release of .NET. And now .NET Framework 3.0 supports nullable value types. But I’m still in 2.0 land and will likely remain there for some time so here’s my solution. The goal is to support both the above OR mapping logic via generics and to emulate the nullable feature of the SqlDateTime type. In the end we want to do something like this:

Nullable ndt = new Nullable();
if (Nullable.TryParse(DateTime.Now.ToString(), out ndt))
{
    obj.ApprovalDate = ndt;
}

We start with a basic generics-enabled struct with exposed properties Value and IsNull:

public struct Nullable 
{
    private static bool _isnull;
    private T _value;

    static Nullable() 
    {
        _isnull = true;
    }

    public bool IsNull 
    {
        get { return _isnull; }
    }

    public T Value 
    {
        get { return _value; }
        set 
        {
            _value = value;
            _isnull = false;
        }
    }
}

The struct has a private _isnull member which is set to true in the static constructor. Only when the value is set does that flag flip to false. So by default it will be null even if the type is not really null; for instance if the underlying DateTime is initialized at 1/1/0001 or the underlying Int32 is initialized at 0. Now we support the TryParse functionality by adding a delegate function that mimics the signature. Note that I’m not supporting the overloaded method for IFormatProvider but rather keeping it simple:

private delegate bool TryParseDelegate(string s, out T result);

Then add a private static function to do the work:

private static bool ParseNullable(string s, out Nullable result, TryParseDelegate Parse) where T : struct 
{
    if (string.IsNullOrEmpty(s)) 
    {
        result = default(Nullable);
        return false;
    }
    else 
    {
        T t;
        bool success = Parse(s, out t);
        Nullable n = new Nullable();
        n.Value = t;
        result = n;
        return success;
    }
}

At this point it’s just a matter of adding public methods for each type that you need to support. I’ve added two methods, one for DateTime and one for Int32. Here is the complete Nullable struct:

public struct Nullable 
{
    private static bool _isnull; 
    private T _value;
    private delegate bool TryParseDelegate(string s, out T result);

    static Nullable() 
    {
        _isnull = true;
    }

    public bool IsNull 
    { 
        get 
        { 
            return _isnull; 
        }   
    }

    public T Value 
    {
        get 
        {           
           return _value;       
        }
        set 
        {
            _value = value;
            _isnull = false;
        }
    }

    public static bool TryParse(string s, out Nullable result) 
    {
        return ParseNullable(s, out result, Int32.TryParse);
    }

    public static bool TryParse(string s, out Nullable result) 
    {
        return ParseNullable(s, out result, DateTime.TryParse);
    }

    private static bool ParseNullable(string s, out Nullable result, TryParseDelegate Parse) where T : struct 
    {
        if (string.IsNullOrEmpty(s)) 
        {
            result = default(Nullable);
            return false;
        }
        else 
        {
            T t;
            bool success = Parse(s, out t);            
            Nullable n = new Nullable();            
            n.Value = t;
            result = n;
            return success;
        }
    }
}

To exercise the struct:

class Program 
{
    static void Main(string[] args) 
    {
        // exercise Nullable with type DateTime
        Nullable ndt = new Nullable();
        Console.WriteLine(string.Format("Is null? {0}", ndt.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", ndt.Value.ToString()));
        
        ndt.Value = DateTime.Now;

        Console.WriteLine(string.Format("Is null? {0}", ndt.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", ndt.Value.ToString()));
        Console.WriteLine();

        // exercise Nullable with type Int32
        Nullable nint = new Nullable();
        Console.WriteLine(string.Format("Is null? {0}", nint.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", nint.Value.ToString()));
        nint.Value = 42;

        Console.WriteLine(string.Format("Is null? {0}", nint.IsNull.ToString()));
        Console.WriteLine(string.Format("Value is {0}", nint.Value.ToString()));

        // exercise TryParse functionality
        if (Nullable.TryParse(DateTime.Now.ToString(), out ndt)) 
        {
            Console.WriteLine(string.Format("Successful TryParse with result {0}", ndt.Value.ToString()));
        }

        if (Nullable.TryParse("99", out nint)) 
        {
            Console.WriteLine(string.Format("Successful TryParse with result {0}", nint.Value.ToString()));
        }

        Console.ReadKey();
    }
}