Category Archives: Programming

fuslogvw, how could I forget you?

This is one of those reminder’s to myself…

Don’t forget that you can use fuslogvw to find problems loading assemblies.

Why do I need reminding?

I had an issue whereby a release build of an application I was working on had been configured for live/prod for the first time and somebody went to test the application which simply failed at start-up – just displaying a Windows dialog asking whether I wanted to close or debug the application.

Ofcourse, the application worked perfectly on my machine and oddly the non-prod versions also worked fine on the other user’s machine. However the live/prod release had one change to the previous build. A new feature had been removed which wasn’t ready to go live and unbeknown to me, the removal of it’s project caused the build to deploy older versions of a couple of DLL’s as part of the new live/prod build.

On my machine this wasn’t an issue as .NET located the newer versions of the DLL’s, on the other user’s machines these could not be located.

This is fine, it was all part of pre-release testing cycle but a little confusing as all the non-prod configurations worked fine on other user’s machines.

When do we get to fuslogvw?

I haven’t had the need to use fuslogvw for ages, but really should probably use it a lot more. To be honest, it makes sense to have it on all the time to catch such potential issues.

What fuslogvw can do is list any failures during start-up of a .NET application. Running fuxlogvw.exe from the Windows SDK folder (for example C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools) will result in the fuslog UI being displayed. As you might have guessed from the name the fus-log-vw is a viewer for the fusion log files.

Note: You must run fuslogvw as Admin if you want to change the settings, i.e. set the path of the log files, change the level of loggin, i.e. I just wanted to log all the bind failures, etc.

Leave fuslogvw open and then run the .NET application you’re wanting to take a look at. Now you’ll need to press the Refresh button on fuslogvw to see the logs after the application has started and depending on what you are logging you may see either a list of assemblies that were loaded (for example when just logging everything) or see failures etc.

We can now see what assembly and what version of that assembly the application (we’re monitoring) tried to load and we can inspect the log itself for more information on the failure (via the log file or the fuslogvw).

It’s as simple as that.

Where to store your application data?

Actually I don’t intend to answer the question “Where to store your application data?” because this will depend on your requirements, but what this post will look at is, some of the options available and hopefully help shed light on what best suits your application.

Application data can be separated into two types, user specific data and application specific data (or if you prefer “All User” data).

Obviously multiple user’s might have access to a single machine but an application may be available to all users of a machine, hence we need a way to store settings specific to each user on the machine, for example user preferences. However we also may have application specific data, maybe the application stores a list of URL’s specific, in essence global settings.

Let’s look at some of our options for storing data…

Within your application’s folder

Obviously we could simply store configuration data etc. along with the application, one way to locate this folder is, as follows

var folder = Path.GetDirectoryName(
   Assembly.GetExecutingAssembly().Location) +
   Path.DirectorySeparatorChar + 
   SettingsFileName;

Here we might store a file for application specific data then create another file using the username (here we can use the Environment.UserName) of the user logged into the machine for each user.

This is a simple solution and in some cases more than adequate, plus it has the benefit that if we delete the application (i.e. it wasn’t installed via an installer) then we delete any configuration files.

Program Data

The ProgramData folder is on the system drive and is hidden by default (see C:\ProgramData). As can be inferred from the name, it’s generally used for settings specific to the application itself, i.e. not based upon specific users on a machine.

We can access it using the following code

var folder = Path.Combine(
   Environment.GetFolderPath(
      Environment.SpecialFolder.CommonApplicationData),
      "YourAppName");

Interestingly you can access the ProgramData using C:\Users\AllUsers in File Explorer, although File Explorer will state that you are in C:\Users\AllUsers it’s the same folder as C:\ProgramData.

Program Data can also be located using the environment variable %programdata%.

User Data

So we’ve seen that we can use the Environment.UserName to combine with our file name to create user files, but Windows already has the capability locations for user data. Plus, depending how your OS is set up, this data may be used across any machine a user logs into (known as Roaming).

The default location for the following “User Data” folders is under the location C:\Users\<username>\AppData

Local

The Local folder can be located using the special folder LocalApplicationData, for example

