November 16

External Network Access to Kestrel in ASP.NET Core

Yesterday I gave a talk at a local user group and I ran into some networking issues with my demo. After some searching for a bit, I found the solution in this blog post: External Network Access to Kestrel and IIS Express in ASP.NET Core.

The missing command that I could not find yesterday is as follows:
dotnet run --urls http://0.0.0.0:5001

By running that command before you run your ASP.NET Core app, it will allow you to override the app's default URLs.

Category: ASP.NET Core | Comments Off on External Network Access to Kestrel in ASP.NET Core
August 7

Task From A Code Test

Earlier this week I took a coding test and the first task in the test was interesting and alittle fun to complete. At the start you are given a text file with integers (one per line) that are used as an input into another process. This process has been failing because of problems with the input file. You are tasked with writing a program to validate the input files and output any errors to a separate file for use in troubleshooting. The task is to validate the file according to a set of rules.

The rules are as follows:
1.Verify that all integers in the file fall between 1 and N where N is the total number of lines in the text file.
2.Verify that all integers between 1 and N exist in the file (So if the file contains 3 lines, they should be 1, 2, and 3 in any order).
3.Output any errors to another file.

Rather than use a bunch of loops directly to iterate through the lines, I opted for a LINQ approach. Having done LINQ for so long, that approach usually looks better to me than writing the loops directly. The code is on GitHub and is available by clicking here.

Category: C#, LINQ | Comments Off on Task From A Code Test
August 4

Rebooting & Blogging

I had originally created this blog years ago and tried to get into blogging. I got a few posts up but then kind of lost interest when life started happening. So when I was recently and unexpectedly given an opportunity to "reboot" my career, I remembered some .NET Rocks! podcasts from the last year that addressed taking your carreer to the next level (Working on your Career with John Sonmez and Managing Your Career with John Sonmez). I decided to go check out his website SimpleProgrammer.com to see what I could find that might help me. One of the things I found was his online 3 week blogging course. I wasn't terribly motivated to blog, but I know blogging would help me and I decided to give it a shot. There are no silver bullets with this, but the course gives you a path forward to building or re-building your blog as the case may be. It turns out that is exactly what I needed to get going.

If you are looking to start a blog or just find something to help jumpstart your blog, I would recommend checking out John Sonmez's Blog Course.

Category: Uncategorized | Comments Off on Rebooting & Blogging
August 3

Registering Types With the SimpleIoC Container

I've been kicking the tires on the Command Query Seperation principle/pattern lately. I've been using the CQS-Sample as a starting point. So far, the approach to breaking things down into Commands and Queries is pretty slick and much easier to unit test. The interfaces are used for dependency injection with an IoC container like SimpleIoC (which comes with MVVMLight). If you have done any work with IoC containers, you'll know that you need to register your types with the container either explicitly or through some kind of convention. With a few classes it's easy to just bang out the few lines of code you need to do it. In this case, the number of commands and queries is growing and having to explicitly register each one is becoming monotonous. So how to I register my queries and commands without having to write any code to explicitly register my types?

Assumptions:

  1. We are working with MVVMLight and SimpleIoC.
  2. For any query or command processor interface there is exactly 1 implementation of it.
  3. All queries are marked with an IQuery interface.
  4. All commands are marked with an ICommand interface (not to be confused with the System.Windows.Input.ICommand).
  5. All command processors implement ICommandProcessor<TCommand> where TCommand is a class that inherits from ICommand.

Step 1: Get an instance of MethodInfo for SimpleIoC's Register<TInterface, TClass>() method.

Normally, getting the MethodInfo for a method you'd like to invoke is more straight forward. This method has 8 overloads so some LINQ was needed to get the correct one.

var registerMethodInfo = SimpleIoc.Default.GetType().GetMethods()
.Where(m => m.Name == "Register")
.Select(m => new
{
Method = m,
Params = m.GetParameters(),
Args = m.GetGenericArguments()
})
.Where(x => x.Params.Length == 0)
.Where(x => x.Args.Length == 2)
.Select(x => x.Method)
.First();

Step 2: Get a list of all types in the current AppDomain.

This step is pretty straightforward. Notice the .ToList() call at the end of method chain. This is to make sure that when we use types in the following steps, we won't be enumerating the IEnumerable of types more than once.

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).ToList();

