Posts in the '.NET' category

The posts below all relate to the topic you selected.

In my previous post I got started using .NET Core Razor pages with Semantic UI. After writing the post I was convinced I'd be using Semantic UI for my next blog redesign. One reason is that when you use Semantic UI's gulp build tools alongside .NET's watch tool, you can be really efficient in designing your site and figuring out how you want it to look. This post demonstrates how to use Visual Studio Code and the built-in multiple-tab terminal window to make this a natural development experience.

Copying the default theme into a new folder named brady makes it easy for me to feel comfortable customizing numerous colors and font sizes, and anything else I want to tweak without fearing I've boned up the default theme. Once I get that working I can run dotnet watch run to start up my site.

dotnet watch

I got started with one of the built-in Semantic UI layouts, with a simple menu at the top of my site.

The before UI

Semantic UI offers a handy gulp watch command that, when executed, will watch all of the files in my theme (or any of the Semantic UI override files). Whenever I change any of these files the changes will be picked up and the CSS/JS files will be rebuilt. I don't want to stop the ASP.NET server from running, but I do want to see immediate updates when I make changes to my Semantic UI theme files. So I open up a new tab in Visual Studio Code and cd into the semantic folder in my project root (not the semantic folder inside of wwwroot!).

Adding a terminal tab

Now I can run the gulp watch build step and any change I make will be automatically picked up. So, let's make a quick change to the top menu bar to give the site some color.

Gulp watch

I'll open up the original default menu theme file that I copied into my own brady theme.

Original menu

Now, I'll change the @background variable to be a blue that might look better with my photo. As soon as I save the file the files are rebuit.

Edited menu

Once the build completes I can refresh the browser, and the changes are visible.

Resulting menu


This post continues my exploration into how Semantic UI and ASP.NET can be great together. I'm in the process of re-writing my blog tool to use Semantic UI, so stay tuned as in the next few days I'll release a new-and-improved site and much simpler codebase for the downr blogging system. Happy coding!


After thinking a lot about my blogging app I decided to start over somewhat on the UI of the site and to simplify things in general. In so doing, Razor seemed like the best option, as I won't have a lot of complexity in either the UI or the middle tier. Since I'm re-thinking the view layer anyway, it felt like a good time to investigate one of the awesome new UI frameworks I've heard about. After some review, Semantic UI was my favorite, so after choosing to use it I found there are a few various resources on the web about using Semantic UI with ASP.NET at various levels of completeness, so I chose to write this one. In this post, I'll walk through the basic steps of using dotnet new along with the Semantic UI getting started experience to blend the two together. There's an accompaying repository if you prefer to just dive in.

Semantic UI and ASP.NET Core

Every great project has to start somewhere. Mine always start with a brand new, spanking clean directory. My app will live in semantic-aspnet. The folks over at Semantic UI have a great getting started article. Take a look at it to get the details, but for the impatient, getting started is as simple as:

npm install semantic-ui --save

Install Semantic UI

Once NPM performs the magical routine of bringing all your site's dependencies down, you'll notice a call to gulp install at the very end of the process. This launches a friendly Semantic UI step-by-step wizard. Since I have no idea what I'm doing as this is my first rodeo with Semantic UI, I'll be gentle and accept the defaults.

Install output

The obvious next step - open the directory up in Visual Studio Code, 2018's favorite software development environment. Then the real fun can begin.

CLI output