var folder = Path.Combine(
   Environment.GetFolderPath(
      Environment.SpecialFolder.LocalApplicationData),
      "YourAppName");

and is also available via the environment variable %localappdata%.

This location contains data that cannot be stored in the Roaming folder, for example data that’s specific to the machine the user is logged into or that is too large to store in a synchronized roaming folder (i.e. where Roaming folders are synchronized with a server).

Roaming

As hinted at in the section on the Local folder. The Roaming folder can be synchronized with a server, i.e. this is a profile which is accessible from other machines that a user logs into on the same domain. Hence anything stored here will “follow” the user around and so is very useful for preferences, favourites etc. However the space available may be limited depending upon quota settings or other space limitations.

To access this folder we simply use the ApplicationData special folder or environment variable %appdata%, for example

var folder = Path.Combine(
   Environment.GetFolderPath(
      Environment.SpecialFolder.ApplicationData),
      "YourAppName");

LocalLow

The LocalLow folder is basically a restricted version of the Local folder. The data is not synchronized with a server and hence does not move from the machine its created on and it has a lower level of access.

When I say “restricted” or “lower level access” basically this means the application being run, itself has security constraints placed upon it.

The LocalLow folder does not have an entry within the SpecialFolder enumeration, so access the folder you need to use the following (copied from Thomans Levesque’s answer on StackOverflow – https://stackoverflow.com/questions/4494290/detect-the-location-of-appdata-locallow)

[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath(
   [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, 
   uint dwFlags, 
   IntPtr hToken, 
   out IntPtr pszPath);

public static string GetFolderLocalLow()
{
   var pszPath = IntPtr.Zero;
   try
   {
      var hr = SHGetKnownFolderPath(folderGuid, 0, IntPtr.Zero, out pszPath);
      if (hr < 0)
      {
         throw Marshal.GetExceptionForHR(hr);
      }
      return Marshal.PtrToStringAuto(pszPath);
   }
   finally
   {
      if (pszPath != IntPtr.Zero)
      {
         Marshal.FreeCoTaskMem(pszPath);
      }
   }
}

Accessing location via the environment variables

In a few places I’ve shown the environment variable for each of the locations mentioned. We can also use these variables to locate the folders, for example

var location = 
   Environment.ExpandEnvironmentVariables("%AppData%")

This will result in returning the Roaming folder location, but what’s nice is this static method will work with environment variables combined with file locations (as you’d probably expect), so for example

var location = 
   Environment.ExpandEnvironmentVariables("%AppData%\MyApp")

This will return a path along the lines C:\Users\<username>\AppData\Roaming\MyApp

Source added to https://github.com/putridparrot/blog-projects/tree/master/FileLocations

The WPF Hyperlink

WPF comes with a HyperLink class, but it’s from the System.Windows.Documents namespace, so is mean’t to be embedded within a textual control, such as a TextBlock (i.e. it’s not a standalone control like the System.Windows.Forms.LinkLabel) and within WPF it doesn’t support opening the supplied Uri in an associated process.

Let’s see it’s usage in some XAML

<TextBlock>
   <Hyperlink NavigateUri="http://putridparrot.com/blog/the-wpf-hyperlink">
   The WPF Hyperlink
   </Hyperlink>
</TextBlock>

This XAML will display a the text “The WPF Hyperlink” with underline and when you move your mouse over the link it’ll change colour and the mouse cursor will change to the hand cursor, but clicking on the link will not result in any web browser (or other associated application opening). We must implement such functionality ourselves either responding to the Click event or supplying an ICommand to the Command property.

Here’s a simple example of the sort of code we’d use to running the Uri via it’s associated application.

var process = new Process
{
   StartInfo = new ProcessStartInfo(Uri)
};
process.Start();

We can use databinding to supply the NavigateUri in the standard way, but if you wanted to change the displayed text, then we need to embed another control into the Hyperlink. For example, here we’re using another class from the System.Windows.Documents namespace, the Run class

<TextBlock>
   <Hyperlink NavigateUri="{Binding Uri}">
      <Run>
         <Run.Text>
            <Binding Path="DisplayText"/>
         </Run.Text>
      </Run>
   </Hyperlink>
</TextBlock>

Turning XAML into objects using XamlReader

I couldn’t come up with a good title for this post, basically the post is about taking a XAML declared Style and finding the easiest way to turn this into a Style object in code.

I had a problem whereby I ended up with multiple style objects which were exactly the same except for the DataItem they were binding to. This ended up meaning I had lots of duplicate XAML code, apart from one difference. Once I started making the code more dynamic (it was adding columns to the Infragistics XamDataGrid) this XAML became almost useless as I needed to create a style for each dynamically added column and hence really need to generate the Style in code.

If you’ve done anything much with code behind for such things as creating Style objects or replicating XAML code you’ve probably found the code doesn’t always map directly to the XAML, and if you already have XAML that works, why not simply reused it.

Note: The reason the code doesn’t always map is that it includes resources, converters and other XAML magically things that are automatically applied, for example converting colour names to colour values, or field lengths etc.

So let’s simple copy our XAML into a string in code and then programmatically change the DataItem field and then generate our Style object from this.

Here’s an example of the XAML as a string

var styleString = 
   "<Style TargetType=\"{x:Type idp:CellValuePresenter}\">" +
   "<Setter Property=\"Template\">" +
   "<Setter.Value>" +
   "<ControlTemplate>" +
   "<Grid>" +
   "<ListBox ItemsSource=\"{Binding DataItem." + source + "}\">" +
   "<ListBox.ItemTemplate>" +
   "<DataTemplate>" +
   "<TextBlock HorizontalAlignment=\"Stretch\" Text=\"{Binding}\"/>" +
   "</DataTemplate>" +
   "</ListBox.ItemTemplate>" +
   "<ListBox.ItemsPanel>" +
   "<ItemsPanelTemplate>" +
   "<StackPanel Orientation=\"Vertical\"/>" +
   "</ItemsPanelTemplate>" +
   "</ListBox.ItemsPanel>" +
   "</ListBox>" +
   "</Grid>" +
   "</ControlTemplate>" +
   "</Setter.Value>" +
   "</Setter>" +
   "</Style>";

In the above we’d obviously supply the source variable and this will then form part of our XAML style. To turn this into a Style object we need to use the XamlReader.Parse method. Before we can use the XamlReader.Parse method we also need to create the namespaces (context items) that we would expect from our XAML code, in this case we create a ParseContent object and assign our namespaces, then pass this into the XamlReader.Parse method also with the styleString. Our code might look like the following

public Style CreateStyle(string source)
{
   var context = new ParserContext();
   context.XmlnsDictionary.Add
   ("", 
    "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
   context.XmlnsDictionary.Add
   ("x", 
    "http://schemas.microsoft.com/winfx/2006/xaml");

   // other namespaces for XamaDataGrid etc.

   var styleString = 
      "<Style TargetType=\"{x:Type dataPresenter:CellValuePresenter}\">" +
      "<Setter Property=\"Template\">" +
      "<Setter.Value>" +
      "<ControlTemplate>" +
      "<Grid>" +
      "<ListBox ItemsSource=\"{Binding DataItem." + source + "}\">" +
      "<ListBox.ItemTemplate>" +
      "<DataTemplate>" +
      "<TextBlock HorizontalAlignment=\"Stretch\" Text=\"{Binding}\"/>" +
      "</DataTemplate>" +
      "</ListBox.ItemTemplate>" +
      "<ListBox.ItemsPanel>" +
      "<ItemsPanelTemplate>" +
      "<StackPanel Orientation=\"Vertical\"/>" +
      "</ItemsPanelTemplate>" +
      "</ListBox.ItemsPanel>" +
      "</ListBox>" +
      "</Grid>" +
      "</ControlTemplate>" +
      "</Setter.Value>" +
      "</Setter>" +
      "</Style>";

   return (Style)XamlReader.Parse(styleString, context);
}

That’s it – much simpler that create each piece of the Style using C# objects and allows us to first test our XAML out then reused it to generate our objects in code.

Note: If your code relied on namespaces/assemblies which are not already loaded you will have to load them into memory yourself before they can be used in this way.

.NET’s SecureString

I’m investigating various security based topics at the moment. Whilst I have dabbled in security in the past I do not class myself an expert on the subject, hence these posts may be fairly basic.

Background

I’m doing some coding that requires a level of security around data (specifically strings) which is simply not available using the String class.

The String class has a couple of properties which make it less than secure

  • The string is stored in memory as plain text
  • The disposal of memory is non deterministic and hence can remain in memory long after it’s usage has been completed

Obviously if we were to store a password in a string we can use tools such as WinDbg to dump memory and ultimately locate all instances of the password strings. Sure it might take a bit of time, but ultimately we’d find the password as plain text.

A solution?

TL;DR SecureString is only really secure until you need to get at the string, this isn’t a solution to 100% security but may help in certain situations, not least for situations where you want to pass a string between methods.

SecureString is a .NET class which is totally unrelated to the String class and it’s aim is to fix the security issues which exist for the String class, so

  • The SecureString may be encrypted within memory, on the MS website it suggests this is dependent upon the underlying OS
  • We can dispose of a SecureString in a deterministic way, i.e. calling the Dispose method or worse case garbage collected

To store some characters in a SecureString we have to append characters, like this

public static SecureString ToSecureString(string data)
{
   var secure = new SecureString();
   foreach (var c in data)
   {
      secure.AppendChar(c);
   }
   secure.MakeReadOnly();
   return secure;
}

We can also assign characters via a constructor override which takes a char* and length argument.

To turn a SecureString back into a String we can use

public static string ToString(SecureString secureString)
{
   var ptr = Marshal.SecureStringToBSTR(secureString);
   try
   {
      return Marshal.PtrToStringBSTR(ptr);
   }
   finally
   {
      Marshal.ZeroFreeBSTR(ptr);
   }
}

If, you come from a COM and C++ background you’ll recognize the BSTR’s.

In this code we get a pointer to the unmanaged BSTR from the SecureString then we use the pointer to create a String object. In the finally clause we zero out and release the memory that the BSTR used, ensuring that our password (or whatever) is both cleared and then removed from memory.

You might now be questioning what use the SecureString really is, if we ultimately convert whatever it’s storing too and from a String.

Ofcourse what you really need to do is store data which might be around for a while in the SecureString and preferably rarely convert them to Strings.

Secure input

Control-wise, WPF contains a SecurePassword property on the PasswordBox to allow input to be turned into a SecureString. Hence we can use this to take user input and store “secure” from input until the point we need to use it.

See also

Comparing secure strings in .NET

F# currying in a little more depth

Unlike Scala, for example, F# does not use an alternate syntax to differentiate a “curry-able” function from a “non-curry-able” function. I was therefore interested in what the F# compiler does to when supplied with a function like the following

let add a b c = a + b + c

Does it really generate something like the following code?

let add a = 
    let add1 b = 
        let add2 c = 
            a + b + c
        add2
    add1

Obviously this wouldn’t be great as the code requires closures and sub-functions to be created and so would be less performant in situations where we do not require the currying capabilities.

Thankfully the F# compiler takes care of everything for us so that if we have code in our application which solely uses the add function, like this

let r = add 1 2 3

then the compiler simply generates the following, this is taken from ILSpy from the compiled code and obviously reproduced in C# which I think demonstrates pretty clearly what happens.

public static int add(int a, int b, int c)
{
   return a + b + c;
}

// therefore our call to the 
// function becomes
int r = Program.add(1, 2, 3);

Now, what happens if we start currying our functions, with code like this

let r = add 1 2 
let r1 = r 3

Here the compiler still creates the add method as before (as one would expect) but it also creates the following internal class (I’ve removed attributes to make it all a little cleaner)

internal sealed class r@9
{
   public int a;
   public int b;

   internal r@9(int a, int b)
      : this()
   {
      this.a = a;
      this.b = b;
   }

   public override int Invoke(int c)
   {
      return Program.add(this.a, this.b, c);
   }
}

// now our calling 
// code looks like this
int a = 1;
int b = 2;
FSharpFunc r2 = new r@9(a, b);
int r = (int)r2.Invoke((!0)3);

So in conclusion, if we’re not using currying on our functions then we get a “standard” function and once we start currying only then do we get the equivalent of sub-functions being created.

More ASP.NET Core with C#

In the previous post I looked into the F# Giraffe library which makes writing all sorts of web request/response code pretty simple. This in turn is built on top of the existing functionality within ASP.NET Core.

Let’s again look at the bare bones code from running up Kestrel adding code to the pipeline

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace KestrelTest
{
    public class Startup
    {
        public void Configure(
            IApplicationBuilder applicationBuilder,
            IHostingEnvironment hostingEnvironment)
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseKestrel()
                .Build()
                .Run();
        }
    }
}

Within the Configure method we can start adding code to respond to different routes using the Map method, for example add the following to the Configure method

applicationBuilder.Map("/hello", app =>
{
   app.Run(async ctx =>
   {
      var request = 
         ctx.Request.Path.HasValue ? 
            ctx.Request.Path.Value.Substring(1) : 
            String.Empty;
       await ctx.Response.WriteAsync("Hello " + request);
   });
});
applicationBuilder.Map("/error", app =>
{
   app.Run(ctx => 
      Task.FromResult(
         ctx.Response.StatusCode = 404) 
   );
});

Note: The code is somewhat basic, obviously you would probably want to write some better code for extracting partial paths etc. from the routes/maps. However we’ll be covering a better alternative to this sort of code later in the post.

In the above we’ve created the equivalent of two “routes”. The first handles URL’s along the line of localhost:5000/hello/World where the return would become “Hello World”. The second route simply responds with a 404 for the URL localhost:5000/error.

We can also (as you’d expect) handle queries within our URL, so let’s say we expect this format URL, http://localhost:5000/hello?name=World, then we can amend our /hello code to the following

applicationBuilder.Map("/hello", app =>
{
   app.Run(async ctx =>
   {
      await ctx.Response.WriteAsync(
         "Hello " + ctx.Request.Query["name"]);
   });
});

These pieces of code write responses, but we can also insert code into the pipeline which doesn’t write to the response but instead might add debug/logging code. Other examples of usage might include (as per Writing Middleware) changes to the culture for the user response.

Here’s a simple example of such code, this is a little contrived as we’re going to (in essence) redirect calls to /hello path. Just place the following code before the applicationBuilder.Map method in the above

applicationBuilder.Use(async (ctx, next) =>
{
   if (ctx.Request.Path.Value == "/hello")
   {
      ctx.Request.Path = new PathString("/error");
   }
   await next.Invoke();
});

Note: there are redirect/URL rewriting capabilities already in ASP.NET Core, see URL Rewriting Middleware in ASP.NET Core.

Routing

In the previous example we demonstrated using the Map method to route our calls but ASP.NET Core libraries already supply a routing middleware which handles a lot of the standard routing type of functionality we’d expect. We can add the routing services by adding a method to the Startup class like this

public void ConfigureServices(
   IServiceCollection services)
{
   services.AddRouting();
}

Now the Configure method should look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   var routes = new RouteBuilder(applicationBuilder);
   routes.MapGet("hello/{name}", ctx =>
   {
      var name = ctx.GetRouteValue("name");
      return ctx.Response.WriteAsync($"Hello {name}");
   });

   applicationBuilder.UseRouter(routes.Build());
}

The RouteBuilder handles the routing in a more helpful/useful manner. Don’t forget to use the line applicationBuilder.UseRouter(routes.Build()); or you’ll find that the routes are not registered and hence your code will never get called.

References

ASP.NET Core MiddlewareRouting in ASP.NET Core

Using Giraffe as a service pipeline in Kestrel

In the previous post we looked at using Kestrel to run an ASP.NET Core application, now we’re going to use Giraffe to build some services.

Giraffe is an F# library to let get started by creating our application code.

  • Create Visual F# | .NET Core | Console App
  • My project is named GiraffeTest
  • Add via NuGet Giraffe and Microsoft.AspNetCore

Replace Program.fs code with the following

open Giraffe
open Microsoft.Extensions.DependencyInjection
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore

let webApp =
    choose [
        GET >=>
            choose [
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
            ]
    ]

type Startup() =
    member this.ConfigureServices (services : IServiceCollection) =
        services.AddGiraffe() |> ignore

    member this.Configure (app : IApplicationBuilder) =
        app.UseGiraffe webApp

[<EntryPoint>]
let main _ =
    WebHost.CreateDefaultBuilder()
        .UseKestrel()
        .UseStartup<Startup>()
        .Build()
        .Run()
    0

In the previous post we saw how to create the Kestrel server, so the code in main is exactly the same (apart from obviously being F#) which creates the server and calls the Startup class to configure our middleware. In this case we add Giraffe to the services and runs the Giraffe webApp HTTP handler.

The webApp HTTP handler is basically our filter and routing function.

Run this code up and navigate to localhost:5000/hello/World and we should get Hello World displayed.

We didn’t actually need the GET handler as by default the GET will be used, but it’s shown here to be a little more explicit in what is being implemented. We can also support POST methods using the same syntax as our GET code.

Extending our routes

Giraffe allows us to declare multiple routes which can include static pages. Let’s start off my adding an index.html page to the “Content root path” as displayed when running the application, in my case this is the folder containing Program.fs. I’m using the following index.html

<html>
    <body>
        Hello World
    </body>
</html>

Now add a new route to the route section of the webApp. i.e.

choose [
    routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
    route "/" >=> htmlFile "index.html"
]

This has now added a route for localhost:5000/ which returns the contents of the index.html file.

A list of different routes can be seen in the source for Routing.fs.

Below is an example of using some different routes

let helloName name = text (sprintf "Hello %s" name)

let webApp =
    choose [
        GET >=>
            choose [
                // case insensitive using anonymous function
                routeCif "/hello/%s" (fun name -> text (sprintf "Hello %s" name))
                route "/"       >=> htmlFile "index.html" 
                route "/error"  >=> setStatusCode 404
                route "/ping"   >=> text "pong"
                // case sensitive use function
                routef "/hello2/%s" helloName
            ]
    ]

Return from the fish (>=>) operator can be marked as different types of result types.
The functions text, htmlFile and other response writes available here ResponseWriters.fs. These include the usual suspects such as XML and JSON. Giraffe also supports Razor, see the NuGet package Giraffe.Razor.

References

Giraffe GitHub repos.

Kestrel – ASP.NET core web server

Kestrel is a .NET Core cross platform web server that can be used to host web sites, web/REST services etc.

Note: This code covers .NET core 2.0 and ASP.NET core 2.0.1

Take a look at Introduction to Kestrel web server implementation in ASP.NET Core for a great post about using Kestrel along with IIS, Nginx etc.

Getting Started

Let’s get started and build a very basic application running Kestrel.

  • Create a Visual C# | .NET Core | Console App (.NET Core) application
  • My project is named KestrelTest
  • Use NuGet to add the package Microsoft.AspNetCore

Now let’s create the most basic and most useless web server by writing the following code

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;

namespace KestrelTest
{
    public class Startup
    {
        public void Configure(IApplicationBuilder applicationBuilder,
            IHostingEnvironment hostingEnvironment)
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseKestrel()
                .Build()
                .Run();
        }
    }
}

In Main we create the webserver and we supply the Startup application which we’d use to configure our services. Minimally we need the Configure method in the Startup object and notice we’re not adhering to any specific interface or type.

We could pass the args to the CreateDefaultBuilder if we want to start the application with certain arguments and/or use the UseKestrel override to create options for our server, but we’re aiming to just create the bare essentials of a Kestrel based web server in this post.

Now we can run this code and we’ll get, by default, a web server running and exposing port 5000 on localhost. However the server does nothing else, no static pages, nothing.

So let’s now add the NuGet package Microsoft.AspNetCore.StaticFiles and change our Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.UseWelcomePage();
}

Now run the application and using your preferred web browser, navigate to localhost:5000 and you should see a ASP.NET Core Welcome Page.

Again this is of little use but does show that everything is working.

Serving up some static content

See Work with static files in ASP.NET Core for more in depth information.

Let’s now use Kestrel to serve up some static pages. Change the Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.UseStaticFiles();
}

