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.


Through the life of this blog in its many guises I have used Blogger, Community Server and WordPress. Now comes the time to move again and I have opted to use MiniBlog; a project created by Mads Kristensen of Visual Studio Web Essentials fame.

About MiniBlog

MiniBlog is written in ASP.Net, C# and uses the website template in Visual Studio. It has a simple architecture and persists the blog posts in XML format as physical files on the web server drive. There is much more to this platform though such as:-

  • Windows Live Writer support
  • RSS and ATOM feeds
  • Support for robots.txt and sitemap.xml
  • Much much more…

Why move?

Although I have had a great experience using WordPress over the past few years, I have become more apparent of the bloat that is downloaded to the users browser in the form of Java Script and CSS. As a developer who strives to optimise web pages to get a better UX for the user, this didn't sit right with me.

old-js

This is the old sites Java Script showing over kb of data downloaded to the users browser.

old-css

The CSS is also loaded with the many styles from various plugins used in WordPress.

Wordpress is written in PHP and my experience is .Net, also the back end it's MySQL again a technology I am not 100% experienced with. So to make the changes to optimise the blog to a level I was happy with would leave me with either rewriting the entire theme and persistence layer or move to a technology stack I can have more control over. MiniBlog gives me this. I can create the style and layout I want with Razor and CSS and tweak the caching layer in the C# code. I can also get gulp up and running to run tasks to concatenate and minimize the css and Java Script files. Also like other projects I am working on, I can easily create a work flow in Team City to do the build and deploy.

What I had to do

Firstly I had to export all my blog posts from WordPress into a format that MiniBlog can understand. Again thanks to Mads Kristensen I could use the MiniBlogFormatter tool to get my posts into the correct format. This tool outputs each post to a seperate XML file. Then going through the current blog I found and separated post I wanted to keep that covered topics and technology that are still current. Then I created a temporary website in IIS to test these posts. It soon became apparent that the directory structure was different and MiniBlog uses a post directory to store files. I didn't want to loose any links to popular posts especially those that are referred to from other sites, so I created a url rewrite rule to do redirects to the new structure for users coming in on the old url.

Optimization

As I have mentioned in a past post concatinating and minification of Java Script and CSS can be achieved by using gulp. Once this was done, the number of files downloaded was much less than before.

new-js

Now only 16 files are downloaded as opposed to 46 in the old site.

new-css

Also with the CSS, there are only 2 as opposed to 7 requests.

With the images, I used Paint.Net to decrease the resolution and size for better performance.

Then in IIS, I navigated to the HTTP Response Headers section for the directories that contain the Java Script and CSS files.

iis 

Clicked on the ‘Set common headers’ link in the top right hand corner.

http-headers

Set the expires date to a date far into the future.

Comments

I was getting a lot of spam comments which Akismet took care of, so I had to find an alternative which would also protect me. I enjoy reading the comments and like to respond so switching off comments was not an option. I eventually went for Disqus which has a plugin architecture that was really simple to implement.

So there you have it, this is now the new blog site. It will change in style over the next few weeks as I make tweaks here and there, but with the CI/CD workflow I have in place this is very easy to work with.

What next?

I run all my sites of the same box which also has both MySQL and SQL Server running on it, so soon I can switch off MySQL, uninstall the PHP processor that it's part of IIS and hopefully free up some more resources.

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
 


Following on from the previous post where we already have a container that can run a static website inside IIS, this post will configure IIS to run a simple MVC website and deploy an application into it.

Setting up Containers for MVC Web Applications

So by calling Get-Container and Get-ContainerImage we should have our ServerCoreIIS container switched off and our 2 base images.

1

Firstly we are going to create a new container that will end up being our base image for MVC applications, so call the New-Container command like this:-

New-Container –Name ServerCoreIISForMvc –ContainerImageName ServerCoreIIS –SwitchName “DHCP”


2a

Then start the container using the Start-Container ServerCoreIISForMvc command and enter a PowerShell session.
Once we are in the session, run ipconfig to see what the IP address is, then we can check that IIS is running by browsing to it.

2b

Now we want to install all the features we need to run an MVC web site, which includes items such as .Net framework, so call this following command:-


