Catchy title, but it explains exactly what is in this post.

I have just released an update to one of my UWP apps called WebUp. The additional functionality I added was email notifications when a http end point went offline. There are different ways you can message from a UWP app, but I wanted to use SendGrid to manage all messaging, so in this post I will cover adding this functionality from a UWP app written using WinJS. So yes it is possible to consume C# functionality from JavaScript and it is easier than you think. Why SendGrid you may ask, simply that they allow you to send 12 thousand emails per month for free, can’t grumble with that.

Windows Runtime Component

This is a dll that can produce winmd metadata that can then be consumed by UWP app written in any supported language such as C#, C++ and even JavaScript. Although the functionality can be limited somewhat, they can be used to create wrappers around libraries that cannot usually be accessed in a UWP app.

What is WinJS?

This is a JavaScript framework from Microsoft that can allow the developer to quickly add functionality to UWP apps. Although originally developed just for creating Windows Store apps, more recently this library has been open sourced and can be used as a framework to create web applications. It can still be used however to create UWP apps using the JavaScript template in Visual Studio.

Creating the app

Firstly create an app using the basic WinJS template in Visual Studio.

image

Choose the target and minimum versions.

image

Now a new project is needed to be added to the solution, so right click the solution.

image

Choose Windows Runtime Component under the C# collection.

image

Right click the references of your main UWP project and add this component.

image

To use SendGrid for messaging, the best component to use is called LightBuzz and can be found here:- https://github.com/LightBuzz/SMTP-WinRT

Although it’s easy to add references via NuGet, for some reason with UWP apps created this way, the library was not copied locally, so I cloned the repo from GitHub and built the project locally giving me a nice shiny library I can then reference old school.

image

Just make sure it is set to copy local in its properties.

Now for some code.

In the class code auto generated when you created the Runtime Component, make sure you have the using statement for LightBuzz.SMTP and add this code:-

When using SendGrid, you can add extra credentials to your account that helps separate out different usage scenarios. I have credentials set up for my WebUp app and I have used it here, just swap out with your credentials.

While in the Component code, have a look at the project.json file, it will list all the runtimes that are available for the component. When running this app,, you will need to change the environment to one of these as ‘Any CPU’ does not work.

image

Now back in the UWP code, add something like this to the app.onactivated function; obviously you will want to put it somewhere else, but for this example it will work.

Enter your email address and run the app. With any luck you should start to receive emails direct from your app via SendGrid.

When doing Continuous Integration and Continuous Deployment, sometimes its great to get your code into production but hidden from any end user actions. In this post I will outline what I have been using with great success on my SaaS application ObsPlanner. There are however loads of libraries and other tools that will do the same thing, but I opted for the more simple, home grown approach.

My application is an MVC application that uses Angular JS in the views to give a better end user experience by acting as a mini SPA, so C#, Razor and Angular need to know about what features are available and what is not.

The database structure is simple, a table with one column for the toggle name and another for if it is enabled like this:-

 

I am using Entity Framework for all my database work, so I have a FeatureToggleRepository that retrieves the data like this:-

Each of my MVC controllers inherit from a BaseController which has methods used throughout the site including the getting of toggles:-

Now each of my controllers can easily get the toggle list:-

Where the toggle list is added to a view model, in this case it includes the logged in user details as well as the toggles. So in the view I can use Razor to run a conditional against it like this:-

So that works great for the View, what about the Angular stuff, couldn't that break if certain elements are not present in the view? Well yes it could so in the JavaScript I simply have all my toggle code nicely wrapped in functions that only get called if an element with the correct id is present in the view like this:-

The setup for this site is a development, staging and live server all with their own copies of the database. So this method allows me to push code through the whole life cycle and simply switch on the feature on the live server when I am happy with it.

Happy coding

Entity Framework code first migrations are really handy, but can be dangerous in the wrong hands as they make changes to the underlying database of your application.

Before the days when a single check in would run through the build process CI/CD pipeline, it was normal for the development stage to make constant changes to a database structure as an when the features requested needed it. With the new model of all changes running through the CI/CD pipeline, the database changes could be quickly pushed to a test or staging server in no time at all. With this new model of writing code, a few precautions have to be taken to make sure EF migrations don’t wreck havoc on the database running the staging or test servers.