Now in your project folder (i.e. the folder with your Program.cs file) which should be the same as the Content root path shown when you run the application. Here you can add a wwwroot folder and place an HTML page in the folder, i.e. here’s a simply index.html file

<html>
    <body>
        Hello World
    </body>
</html>

Make sure you set the file to have the “Copy to Output Directory” option as “Copy if Newer” in the properties window in Visual Studio.

Run the application again and navigate to localhost:5000/index.html and you should see the text Hello World.

Middleware

As we’ve seen in this post, the design of Kestrel is to supply a default web server application which we can then add our middleware code to, turning the application into a static web server or adding ASP.NET MVC into the mix etc. We can implement our own middle ware (see ASP.NET Core Middleware) which can be used to handle requests via a middleware pipeline.

I’m not going to go into any real depth in terms of developing my own middleware as we can already use various libraries for this, but just to demonstrate how we can intercept a request, change the Configure method to look like this

public void Configure(
   IApplicationBuilder applicationBuilder,
   IHostingEnvironment hostingEnvironment)
{
   applicationBuilder.Run(async context =>
   {
      await context.Response.WriteAsync("***Hello World***");
   });
}

Now if we run up the application and navigate to localhost:5000 we should see ***Hello World*** returned.

References

Introduction to Kestrel web server implementation in ASP.NET Core
BenchmarksASP.NET Core Web Servers: Kestrel vs IIS Feature Comparison and Why You Need Both