Step 3: Get all query interfaces that inherit from IQuery.

var queryInterfaces = from t in types
where t != typeof (IQuery)
where t.IsInterface
where typeof (IQuery).IsAssignableFrom(t)
select t;

Step 4: Create a query implementation class to query interface mapping

This step creates the query interface to query type mapping. The result is projected into an anonymous type that will be easy to use in the next step.

var queryMappings = from queryInterface in queryInterfaces
from t in types
where t.GetInterface(queryInterface.Name) == queryInterface
select new {queryInterface, Query = t};

Step 5: Register the query types

This is the last bit of reflection needed to register the queries. This code iterates of the query mappings from the previous step, gets a generic MethodInfo using the interface and implementation, and then invokes it on the current SimpleIoC instance.

foreach (var queryMapping in queryMappings)
{
var genericRegisterMethodInfo = registerMethodInfo.MakeGenericMethod(queryMapping.queryInterface, queryMapping.Query);
genericRegisterMethodInfo.Invoke(SimpleIoc.Default, null);
}

Step 6: Get a list of classes that inherit from ICommand.

var commands = from t in types
where t != typeof (ICommand)
where typeof (ICommand).IsAssignableFrom(t)
select t;

Step 7: Make the ICommandProcessor<T> interfaces.

This is an interesting step in the process. The command processors do not have a common non-generic interface, so we'll have to make the generic type of ICommandProcessor<TCommand>.

 

var commandProcessorInterfaces = from command in commands
select new {CommandProcessorInterface = typeof (ICommandProcessor<>).MakeGenericType(command)};

Step 8: Map ICommandProcessor<T> interfaces to ICommandProcessor<T> implementations

Now we'll create the mapping between the ICommandProcessor<TCommand>s and their implementations.

var commandProcessorMappings = from commandProcessorInterface in commandProcessorInterfaces
from t in types
where t.GetInterface(commandProcessorInterface.CommandProcessorInterface.Name) == commandProcessorInterface.CommandProcessorInterface
select new {commandProcessorInterface.CommandProcessorInterface, CommandProcessor = t};

Step 9: Register the command processor types

Same thing as step 5. Just iterating over the command mappings to make the generic MethodInfos and then invoking them on the current SimpleIoC instance.

foreach (var commandProcessorMapping in commandProcessorMappings)
{
var genericRegisterMethodInfo = registerMethodInfo.MakeGenericMethod(commandProcessorMapping.CommandProcessorInterface, commandProcessorMapping.CommandProcessor);
genericRegisterMethodInfo.Invoke(SimpleIoc.Default, null);
}

And that's how I register all my command processors and queries through reflection. LINQ and Reflection FTW!

Are there better approaches? Sure. Are there better IoC containers out there? You betcha. But, this approach is Good Enough™ for now.

Category: C#, LINQ | Comments Off on Registering Types With the SimpleIoC Container
August 1

How to Detect Concurrent Events Using LINQ and Reactive Extensions

Here's the scenario...

I have 3 referees around a powerlifting platform. Each has a set of 4 switches in their hand that is used to indicate if they thought a lift was good or not. One switch indicates the lift was good and the other 3 indicate the lift was no good and the general reason why. A referee's light box displays the result by turning lights on and off. The individual lights should only turn on when all 3 referees have pushed their buttons. How do I determine when all 3 referees have pushed their buttons?

To get started, we need to create a simple event to indicate a referees decision.
public class RefereeDecisionEvent
{
public DateTimeOffset Timestamp { get; set; }
public DecisionCode Decision { get; set; }
}

The Decision property will hold a referee's decision represented as a DecisionCode enumeration.

public enum DecisionCode
{
White = 0,
Red = 1,
Blue = 2,
Yellow = 4
}

White indicates the referee decided it was a good lift. Red, Blue, and Yellow represent potential reasons why the referee decided the lift was no good.

We'll also need 3 event sources. Each event source represents a different referee; left, center, right. The actual implementation of the sources is outside the scope of this blog post. That said, I'll just generate some events for each source at different intervals to give us some simple test data.