Migrations in Entity Framework

A migration is a change to the schema of a database based on any model changes that have been created in the data layer of the application. If for example there is a User class and a new property is added for membership level, then with migrations enabled, a new column will be created in the database to match the new property.

But for a database already in existence and maybe even already in production, you don’t want changes to the schema to go directly through to production. So there are a few steps to take, these are:-

  1. Create a copy of the existing database on the local machine
  2. Reverse engineer the database to classes that can be used for Code First migrations
  3. Enable migrations
  4. Create a manual empty migration to tell EF that both model and database are in sync
  5. Disable migrations for all but local changes
  6. Generate a migration script for the dba to implement

Create a copy of the existing database on the local machine

I will leave this step up to you as some developers prefer to either restore a database back up locally, script the entire database and data and run the script locally or you may even have a database on another server that you can use.

Reverse engineer the database to classes that can be used for Code First migrations

By using the Entity Framework Reverse POCO Generator Visual Studio plugin, it is possible to point it at the database and generate the DbContext and all the necessary POCO classes.

Right click the project in Visual Studio and choose Add > New item.. from the context menu, you will then get a choice that includes ‘EntityFramework Reverse POCO Code First Generator’ in the template list.

reverse-engineer-db

By default this will create a context with the name MyDbContext like this:-

image

Simply change the ConnectionStringName to match that in your app.config or web.config and save the file and it will generate the necessary classes in a cs file under the T4 template.

image

 

As this tool uses a t4 template to generate the classes, it is easily configurable for example to change the context class name.

 

Enable migrations

To enable migrations, simply go to the ‘Package Manager Console’ view in Visual Studio. It can be found either by typing in the Quick launch text box at the top right or View > Other Windows  > Package Manager Console. In the default project drop down make sure the correct project is selected then type:-

Enable-Migrations

This will create a ‘Migrations’ directory within the project which will have a Configuration.cs file inside.

This file will house the main configuration class for the migrations and it is in here where you can change whether AutomaticMigrations are enabled and if data loss is acceptable. On a development machine, that is probably OK, but you don’t want those settings passed into staging or production; so use a pre-processor directive such as this

In this class, you will notice the DbMigrationsConfiguration is being inherited from which is using the DbContext class we created when we reverse engineered the database. It is this class that is responsible for the model and to keep track of the migrations.

Going back to the generated context class we need to add references to System.Data.Entity to get access to the functionality to drop and recreate the database and pluralize names. This can be added to the OnModelCreating method like this:-

By setting the Initializer context to null stops any changes being made to the schema, whereas setting it to DropCreateDatabaseIfModelChanges will do just that.

Create a manual empty migration to tell EF that both model and database are in sync

Now you have the model that matches the database schema, you can manually add a migration using this command:-

Add-Migration –IgnoreChanges

image

By giving it a name it will be easier to identify it later on in the migrations collection and will also allow it to generate a class with the Up and Down methods that are used to generate logic to change the schema to different versions. As this is the initial synced migration, these should be left empty.

image

Disable migrations for all but local changes

Now that the switches are put in place, when the code goes through the CI/CD pipeline just build it with a switch of anything but Debug. For example in TeamCity I have a build step using MSBuild using the parameter /p:Configuration=Release

 

Generate a migration script for the dba to implement

Lets face it, nobody wants to feel the wrath of a DBA if you make changes to the production database without firstly notifying them. There should even be a proper change management process that would need to be followed through before any changes are pushed to production. This is where the script generation feature from Entity Framework comes in handy.

By using the command:-

Update-Database –Script

You can generate a TSQL script that will show all the changes needed to get the database up to data with the model; this script can then be run by the DBA on the staging or production servers. Here I have added a simple class called TestTable in the generated cs file.

 

 

image

Happy coding.

Creating Controllers in Umbraco CMS

On a recent project I needed to implement a secure area on a public facing website that runs on Umbraco CMS.
Umbraco runs on top of ASP.Net MVC, so pretty much what you can do with ASP.Net MVC you can do with Umbraco. The key requirements for this small project were to create a secure area that allows users to register for an account and login. Also the registered users were to be given different roles one for the uploading of documents and the other for the download of the same documents.

image