Currying functions

Currying is probably better known within functional languages. In it’s simplest form we can view a currying as a way to declare a function and if a user of the function supplies less arguments than expected then a function is returned which takes the remaining arguments.

Let’s look at currying using a functional language such as F# first, as this really shows the usefulness of such a capability. We’ll define an add function which takes three parameters

let add a b c = a + b + c

Now we can write code such as

let r = add 1 2

Note: when we create a new function from our curried function, such as r in above, we can call this a partially applied function.

As you can see, we have not supplied all the arguments and hence r is not an integer but is instead a function which now accepts a single argument, i.e. the final argument the add function expects. Therefore we can write the following code against the returned function

let i = r 3

Now, i is an integer and contains the result of add 1 2 3 function call (i.e. the value 6).

Currying comes “built-in” syntactically in languages such as F#. We can write explicit code to demonstrate what in essence happens when we work within currying capable languages. Here’s an F# example which shows how we create functions returning functions along with closures to pass the preceding function arguments to each inner function

let add a = 
    let add1 b = 
        let add2 c = 
            a + b + c
        add2
    add1

Note: The F# compiler does NOT create the code equivalent to the above when we create functions unless the usage of the add method includes using it in a curried scenario.

The above is written in F# but you’ll notice that this same technique can easily be written in languages such as C#, Java etc. Here’s the same code in a verbose implementation in C#