Step 1 is to join the left source's events with the right source's events. Since the left and right event sources create new events at different intervals, the events will most likely not occur at exactly the same time. We can fix this by increasing the duration of both sequences of events by 3 seconds. Now, we are joining the events from the left and the right sources when they occur within 3 seconds of each other.

var step1 = leftSource.Join(rightSource,
l => Observable.Interval(TimeSpan.FromSeconds(3)),
r => Observable.Interval(TimeSpan.FromSeconds(3)),
(l, r) => new {Left = l, Right = r});

Step 2 is to join the center source's events with the now joined left and right side events. We'll extend the durations of the events 3 seconds so that we can get a combined event that shows the left, center, and right events that all occurred withing 3 seconds of each other.

var step2 = centerSource.Join(step1,
l => Observable.Interval(TimeSpan.FromSeconds(3)),
r => Observable.Interval(TimeSpan.FromSeconds(3)),
(l, r) => new {r.Left, Center = l, r.Right});

In Step 3, we'll project the results of step 2 into an event that is better laid out for our purposes. That Observable can then be subscribed to by an Observer that handles turning the lights on and off.

var step3 = from e in step2
select new
{
e.Left,
e.Center,
e.Right,
Status = new[] {e.Left.Decision, e.Center.Decision, e.Right.Decision}.Count(x => x == DecisionCode.White) >= 2 ? "Good" : "Bad"
};

And that's how it's done.

Category: C#, Reactive Extensions | Comments Off on How to Detect Concurrent Events Using LINQ and Reactive Extensions
July 27

Simplifying Switches Using Dictionaries

Have you ever had to write a long series of if/then statements or a giant switch statement that extends for a page or two of your code? Want an easy way to increase the readability of your code, increase it's maintainability index, and decrease it's cyclomatic complexity? Let's see an example problem and then a possible solution.

Let's start off by considering the following array of anonymous types:

var items = new[]
{
    new {Operation = Operation.Add, Value1 = 1, Value2 = 2},
    new {Operation = Operation.Subtract, Value1 = 4, Value2 = 3},
    new {Operation = Operation.Multiply, Value1 = 5, Value2 = 6},
    new {Operation = Operation.Divide, Value1 = 8, Value2 = 4},
    new {Operation = Operation.Add, Value1 = 9, Value2 = 10},
    new {Operation = Operation.Subtract, Value1 = 12, Value2 = 11},
    new {Operation = Operation.Multiply, Value1 = 13, Value2 = 14},
    new {Operation = Operation.Divide, Value1 = 16, Value2 = 4},
    new {Operation = Operation.Add, Value1 = 17, Value2 = 18},
    new {Operation = Operation.Subtract, Value1 = 6, Value2 = 3},
    new {Operation = Operation.Multiply, Value1 = 8, Value2 = 8},
    new {Operation = Operation.Divide, Value1 = 10, Value2 = 2}
};

I need to iterate over this array and execute the given Operation on Value1 and Value2 properties to produce a list of results A brute force method of doing this is as follows:

var results = new List<int>();
 
foreach (var item in items)
{
    switch (item.Operation)
    {
        case Operation.Add:
            results.Add(item.Value1 + item.Value2);
            break;
        case Operation.Subtract:
            results.Add(item.Value1 - item.Value2);
            break;
        case Operation.Multiply:
            results.Add(item.Value1*item.Value2);
            break;
        case Operation.Divide:
            results.Add(item.Value1/item.Value2);
            break;
        default:
            throw new ArgumentOutOfRangeException();
    }
}

The switch statement is pretty straightforward and simple to implement in this example. Visual Studio 2013 Code Analysis is giving the code a maintainability index of 54 and a cyclomatic complexity of 6. What if I needed more lines of code to handle each operation? This could turn into a mess to test, debug, and maintain.

A possible solution to this problem is to replace your switch with a dictionary. I realize that seems odd to replace a control statement with a data structure, but refactoring to this approach will simplify your code. In our example, each item in the array has an Operation to be performed on the Value1 and Value2 properties. I can setup my dictionary with the key value being the Operation enumeration, and the value being the Action, Func, or method group that performs the operation.

var operationMethods = new Dictionary<Operation, Func<int, int, int>>
{
    {Operation.Add, Add},
    {Operation.Subtract, Subtract},
    {Operation.Multiply, Multiply},
    {Operation.Divide, Divide}
};

