Catchy title, but it explains exactly what is in this post.
Windows Runtime Component
What is WinJS?
Creating the app
Firstly create an app using the basic WinJS template in Visual Studio.
Choose the target and minimum versions.
Now a new project is needed to be added to the solution, so right click the solution.
Choose Windows Runtime Component under the C# collection.
Right click the references of your main UWP project and add this component.
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.
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.
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:-
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.
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:-
- Create a copy of the existing database on the local machine
- Reverse engineer the database to classes that can be used for Code First migrations
- Enable migrations
- Create a manual empty migration to tell EF that both model and database are in sync
- Disable migrations for all but local changes
- 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.
By default this will create a context with the name MyDbContext like this:-
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.
As this tool uses a t4 template to generate the classes, it is easily configurable for example to change the context class name.
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:-
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:-
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.
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:-
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.
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.
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.
So when the admin staff adds a new Member they choose the Portal Member Type.
Then simply add the necessary details and save.
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.
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.