Tuesday, 2 February 2016

WCF Known Types

WCF allows you to write web service methods that take or return objects of multiple types using the KnownType attribute. This is done by defining a base class and inheriting from this class for other classes that you want to use as parameters. The base type is decorated with the KnownType attribute for each inherited type and you use the base type as the parameter on your web service method.

Here's a quick example of a base class, derived class and using the KnownType attribute on the base class. It also includes a service contract with a web service method that accepts our base class.


When implementing the web service method, we can then check the type of the class we're being passed and react accordingly.

You can call this web service from your web front-end (here I'm using AngularJS):
$http.post(urlBase + '/Items/' + id, {'req': data});
To tell WCF which type you are passing to the web service method, you need to add a property to the object in the following format (that's two underscores):
__type: DerivedClass:#MyNameSpace
After a lot of experimentation, I could only see the object in the web service method as the base type. I finally got it working when I discovered that the __type property has to be the first property when the object is serialized to JSON. The following solves the problem by creating a new object in JavaScript with the __type property and then adds the properties from the original object:

  var d = {__type: 'DerivedClass:#MyNameSpace'};
  for (var i in data) {
      d[i] = data[i];
  }
  $http.post(urlBase + '/Items/' + id, {'req': d});

Sunday, 24 January 2016

Microsoft Web Platform Day

This week I spent a day with Microsoft at their Web Platform Day to learn about what's new with ASP.NET. Here are some notes I took back to my team of things we should look into implementing and some things that don't really fit into our platform but are interesting to know about.

Task Runners

Task Runners can be used to….run tasks! This is usually done as part of the build process for tasks such as minifying JavaScript and CSS. There are a few task runners out there such as Grunt, Gulp and Broccoli(?!) but Microsoft were recommending Gulp. These are integrated a bit better in more recent versions of Visual Studio and ASP.NET, but can be used in any web development project.

A few of the task plugins:

gulp-minify-css: minifies your CSS files removing comments, whitespace and new lines to reduce file size and make the site load quicker
gulp-uglify: minifies JavaScript and can also do stuff like shortening names of functions and variables in the minified version of your JavaScript to reduce file size
gulp-autoprefixer: some browsers implement their own CSS features which are prefixed with –webkit, -moz or –ms. This makes sure you have prefixes for all browsers if you use one of them
gulp-concat: bundles files into a single file (e.g. multiple CSS files into one, or multiple JavaScript files into one) to reduce number of requests made by the browser and improve performance
gulp-imagemin: Optimizes .png and .jpg images for the web

Tasks can be chained together in Gulp so that you could minify several CSS files and then concatenate into one. You can also set Gulp to watch for changes to files and run automatically when you make changes.

Performance & Best Practises

There are a few check-lists, site scanners and plugins that will check sites for performance and best practises. Site authentication often prevents site scanning websites from accessing sites but you can still check your work with a plugin such as YSlow. This will give a report with a rating for a page and a list of recommendations. Many of the recommendations are covered by the task runners mentioned above (minifying and concatenating). Another checklist worth reading through is http://webdevchecklist.com/.

Image sprites are a single image file containing multiple icons and CSS to pick out individual icons from the file. This reduces the number of HTTP requests made by the page and improves performance compared to requesting each image individually. Going even further, it is recommended that icon fonts are used, where appropriate, so that the icons can easily be scaled and their colour can be changed.

There are web.config changes that can be implemented for caching settings and compression of files but then ‘cache busting’ strategies should be investigated so that clients get the latest versions of files when caching is being used.

Entity Framework

Entity Framework is a Microsoft technology for working with databases and simplifies going between C# classes and database tables. It is recommended that you take a code first approach – write your classes, set up your database connection string and the tables can be automagically created in the database. You can create classes from an existing database but you can get into problems if you want to make database changes and then import again.

ASP.NET Web API

Used to create RESTful web services and integrates well with Entity Framework. A Visual Studio feature (‘scaffolding’) can automatically create web service methods for CRUD operations from your Entity Framework models. You can also easily add OData support to add filtering and sorting to you web services via a query string (e.g. “‘?$name eq ‘bob’”).

ASP.NET Smart Tags / Tag Helpers

These are ASP.NET tags used in your HTML which are rendered on the server. One example give was loading scripts based on the environment. This lets you deliver full JavaScript and CSS files in the development environment but minified versions in production.

Another example was fall-back href’s when loading scripts. You can refer to CDN versions of popular scripts such as jQuery to improve performance, but provide a fall-back URL to a version on your server if the CDN is not available or the file is no longer on the CDN.

Web Performance and Load Test

A new project template in Visual Studio 2015 allows you to simulate web site load and analyse results. The requests are generated from Azure so presumably there is a cost associated with it and I'm not sure how it would work with site authentication.

ASP.NET Core

Microsoft have released an open source version of ASP.NET which runs on Windows, Linux and OSX. This can handle as much as 8 times the traffic of an ASP.NET 4.6 site on the same server. This is largely achieved by allowing you to configure which pipeline features are used when handling requests. 

You can also ship your site bundled with the framework which avoids version dependency problems on the server.

Despite all of this goodness, it isn't finished yet and doesn't have a lot of the features of ASP.NET 4.6.

Azure

Some interesting Azure features were demonstrated.

Platform as a Service / Infrastructure as a Service:

With Infrastructure as a service, you get a virtual machine and look after the software, patches etc. With platform as a service, that is all handled for you and you just upload your code/content.

Deployment Slots:

You can set up deployment slots in Azure for different environments (dev, test, live etc.). You can also use slots for A/B testing or staged roll-out. You can easily switch slots around when you want to move from test to live.

Continuous Deployment:

Deployment slots can be linked to a source repository such as a GitHub branch and automatically update if code is committed to the repository.

Auto-Scale:

Azure can be set up to automatically scale to more servers (within set limits) when demand exceeds a specified threshold. It can also automatically scale down if demand drops below a set threshold. This lets you maintain availability without spending more than you need.

Azure Storage:

A cheap way to host static content with good performance.

Azure Cloud Explorer:

You can now debug code running on Azure from Visual Studio running locally.

Apps

There is a web standard being developed for a manifest file for web sites. Microsoft have a tool called ManifoldJS that uses this to generate app store apps for Windows, iOS, Android and Chrome from a website.

Saturday, 9 January 2016

Visual Studio Code and GitHub for Windows

If you have GitHub for Windows / GitHub Desktop installed and install Visual Studio Code, you may receive the error 'it looks like git is not installed on your system' when clicking on the Git icon. This is most likely because the path to the git executable git.exe isn't in your system path.





Locate the git executable

The first step is finding the path to folder that contains git.exe.

GitHub for Windows installs to C:\Users\<User>\AppData\Local\GitHub which can be shortened to %USERPROFILE%\AppData\Local\GitHub. Within this folder is a sub-folder starting PortableGit.... such as PortableGit_c7e0cbde92ba565cb218a521411d0e854079a28c. 

You can use a shortened name for this folder such as portab~1. To find this shortened name, navigate to the GitHub folder in the command prompt and run:
for /d %I in (*) do @echo %~sI

You might have to hunt around for the git.exe file in this folder. At one point I found it in a bin sub-folder but this appears to have changed recently to mingw32\bin (GitHub for Windows version 3.0.11).

My final path ended up being:
%USERPROFILE%\AppData\Local\GitHub\portab~2\mingw32\bin


Add to the system path

  1. Go to System Properties by opening the run dialog (Windows key + R) and opening 'control sysdm.cpl'
  2. Change to the Advanced tab and click on Environment Variables
  3. In the System variables section, click on Path and click Edit
  4. At the end of the value text add a semicolon and the path to the git executable
  5. Click OK, OK and OK to close System Properties
Restart Visual Studio Code and Git integration should now work.

Monday, 20 April 2015

Chrome ends support for NAPI (SharePoint 2013 plugin)

Netscape Plugin Application Programming Interface (NPAPI) is a cross-platform plugin architecture. SharePoint 2013 makes use of this API for a plugin for Chrome and Firefox that provides functionality such as allowing documents to be opened in the local application (such as editing Word documents in Word).

Google has slowly been phasing out support for NPAPI plugins in Chrome, but as is so often the case, you don’t notice these things until they are switched off.
The current version of Chrome (42) disables NPAPI plugins by default and in the future they will not be supported at all.


For now you can enable NPAPI by going to chrome://flags/#enable-npapi in Chrome and clicking enable. After restarting the browser, the plugin should work again but this is not a long term solution as this option will eventually be removed. It would appear that unless Microsoft can provide a plugin that doesn’t depend on NPAPI, Chrome won’t be able to provide the best experience for SharePoint 2013.

Tuesday, 20 May 2014

SharePoint 2013 - Getting the last modified date of solutions

I'm slowly starting to use more and more powershell since moving from SharePoint 2007 to 2013. When deploying and updating multiple solutions in a SharePoint farm (especially with multiple developers working in the same environment), it can be useful to know when a solution was last updated. I put together the following little script to output the name and last changed date of all solutions in the farm to a text file:



Start-Transcript -path lastmod.txt -append
Get-SPSolution | ForEach-Object { Write-Output ($_.Name + " - " + $_.LastOperationEndTime) }
Stop-Transcript

Sunday, 2 February 2014

CSS3 Responsive Menu Layout

I'm putting together a home automation / remote control system to run on my Raspberry Pi and allow me to control various devices around the house. I wanted to create a web interface that would work equally well on a laptop and phone which led me to put together a responsive web layout using CSS only which displays the navigation differently depending on the screen size.

Responsive Web Design is an approach to web development whereby a single dynamic layout provides an optimum experience regardless of the screen size or resolution it is being displayed on.

The viewport meta tag instructs mobile browsers to report a screen resolution proportional to the physical screen size. There is an excellent article on its use here.
<meta name="viewport" content="initial-scale=1.0;">
CSS3 media queries allow us to apply different CSS rules to elements depending on the screen size:

  /* mobile */
  @media screen and (max-width:540px)
  {
    .navmenu {
      text-align: center;
      margin: 0;
    }
  }
  
  /* desktop */
  @media screen and (min-width:540px)
  {
    nav {
      min-height: 200px;
      display: inline-block;
    }
  }

This allowed me to create the layout you can see here which displays a menu on the left hand side of the screen if the browser width is greater than 540 pixels and across the top of the screen for widths less than 540 pixels.

Desktop:


Mobile:


Thursday, 16 January 2014

Yet Another Raspberry Pi Remote Controlled Socket

There are a few blog posts about using remote controlled electrical switches with the Raspberry Pi but I thought I'd share my experiences and code.

I bought this set of three sockets and a remote - http://www.clasohlson.com/uk/Remote-Control-Switch-3-pack/18-2035 and a cheap set of a 433Mhz transmitter and receiver from eBay. The manual refers to the sockets as EMW200R.

I came across this link which was trying to achieve the same thing and suggested attaching the receiver to the sound card on a PC and recording the signal sent by the remote control using audio software such as Audacity to identity pulses being sent and their length. Originally my recordings seemed to show audio waves instead of on/off pulses until further reading mentioned that the receiver must be connected to a line in socket instead of a microphone input. After making this change I could clearly see the pattern of hi/low pulses and measure their length.

This similar link mentions that commands are made up of the socket group, socket number, command and sync. Each of these is made up of a series of high and low pulses. I found that my sockets used the same series of pulses for each of these with the exception of a different sync command and the pulse lengths being slightly different.

I put together some python code to control the sockets by passing command line arguments of the pin number (1 - 26), the socket group (A - D), the socket number (1 - 4) and the command (On or Off). Because it is using the GPIO port, the code needs to be run as root (using sudo).

To get the code to run using RASPBMC I needed to install the following:

sudo apt-get install python-dev
sudo apt-get install python-pip
sudo pip install rpi.gpio

The code is as follows:



I then wanted to set up a cron job to turn a lamp on at 5PM every day and off at 11PM. To do this I needed to enable cron in the RASPBMC settings (not required for other distributions) and then edit the root cron table using:
sudo crontab -e -u root
I added the following lines to turn a socket on daily at 5PM and off at 11PM:

0 17 * * * /usr/bin/python /home/pi/EMW200R.py 11 A 1 On
0 23 * * * /usr/bin/python /home/pi/EMW200R.py 11 A 1 Off