In the example above, I'm using the following methods:

public int Add(int left, int right)
{
    return left + right;
}
 
public int Subtract(int left, int right)
{
    return left - right;
}
 
public int Multiply(int left, int right)
{
    return left*right;
}
 
public int Divide(int left, int right)
{
    return left/right;
}

With the dictionary approach, our code to iterate over the items and execute the individual operations looks like this:

var results = new List<int>();
 
foreach (var item in items)
{
    results.Add(operationMethods[item.Operation].Invoke(item.Value1, item.Value2));
}

VS2013 gives the refactored code a maintainability index of 63 and a cyclomatic complexity of 2. Our code is still doing the same thing as the switch was, but we have broken the code down to simpler pieces that are more readable and more easily to wrap unit tests around.

I find this to be a good approach to take when the "cases" of our switch statement are known up front (such as using an enumeration). If it is possible that you will not have all the cases or keys in the dictionary, you can still use this approach but you will want to handle things more gracefully with the Dictionary's TryGetValue method like so:

Func<int, int, int> operation;
 
if (operationMethods.TryGetValue(item.Operation, out operation))
{
    results.Add(operation(item.Value1, item.Value2));
}
else
{
// TODO: Handle case of the missing case/key
}

To tie it all together, here is a Gist with the code I discussed in this post.

I hope this helps. If you have any questions or comments, please use the comments form below. Thanks.

Category: C# | Comments Off on Simplifying Switches Using Dictionaries
December 28

How To Enable Windows Authentication When Using IISExpress

Back in early October, my employer temporarily assigned me to a project to replace an existing Access-based application. After initial meetings with the client, it was decided that an ASP.NET MVC 4 and SQL Server 2008 solution would be the best way to deliver what the client was looking for while also removing many of the rough edges from the legacy application. One thing I like about building intranet applications is that your client has standardized on a particular browser. In this case it is IE8+. Since the users of the web application will all be connected to the client’s Active Directory, we decided to use that for authentication. I would have liked to also manage roles/groups through AD as well, but that was shot down.

Fast forward to the end of December and my employer has hired a new resource to take over the work. The new resource downloads all the source code on to his freshly re-paved laptop, opens up Visual Studio 2012 and attempts to start the application. The code builds fine, the web browser pops up, and then an exception with the following message is thrown:

Trust relationship between the primary domain and trusted domain failed

By default, IISExpress has Windows Authentication turned off. To turn it on, we need to add the following code to the bottom of the “\My Documents\IISExpress\config\applicationhost.config” file.

   1:  <location path="MyWebsite">
   2:      <system.webServer>
   3:          <security>
   4:              <authentication>
   5:                  <anonymousAuthentication enabled="false" />
   6:                  <windowsAuthentication enabled="true" />
   7:              </authentication>
   8:          </security>
   9:      </system.webServer>
  10:  </location>

Now, you will need to change the path attribute on the location element to match the name of your website. In this case, my website’s URL is “http://localhost:5439/MyWebsite/”. Next you can tweak the authentication elements to work the way you need them to. In this case, I only want authenticated users to allowed access to the website.

Once these changes were made on the new resources laptop, he was up and running. This occupied some of my time the other day to figure out what was going on and this blog post is here to serve as a reminder to me and maybe other people who are having the same issue.

Category: Uncategorized | Comments Off on How To Enable Windows Authentication When Using IISExpress
June 19

Using C# extension methods with Microsoft StreamInsight

Many times when working with different APIs we find some functionality that is useful but often times tedious to get at. A couple examples that come to mind are accessing OSI PI data (it comes back in a series of jagged arrays forcing you to have to check for null, etc) and Microsoft StreamInsight diagnostic views. Since we don't have access to the original code to make the changes directly to the API, one of the best ways to extend it is to use extension methods. Sometimes we forget that we have this tool in the toolbox. I came across a good blog post from the DevBiker called A couple of helpful StreamInsight Query extension methods. There are a couple of extension methods in there that smooth out some of the rough edges when dealing with StreamInsight's Query object.

Category: Microsoft StreamInsight | Comments Off on Using C# extension methods with Microsoft StreamInsight