Install-WindowsFeature Web-Default-Doc;Install-WindowsFeature Web-Dir-Browsing; Install-WindowsFeature Web-Http-Errors;Install-WindowsFeature Web-Static-Content; Install-WindowsFeature Web-Http-Logging;Install-WindowsFeature Web-Request-Monitor;Install-WindowsFeature Web-Stat-Compression;Install-WindowsFeature Web-Filtering;Install-WindowsFeature Web-Windows-Auth;Install-WindowsFeature Web-Net-Ext45;Install-WindowsFeature Web-Asp-Net45;Install-WindowsFeature Web-ISAPI-Ext;Install-WindowsFeature Web-ISAPI-Filter;Install-WindowsFeature Web-Metabase

3

That may take a while to run through.

4


5

When it is done you will be back at the PowerShell prompt and you shouldn’t need to reboot the container.
Exit out of the PowerShell session and stop the container. Now we need to create an image from this container, so call the Get-Container and pipe it to the New-ContainerImage command similar to what we did in the last post:-


Get-Container –Name ServerCoreIISForMvc | New-ContainerImage –Publisher AsteropeSystems –Name IISMvc –Version 1.0

6

Now you have an image of Server Core with IIS and MVC that you can create all future containers from.

Deploy an MVC application to a container

You may have a different method of how to deploy an application to a container, but for simplicity for this exercise I have a network share that I have copied an out of the box Visual Studio MVC application into. So create a new container from the IISMvc image.


New-Container –Name MvcSite1 –ContainerImageName IISMvc –SwitchName “DHCP”

Start it up and enter a PowerShell session and map a network drive like this:-

net use z: \\Server01\Share PASSWORD /user:USERNAME

Where you enter your network credentials for USERNAME and PASSWORD.

Now delete the default IIS website that resides in inetpub\wwwroot

Remove-Item C:\inetpub\wwwroot\iisstart.htm
Remove-Item C:\inetpub\wwwroot\iisstart.png
Remove-Item C:\inetpub\wwwroot\aspnet_client


Then recursively copy all files from the newly mapped Z drive to this location.


Get-ChildItem -Path Z: | % { Copy-Item $_.fullname C:\inetpub\wwwroot -Recurse -Force}

7a

Get the containers IP address and browse to it and there it is, an MVC application running from a container.

7b

So now you can quickly remove containers using the Remove-Container command and recreate a new container based off the IISMvc image as and when you need to.


Happy coding.


Creating an IIS Base Image for Containers

Now we have a base image from the last post, we can use it to create other images and containers. Enter a PowerShell command and call Get-ContainerImage, we should see our WindowsServerCore image.
1
For the sake of this demonstration we will let our containers get an IP address from DHCP in the network, other situations will lead to different DHCP configurations with the containers and their IP address as completely throw away.
So again in the host machine create a new VM switch, I have it mapped to my External switch which will handle the DHCP.


New-VMSwitch –Name DHCP –NetAdapterName Ethernet


2
3
Now we create a new container which will become our base IIS image, so call

New-Container –Name ServerCoreIIS –ContainerImageName WindowsServerCore –SwitchName “DHCP”


4
Then start it up with Start-Container –Name ServerCoreIIS
5
We will need to enable the IIS feature, so enter a PowerShell session.
6
Then invoke the command to install the Web Server feature.


Invoke-Command –ScriptBlock {Install-WindowsFeature Web-Server}


7
It will run through and should show an Exit Code of Success
8
9
Get the IP address.
10
We should see the typical IIS welcome page when we browse to it.
11
Now call Stop-Container ServerCoreIIS
12
We now need to create an image from that container, so call the Get-Container command and pipe it to the New-ContainerImage like this.


Get-Container –Name ServerCoreIIS | New-ContainerImage –Publisher YourCompany –Name ServerCoreIIS –Version 1.0


13
I have named both the container and image the same so I can easily determine the relationship.
14
When calling Get-ContainerImage we should see our 2 base images.
15
Now we can create any number of containers based off the ServerCoreIIS image like this.
17
Start one up, enter a PowerShell session using Enter-PSSession –ContainerName “IISWeb01” –RunAsAdministrator and get the IP address
18
We should then see the IIS welcome page again when we browse to that address.
19
So now we have a static website running from c:\inetpub\wwwroot on the container. In the next post I will configure the base IIS image to run an MVC website and create a container from that.


Happy coding.