public static Func<int, Func<int, int>> Add(int a) => 
   new Func<int, Func<int, int>>(b => (c => a + b + c));

Thankfully C# allows a less verbose syntax, so the above can be rewritten as

public static Func<int, Func<int, int>> Add(int a) =>
   b => (c => a + b + c);

To call such a function we’d need to write code such as

var i = Add(1)(2)(3)

This is not as elegant as the F# code (in my opinion) but does allow currying and partially applied functions in C#.

As you’d expect – another functional language, Scala, supports currying using the following syntax

def add(a : Int)(b : Int)(c : Int) = a + b + c;

val r = add(1)(2)_
// or alternate syntax
// val r = add(1)(2)(_)
val i = r(3)

Notice that we require the _ (underscore) to ignore the third argument and we need to wrap each argument within brackets (creating parameter groups) to enable the function to be curried. The missing last argument need now be enclosed within brackets.

Scala also allows us to create partially applied functions where it’s not just the last n parameters that make up the new function. For example (let’s change the argument types to a string to the output is more obvious.

def mid(a : String)(b : String)(c : String) = a + b + c;

def m = mid("Start ")(_:String)(" End")
println(m("Hello World"))
// outputs Start Hello World End

In this case we’re making a partially applied function using the curried function mid where in usage we miss out the middle parameter in the example usage. However we must also supply the type along with the _ placeholder.