The semantic.json file contains configuration that's used by Semantic UI's Gulp build process (don't worry, we'll cover that next, and it's not complicated) to know where to drop files produced by the build. There are a ton of components (Button, Flags even a Reveal) in Semantic UI, and with all those modules come a good number of .css and .js files. They get minified and packaged up awesomely by the gulp build command.

Note: Take note that you need to CD into the semantic folder (the folder identified by the base property in semantic.json) before running gulp build.

Gulp build

When the build completes, all of the files needed to run Semantic UI will be in my semantic\dist folder.

Gulp build output

That's no good, since I know I'll need to have those files in the static files area - the wwwroot folder - so I need to make some tweaks to the configuration. Specifically, I'll swap all the instances of dist with ../wwwroot/semantic. That way, I'll be able to edit my .cshtml files in the Pages folder, my C# source code, and my UI layer by making use of the great theming capabilities and layout features Semantic UI offers. Once I tweak the configuration I can simply run the gulp build command once more, and...

Edit to wwwroot

Voila! Now, the Semantic UI's output is dropped into the wwwroot folder. With it there, I'll be able to drop in the .NET Core stuff next. That way, the Semantic UI distribution components fit nicely inline with the conventions I'm used to when I'm building ASP.NET Core Razor page apps.

Build in wwwroot

Now I'll run dotnet new razor to lay down the ASP.NET source code I'll need to get started. It'll drop down the typical Bootstrap UI layer, but I can delete the lib folder altogether since I'll be using Semantic UI.

DotNet new

Since I'm no longer using Bootstrap I can refer to the Semantic UI docs on including Semantic UI in my site's HTML, as well as stripping out most of the remaining HTML from the layout page.

Most basic HTML starting point

Then I pull over the navigation and footer HTML from the fixed layout sample, and rip the body area as well to surround the call to @RenderBody(), edit the index.cshtml file some to just show a basic text paragraph. All of the source code for this super-basic beginning is in the accompanying repository, but the results look pretty nice.

Resulting layout


I've taken a look at Semantic UI as it's been years since I tried a new UI framework. As with any new trick or sauce, it takes a little trial-and-error to get things perfect, but the effort is minimal to get tweak your new ASP.NET Razor app to make use of Semantic UI. I'm still learning about the theming capabilities; there are so many awesome things the folks at Semantic UI give you to make creating your own color schemes and layouts a breeze. Hope this helps you if you're thinking of using the two together, and getting started literally takes 10 minutes. Happy coding!


As announced by Scott Guthrie recently, Azure Web Sites now supports the .NET Framework 4.5. Some awesome ASP.NET features are now available to web developers who want to host their ASP.NET applications on Azure following the web sites offering getting support for .NET 4.5. One feature I’m especially excited about is Entity Framework Spatial support. Only available in .NET 4.5, EF Spatial is something that gives developers who want to build location-aware applications the ability to easily save and retrieve location data without having to invent crazy solutions using SQL code. I’ve implemented the Haversine formula using a SQL stored procedure in the past, and I can speak from experience when I say that EF Spatial is about 10,000 times easier and more logical. Don’t take my word for it, though. Take a look at the sample code I’ll show you in this blog post, which demonstrates how you can develop a location-aware API using ASP.NET Web API, EF Spatial, and host the whole thing on Azure Web Sites.

Creating the Site in Azure

Before diving into code I’ll go out to the Azure portal and create a new web site. For this API example, I create a site with a database, as I’ll want to store the data in a Azure SQL Database. The screen shot below shows the first step of creating a new site. By simply selecting the new web site option, then selecting “with database,” I’m going to be walked through the process of creating both assets in Azure in a moment.


The first thing Azure will need to know is the URL I’ll want associated with my site. The free Azure Web Sites offer defaults to [yoursitename], so this first step allows me to define the URL prefix associated with my site.

Simultaneously, this first step gives me the opportunity to define the name of the connection string I’ll expect to use in my Web.config file later, that will connect the site to the Azure SQL Database I’ll create in a moment.


The last steps in the site creation process will collect the username and SQL Server information from you. In this example, I’m going to create a new database and a new SQL Server in the Azure cloud. However, you can select a pre-existing SQL Server if you’d prefer during your own setup process.

I specifically unchecked the “Configure Advanced Database Settings” checkbox, as there’s not much I’ll need to do to the database in the portal. As you’ll see in a moment, I’ll be doing all my database “stuff” using EF’s Migrations features.


Once I’ve entered the username I’d like to use, the password, and selected (or created) a SQL server, I click the check button to create the site and the SQL database. In just a few seconds, both are created in Azure, and I can get started with the fun stuff – the c0d3z !

Preparing for Deployment

Just so I have a method of deploying the site once I finish the code, I’ll select the new site from the Azure portal by clicking on it’s name once the site-creation process completes.


The site’s dashboard will open up in the browser. If I scroll down, the Quick Glance links are visible on the right side of the dashboard page. Clicking the link labeled Download Publish Profile will do just that – download a publish settings file, which contains some XML defining how Visual Studio or WebMatrix 2 (or the Web Deploy command line) should upload the files to the server. Also contained within the publish settings file is the metadata specific to the database I created for this site.


As you’ll see in a moment when I start the deployment process, everything I need to know about deploying a site and a database backing that site is outlined in the publish settings file. When I perform the deployment from within Visual Studio 2012, I’ll be given the option of using Entity Framework Migrations to populate the database live in Azure. Not only will the site files be published, the database will be created, too. All of this is possible via the publish settings file’s metadata.

Building the API in Visual Studio 2012

The code for the location API will be relatively simple to build (thanks to the Entity Framework, ASP.NET, and Visual Studio teams). The first step is to create a new ASP.NET MVC project using Visual Studio 2012, as is shown below. If you’d rather just grab the code than walk through the coding process, I’ve created a public repository for the Spatial Demo solution, so clone it from there if you’d rather view the completed source code rather than create it from scratch.

Note that I’m selecting the .NET Framework 4.5 in this dialog. Previous to the 4.5 support in Azure Web Sites, this would always need to be set at 4.0 or my deployment would fail. As well, I would have had compilation issues for anything relating to Entity Framework Spatial, as those libraries and namespaces are also only available under .NET 4.5. Now, I can select the 4.5 Framework, satisfy everyone, and keep on trucking.


In the second step of the new MVC project process I’ll select Web API, since my main focus in this application is to create a location-aware API that can be used by multiple clients.


By default, the project template comes with a sample controller to demonstrate how to create Web API controllers, called ValuesController.cs. Nothing against that file, but I’ll delete it right away, since I’ll be adding my own functionality to this project.

Domain Entities

The first classes I’ll add to this project will represent the entity domains pertinent to the project’s goals. The first of these model classes is the LocationEntity class. This class will be used in my Entity Framework layer to represent individual records in the database that are associated with locations on a map. The LocationEntity class is quite simple, and is shown in the gist below.

Some of the metadata associated with a DbGeography object isn’t easily or predictably serialized, so to minimize variableness (okay, I’m a control freak when it comes to serialization) I’ve also created a class to represent a Location object on the wire. This class, the Location class, is visible in the following gist. Take note, though, it’s not that much different from the typical LocationEntity class aside from one thing. I’m adding the explicit Latitude and Longitude properties to this class. DbGeography instances offer a good deal more functionality, but I won’t need those in this particular API example. Since all I need is latitude and longitude in the API side, I’ll just work up some code in the API controller I’ll create later to convert the entity class to the API class.

Essentially, I’ve created a data transfer object and a view model object. Nothing really new here aside from the Entity Framework Spatial additions of functionality from what I’ve done in previous API implementations which required the database entity be loosely coupled away from the class the API or GUI will use to display (or transmit) the data.

Data Context, Configuring Migrations, and Database Seeding

Now that the models are complete I need to work in the Entity Framework “plumbing” that gives the controller access to the database via EF’s magic. The first step in this process is to work up the Data Context class that provides the abstraction layer between the entity models and the database layer. The data context class, shown below, is quite simple, as I’ve really only got a single entity in this example implementation.

Take note of the constructor, which is overridden from the base’s constructor . This requires me to make a change in the web.config file created by the project template. By default, the web.config file is generated with a single connection string, the name of which is DefaultConnection . I need to either create a secondary connection string with the right name, change the default one (which I’ve done in this example), or use Visual Studio’s MVC-generation tools to create an EF-infused controller, which will add a new connection string to the web.config automatically. Since I’m coding up this data context class manually, I just need to go into the Web.config and change the DefaultConnection connection string’s name attribute to match the one I’ve added in this constructor override, SpatialDemoConnectionString . Once that’s done, this EF data context class will use the connection string identified in the configuration file with that name.

During deployment, this becomes a very nifty facet of developing ASP.NET sites that are deployed to Azure Web Sites using the Visual Studio 2012 publishing functionality. We’ll get to that in a moment, though…

EF has this awesome feature called Migrations that gives EF the ability of setting up and/or tearing down database schema objects, like tables and columns and all indexes (oh my!).  So the next step for me during this development cycle is to set up the EF Migrations for this project. Rowan Miller does a great job of describing how EF Migrations work in this Web Camps TV episode, and Robert Green’s Visual Studio Toolbox show has a ton of great content on EF, too, so check out those resources for more information on EF Migrations’ awesomeness. The general idea behind Migrations, though, is simple – it’s a way of allowing EF to scaffold database components up and down, so I won’t have to do those items using SQL code.

What’s even better than the fact the EF has Migrations is that I don’t need to memorize how to do it because the NuGet/PowerShell/Visual Studio gods have made that pretty easy for me.  To turn Migrations on for my project, which contains a class that derives from EF’s data context class (the one I just finished creating in the previous step), I simply need to type the command enable-migrations into the NuGet package management console window.

Once I enable migrations, a new class will be added to my project. This class will be added to a new Migrations folder, and is usually called Configuration.cs . Within that file is contained a constructor and a method I can implement however I want called – appropriately – Seed. In this particular use-case, I enable automatic migrations and add some seed data to the database.

Enabling automatic migrations basically assumes any changes I make will automatically be reflected in the database later on (again, this is super-nifty once we do the deployment, so stay tuned!).

Quick background on what types of locations we’ll be saving… My wife and I moved from the Southeast US to the Pacific Northwest region recently. Much to our chagrin, there are far fewer places to pick up great chicken wings than there were in the Southeast. So, I decided I needed to use our every-Sunday-during-football snack of chicken wings as a good use-case for a location-based app. What a better example than to give you a list of good chicken wing restaurants listed in order of proximity? Anyway, that’s the inspiration for the demo. Dietary recommendation is not implied, BTW.

The API Controller Class

With all the EF plumbing and domain models complete, the last step in the API layer is to create the API controller itself. I simply add a new Web API controller to the Controllers folder, and change the code to make use of the plumbing work I’ve completed up to now. The dialog below shows the first step, when I create a new LocationController Web API controller.


This controller has one method, that takes the latitude and longitude from a client. Those values are then used in conjunction with EF Spatial’s DbGeography.Distance method to sort the records from closest in proximity, then the first five records are returned. The result of this call is that the closest five locations are returned with a client provides its latitude and longitude coordinates to the API method. The Distance method is used again to determine how far away each location is from the provided coordinates. The results are then returned using the API-specific class rather than the EF-specific class (thereby separating the two layers and easing some of the potential serialization issues that could arise), and the whole output is formatted to either XML or JSON and sent down the wire via HTTP.

At this point, the API is complete and can be deployed to Azure directly from within Visual Studio 2012 using the great publishing features created by the Visual Studio publishing team (my buddy Sayed Hashimi loves to talk about this stuff, so ping him on Twitter if you have any questions or suggestions on this awesome feature-set).

Calling the Location API using an HTML 5 Client

In order to make this a more comprehensive sample, I’ve added some HTML 5 client code and Knockout.js -infused JavaScript code to the Home/Index.cshtml view that gets created by default with the ASP.NET MVC project template. This code makes use of the HTML 5 geospatial capabilities to read the user’s current position. The latitude and longitude are then used to call directly the location API, and the results are rendered in the HTML client using a basic table layout.

The final step is to deploy the whole thing up to Azure Web Sites. This is something I wasn’t able to do until last week, so I’m super-stoked to be able to do it now and to share it with you on a demo site, the URL of which I’ll hand out at the end of this post.

One Last NuGet to Include

Entity Framework Spatial has some new data types that add support for things like… well... latitude and longitude, in this particular case. By default, these types aren’t installed into a Azure instance, as they’re part of the database SDK. Most times, those assemblies aren’t needed on a web server, so by default you won’t have them when you deploy. To work around this problem and to make Entity Framework Spatial work on the first try following your deployment to Azure, install the Microsoft.SqlServer.Types NuGet package into your project by typing install-package Microsoft.SqlServer.Types in the Package Manager Console or by manually finding the package in the “Manage NuGet References” dialog.

Thanks to Scott Hunter for this extremely valuable piece of information, which I lacked the first time I tried to do this. This solution was so obvious I hid in my car with embarrassment after realizing how simple it was and that I even had to ask. NuGet, again, to the rescue!

Once this package is installed, deploying the project to Azure will trigger automatic retrieval of that package, and the support for the location data types in SQL Server will be added to your site.

Publishing from Visual Studio 2012 is a Breeze

You’ve probably seen a ton of demonstrations on how to do deployment from within Visual Studio 2012, but it never ceases to amaze me just how quick and easy the team has made it to deploy sites – with databases – directly up to Azure in so few, simple steps. To deploy to a site from within Visual Studio 2012, I just right-click the site and select – get this – Publish. The first dialog that opens gives me the option to import a publish settings file, which I downloaded earlier just after having created the site in the Azure portal.


Once the file is imported, I’m shown the details so I have the chance to verify everything is correct, which I’ve never seen it not be, quite frankly. I just click Next here to move on.


This next step is where all the magic happens that I’ve been promising you’d see. This screen, specifically the last checkbox (highlighted for enthusiasm), points to the database I created earlier in the first step when I initially created the “site with database” in the Azure portal. If I check that box, when I deploy the web site, the database schema will be automatically created for me, and the seed data will be inserted and be there when the first request to the site is made . All that, just by publishing the site!


Can you imagine anything more convenient? I mean seriously. I publish my site and the database is automatically created, seeded, and everything wired up for me using Entity Framework, with a minimal amount of code. Pretty much magic, right?

Have at it!

Now that the .NET 4.5 Framework is supported by Azure Web Sites, you can make use of these and other new features, many of which are discussed or demonstrated on at’s page set aside just on the topic of ASP.NET 4.5 awesomeness . If you want to get started building your own location API’s built on top of Entity Framework Spatial, grab your very own Azure account here, that offers all kinds of awesomeness for free. You can take the sample code for this blog, or copy the gists and tweak them however you want.

Happy Coding!


During a friendly code review discussion a week or so ago I realized I’d forgotten my favorite lore of custom authentication/authorization functionality in lieu of ASP.NET P&M. Though I definitely prefer P&M to rolling my own from scratch to the extent that I’ve gone as far as to use it as a pass-through there are some times when P&M is too much – or too little – so custom schemes must be developed. The thing that surprises me each time I observe a custom scheme is the lack of usage of the IPrincipal/IIdentity interfaces. With MVC 3.0 as my major weapon of choice in web development and my recent adoption of P&M, it became obvious that an opportunity had popped up for mixing my favorite old-school .NET trick into my favorite new-school paradigm.

Here’s the thing. If you don’t use the IIdentity and IPrincipal interfaces when you create a custom authentication/authorization solution you’ve completely missed the boat and I guarantee you you will write 100 times more code, that will be more brittle, than you would have ever written had you just used them in the first place.


A quick look into what these two interfaces offer is in order. The graphic above sums it up visually. You’ll see that the IIdentity interface is typically considered a requirement for the IPrincipal to exist; obviously this model fits in rather well with MVC’s favoritism to IoC/DI practices.  The principal wraps around the identity, supplying access to a user’s roles. So long as your classes implement the requirements, they can be bound to the HTTP Context, the current thread, basically attached the process so that all the niceties like use of the [Authorize] attribute and role-based location security via the web.config file are possible without tons of rework.


The first class needed in any custom implementation is the identity class. The main purpose of this implementation is to represent the user’s name, really, as well as how the user was authenticated and if they are authenticated. Should the IsAuthenticated property be set to false at run-time, code later on assumes the user is an anonymous user.


Next will be the CustomPrincipal class. Since this class implements IPrincipal, it can be used to bind itself directly to a thread (or an HTTP Context). Since it can be used in that manner, all the functionality and support offered via web.config-based authorization, use of the [Authorization] attribute, all of that – it will be maintained and you won’t have to write it (or support it, or debug it, and so on). Note how the constructor’s argument is highlighted to illustrate the connection between the two classes.


To wrap these classes up via a native event handler or inherited method we’ll create a BaseController . It could – and probably should – be done via an injected service, obviously, but I’m honoring the KISS principle [you say principle, I say principal ] for the purposes of this walk-thru. The base controller is shown below and its main purpose in existing – to authorize the active user account prior to allowing execution of the controller action.


Caveat: This next part isn’t a recommendation, it’s only used for the purposes of keeping this explanation simple. Forgive me.

Now that we’ve satisfied the authorization part we’ve got to authenticate the user and store their login information somewhere for the life of their… yeah, you guess it, for the life of their session. We’re going to use Session here, okay, but just for the demo. It isn’t a recommendation. Please turn off the tape recorder.

The SimpleSessionPersister class below persists the user’s name into a session variable [ducks under flying tomato]. The login controller action below the utility class just validates that the user provided something for their username and password and, if so, the user’s username is persisted to session for use – by the BaseController, specifically – later during the HTTP request.


You can relax now, that part’s over.

Now that the user has been authenticated we can assume that each controller we create (provided it inherit from our custom base) will authorize each individual request per the best-practice role-base security means. Take the following controller action below, which requires the user be authenticated via the [Authorize] attribute and the web.config, also below, which indicates the login page URL as our Login controller action.


Should a user try to hit the non-anonymous page they’d be redirected to the login page (see the URL highlighted below). 


To review the process we went through to accomplish our very own custom-made end-to-end security paradigm that still allows usage of the .NET built-in role-based security resources, here’s what we had to do:

  • Implement the IIdentity interface in a custom class
  • Inherit from the IPrincipal interface in a custom class
  • Create a way to authenticate the user
  • Create a way to persist the authentication information [a.k.a. username in this example]
  • Override the OnAuthorization method in a base controller and then use that base controller in future controllers

Happy Coding! If you’d like to take a peek at the code for this demo and debug it for better observation as to how it all works together you can download the code from my DropBox account .


This post serves a dual purpose, to add to the list of articles in the series on Generics and Reflection. It also introduces a Fluent business logic processor I’ve built about 100 times in other incantations but I think all eventually leading up to this point. In keeping with my current trend of hypercomplicating the sublime by making giving it a Fluent interface to make it easy for reuse later on, the result was, as my friend Bill Hargett would probably say, is an object-oriented way of representing a procedure. Pretty much. So that’s our goal statement.

Represent the relationship between an object and the steps it takes through a system or the actions on which a process acts out on that object as a series of disconnected objects. Expose the ability to use that decisioning power via a Fluent interface. Use business language-rich unit tests to provide guidance on the manner in which the processes should be executed.

Typical late-night insomnia fodder. Thank goodness for Generics, for they make the whole engine and core architecture of this idea possible in about 200 lines of code. Maybe less.

To get started take a look at the super-simple business entity and exception. You can probably figure out what the business logic looks like. We’ll spell it out in provable statements:

  1. Allow all users 21 or over to drink
  2. Disallow all users under 21 to drink


Taking that logic and rolling unit tests is pretty easy.


Given those tests we have a rather common language from which a Fluent interface can be created. Handle a target instance or list of instances using associated method calls. Why method calls and not interfaces? That’d force too much structure. You could have one old app with all the  methods you need, just not glued together properly. You refactor a little, tie it all together, and use something like NDecision to direct traffic.


With the unit tests defined and a little imagination and patience applied the Fluent interface takes a structure that makes the business rules quite easy to implement. The test out put is below. you’ll see both tests pass in spite of the fact that the result behavior of the underage run is an exception is thrown; it’s just one the test is actually is expecting.


If you’re interested in this, let me know and I’ll get you a copy of the code. It is pretty short and is probably going to be shown in a future post, so stay tuned.