As MVC implements the membership provider, it was possible to create a register form which uses the same provider. In the view instead of using Html.BeginForm, for Umbraco we use Html.BeginUmbracoForm()

All this method does is acknowledge the registration and send out an email to the admin staff who then validates the request offline. One they have done this they will manually create a member in the Umbraco back office. Members in Umbraco can belong to either the Member type or a custom type. For our implementation we created a Portal Member Type that has all the same properties as the Member type except for an additional Portal Admin property. Members that are a Portal Admin are allowed to upload documents to the secure area; all other members are read only in essence.

image

So when the admin staff adds a new Member they choose the Portal Member Type.

Then simply add the necessary details and save.

image

Now that the user has an account to login they can go back to the same page and enter their credentials.

Which when posted sends required parameters to the controller.

This controller inherits from the Umbraco SurfaceController which allows it do either a standard redirect or a RedirectToCurrentUmbracoPage() for invalid attempts.
This method simply uses the Membership.ValidateUser() method which does the lookup in the database for the user.

Once the redirect has been complete, the call into the Index method of the GovernorPortalController occurs which inherits from the Umbraco RenderMVCController class. This class allows the Index method to be overridden and so a model can then be passed to the calling view. In our implementation we simply go to a backend database to get a collection of document details that are stored in a custom table in SQL Server. The controller then passes that collection to a ViewBag that the view then iterates through.

For some reason that I am yet to work out, the recommended way to implement custom controllers in Umbraco is to override RenderMVCcontroller for GETs and override SurfaceController for POSTs.

Anyway that aside, Admin Portal users need to upload documents to this area so another form is added to the same view. This is again using the Html.BeginUmbracoForm() helper method that posts to the UploadController's UploadFileMethod taking in an HttpPostedFileBase and title string parameters.

image

After checking this file's ContentLength, it is then saved to the server file system while being saved with a GUID for its filename to stop conflicts.

Various properties are then saved to the database, in this example I am using a simple SqlCommand instead of using Entity Framework as nowhere else in the site is using EF.

Once a collection of documents is presented to the user, admin users can delete documents by the use of a conditional that checks their role; this is found by querying the Umbraco properties for the user.

Happy coding.

Offline Web Applications

The HTML 5 specification, now available in most evergreen web browsers, gave the power of offline web applications. How this works is a manifest file is downloaded to the client which lists all files needed to make that page useable even if there is no network connection. This manifest file canm include JavaScript, CSS and HTML files. Of course it is possible to create an ASP.Net MVC application that can use this same technique as it renders HTML 5 anyway, however there are a few gotchas to look out for which I will cover in this post. Firstly the path to the .manifest file needs to be included in the HTML element at the top of the page.
<html lang="en" manifest="offline.manifest">
manifest file
For an MVC site, simply add the reference to the manifest in the _Layout file and add each resource you want in the browser application cache.
 
These resources above are used for the standard MVC template you get with Visual Studio 2015.
Now to get IIS to serve up this offline.manifest file you either have to add a mime type on the server or add it to the <system.webserver> element in web.config.
Its important that you add the clear element and you need then to add the usual types your site will serve up other wise you will get an HTTP 500 on each of these.
In Chrome when browsing to this page you can examine the Application Cache by going to the developer tools (F12) and going to the Resources tab.
1
Make sure that the 'Disable cache' check box is cleared as by default it is checked when you open up the developer tools and the browser will not retrieve the files needed from the cache.
2
Now by switching off your network connection or setting the Network throttling drop down to Offline (I disable my network card temporarily for a full test), your website should still view correctly and as the JavaScript has also been cached, it should function the same as well.
3
The main issue with the .manifest file is the browser does not know when the contents listed in it have changed unless the time stamp on the manifest itself has changed. One way to do this is to version the file and an even better way is to version it by using your application build number.
There are many issues with MVC serving up a .manifest file and the easiest solution I have found is to write out a physical file to the location the site is hosted in like this.
Which can be placed inside the Home/Index controller. Then add the path to the _Layout file like this.


<html lang="en" manifest="/Manifest/offline.manifest">


You will need to add write permissions to this directory for the IIS account so it can delete and write the file. Now if your build number increments each time you do a build and deploy, the manifest file will be regenerated and the client browser will pick up any changes.


Happy coding