Category: Web

Getting started with ASP.NET Web API part 1

Well, I am back. I have been working on a very large project the last couple of months that gently removed the spare time to blog about the things I care about. But I'm jumping in again.

What has happened since then?
Well, it is like the whole ecosystem has changed since last year. It's all about mobile and BYOD. No one develops for the desktop anymore. Computer sales are dropping. Even Intel is now focussing on tablets and laptops because of declining revenues.

Of course we .NET developers still have a lots of work in enterprises so no worries there. But, if you start building an app, you'd better consider building it for mobile as well.

That means we need to write applications in a platform independent manner. So it means we have to decouple our apps. We need to provide an API that any client application (phone, tablet or desktop) can consume.

So, this is the moment to dive into the ASP.NET Web API which is very lightweight if you want it to.

What are we going to build?
We are going to create an addressbook. It's a simple CRUD application.
This is What we need:
Visual Studio 2012.3
SQL 2012 Server Express

Next create a new database called AddressBook and execute this sql. Thanks to Brian Dunning.

Getting started with the Web API
Fire up Visual Studio and create a new empty Visual Studio Solution called AddressBook.
Add a new project to this solution -> Visual C# -> Web -> ASP.NET Empty Web Application called AddressBook.Api

In the Package Manager Console, type:

Install-Package Microsoft.AspNet.WebApi

Next add a new class and name it PersonController:
2013-07-19 10_37_56-AddressBook - Microsoft Visual Studio

Then make it look as follows:

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AddressBook.Api
    //class must inherit from the apiController
    public class PersonController : ApiController
        public IEnumerable Get()
            return new string[] { "Marie", "Tina" };

Now we must add a default route for the application. The routes are global to the application. So the place to configure the routes is in Global.asax. So go ahead and add a new Global Application Class file, and add the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.SessionState;

namespace AddressBook.Api
    public class Global : System.Web.HttpApplication

        protected void Application_Start(object sender, EventArgs e)
               name: "default",
               routeTemplate: "{controller}/{id}",
               defaults: new
                   id = RouteParameter.Optional

F5 and the result is like this:

2013-07-19 10_45_20-IIS 8.0 Detailed Error - 403.14 - Forbidden

Well that can't be good.

According to our route, however, we must explicitly enter the name of our controller in the URL. And then it works:

2013-07-19 10_47_49-localhost_54555_Person

Next time I show how to display the data from the AddressBook database.

PHP MVC for an ASP.NET MVC developer part 1. Setting the stage.

Jacqie has a little LAMP!

What if the customer is hosting their sites on a LAMP server? Let’s write some PHP! This has a few advantages over IIS hosting. It is super affordable and available. However. Can I use the MVC pattern in PHP? Can I do OO in PHP? Can I have a layered architecture?

Searching DuckDuckGo for PHP MVC frameworks returns lots of results and it seems there are many PHP MVC Frameworks. See this list, for example.  Now which one to choose? I want to be up speed as soon as possible. And that said, how to get that the PHP/MySQL stuff onto my Windows laptop?

Which PHP MVC Framework?

The PHP MVC framework I will use, should have a. enough documentation, b. support the latest and the greatest PHP version and c, be awesome. My winners are: CakePHP, Kohana (which is not that well documented and also pretty hard to use re the web but their website looks awesome) and YII.

Install the LAMP on Windows

To get a WAMP running, I picked the Uniform Server because it’s a small download and supports the latest PHP (5.4) and MySQL. It is also highly configurable and supports vHosts and stuff like that.

Download, extract and save it somewhere directly under the root of a drive. (D:)


Next, click Start_as_program.exe and start Apache and MySQL:


If that doesn’t work, just make sure you stop other webservers you might be running (run services.msc). The Uniform Server defaults to port 80.

When the services are started you see the default server displayed. The website live in the /www folder. Here you can put your php files.


So, what is the best PHP editor/IDE then? I installed Netbeans, because it is easier than Eclipse, according to this article and I want to get up and running asap.

And what’s so funny. Netbeans supports Git. Look at this:


Next time, you make coffee and I’ll be sure we have some CakePHP.

Make way for HTML5 the full experience in IE9

I installed IE9 Platform in March, tested it, tried out my websites and everything looked fine, but it was only until the release of last months Ie9 beta that I found out that our very own blog did not display correctly. The header appears to be broken in IE9 and this is most interesting since twentyten is a standard customizable theme of wordpress!

So it's time to find out what has changed in the world of HTML!

HTML5 and IE9 brings some cool new features we only could achieve using plug-ins like activeX, Silverlight, Flashplayers etc.
What does HTML5 mean?
No more codecs or frames.
New are footer, header, Navigation, Video, audio, canvas, article, svg
back from the old and recycled are <Ol> <dl> and <small> and also overlapping tags are allowed.

New ECMAScript 5 support - Supports ActionScript, JavaScript en JScript

Enhanced object Model
Find elements by: CSS Selectors API



Allows css syntax

QuerySelectorAll() API

It loads the page as soon as the parsing is finished.
HTML5 also enables local storage and remebers your webinput even after a refresh, this new method makes your web available when no internet connection is available, you can even edit and modify web entry off line, the changes will be sent to the server as soon as an internet connection is available again.

It also brings us new binary attributes, whom work, by just being there! Just plain code for video and audio, no flash or silverlight is needed, no plug-ins. full javascript API It works for regular and fullHD video.

code example:

<video src="kewlmuvee.mp4" autoplay controls></video>

We want to ad some user options so they can controll the vid!

<video src="muvee.mpg" id="video">
<button onclick="document.getElementById('video').pause()">
<button onclick="document.getElementById('video').play()">
<button onclick="document.getElementById('video').currentTime = 0">
Back to Beginning</button>

How cool is that!

Also a kewl new feature is Canvas, as a codejunky you don't want to draw a circle, you just want to Program it!

<p>HTML 5 Full Circle</p>
<circle id="myCircle" cx="50%" cy="50%" r="100"
onmousedown="alert('Itslet says Hi!');"/>

<canvas>: Drawing programatically on screen, make dynamic pages you can move around and even convert back to a savable format for the guest on your site!

SVG Vector based graphics available, you can manipulate elements like colours in an advanced way, like transparency  and multiple colours.
Multiple Web standard colours can be used in designing websites:
Hexadecimal colours, a very common used webcolour and start with a #.
HSL is a colour standard used for printed matter, (Hue, Saturation and lightness) and (Alpha)transparency

A new Font upcoming standard, which will also make it possible importing (multiple) Fonts “WOFF” in your css (read more about it at web open font format).
(URL) media/Fonttype.woff

With Media queries you can have multiple css types in one page for different media.
So your webpage will display in the correct format on your Phone, Ipad, browsertype etc.
e.g NO.css (Max-width px) with this info available the devices choose what css is loaded to display the site.

Gone in HTML5 but still available:
<Applets> use <embedded>
<big> use css
<blink> use css
<center> use css
<font> use css

But i can tell you about all this great features, but you just have to go and see for yourself, implementing HTML5 in all your webdevelopment will make the web faster, cleaner and simple!

To conclude with the wordpress 2010 theme, it does not seem like a wordpress error at, the css looks fine, so I tried a work around I found at wordpress , and changed the stylesheet at line 365 to "display : inline;"

Want more? Install Platform, IE9 and start by visiting this webpage

Ruby on Rails envy part 2 – The first webapplication

Fire up Putty and log on to our newish ROR virtual appliance!

Oh wait. First I have to think of something we are going to create. So how about a Marketplace app, where supply and demand meets? And since we're so into a free society, let's make it an app where no money is allowed. So we're going to exchange goods and services. What do we need?

  • List all open requests
  • Create a new request
  • Read and display a request
  • Update the request
  • Delete the request

That will be enough for now. So, what are the features of the request?

  • name - name of the requester (string)
  • contents - the textbody of the request (text)
  • title - the title of the request (string)

Now start up Putty and log on to the BitNami server.

cd /opt/bitnami/projects
rails fleemarket

This is something like File -> New Project -> ASP.NET MVC 2 application in Visual Studio. With this command, you'll create the complete web application in a folder 'fleemarket'. If I cd into this new folder I get to see:

root@linux:/opt/bitnami/projects/fleemarket# ls
app     db   lib  public    README  test  vendor
config  doc  log  Rakefile  script  tmp

Right, now let's run it. After all, in VS I can also start debugging right after the creation of my project:

ruby script/server

Anyhow, we'll get the following output as the server is starting. So we need to open up another instance of Putty for editing.

root@linux:/opt/bitnami/projects/fleemarket# ruby script/server
=> Booting Mongrel
=> Rails 2.3.5 application starting on
=> Call with -d to detach
=> Ctrl-C to shutdown server

So, let's create the Request class first.

root@linux:/opt/bitnami/projects/fleemarket# ruby script/generate scaffold request requester:string title:string contents:string
      exists  app/models/
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/requests
      exists  app/views/layouts/
      exists  test/functional/
      exists  test/unit/
      create  test/unit/helpers/
# etc 

So, Rails created a controller and a view apparently. And now for the database.

root@linux:/opt/bitnami/projects/fleemarket# rake db:migrate
(in /opt/bitnami/projects/fleemarket)
==  CreateRequests: migrating =================================================
-- create_table(:requests)
   -> 0.0040s
==  CreateRequests: migrated (0.0042s) ========================================

I am done. And then check out what I've just created. A complete CRUD thing with a database.

Next time, let's check out what just happened under da hood.

ASP.NET MVC 2 and MongoDb Part 4 – First steps with jQuery, AJAX and JSON

In the past articles we created a simple application to submit bugs to a project. If you run the BugBase app, it looks like this:

It's ugly!
Let's add some style quickly. And since I am not a webdesigner, I Google for 'minimalist templates' and grab a free one, like this one, courtesy to Cardeo.

Masterpages are around for eons, so I won't go into the technical details of this phenonemon much. After creating a masterpage from Cardeo's design, BugBase looks like this:

And the bug submitform:

It's slightly better, no?

JavaScript, Ajax and JSON

Ajax is a technique that provide a snappier user experience through the use lightweight calls to the web server, in stead of full roundtrips to the server every time you submit a form. These asynchronous calls are initiated on the client using JavaScript and involve formatting data, sending it to a web server, and parsing and working with the returned data. While most browsers can construct, send, and parse XML, JavaScript Object Notation (or JSON) provides a standardized data exchange format that is better-suited for Ajax-style web applications. (Okay, I didn't write the last paragraph myself, Microsoft did. But I never found a more clever desription of the JQuery. AJAX and JSON triade.)

So, let's Ajaxify the Bug submit form. Let's make use of the jQuery Form Plugin, which actually does everything for you. Just copy jquery.form.js to the Scripts folder and make references in the head sections of Create.aspx (or in the BugBase.Master).

Next, I'm going to go ahead and add my own .js file (Add, New Item) to the scripts folder for my jQuery code. Also add a reference to this script:

<title>BugBase the Bug submitting app</title>
 <link href="../../Content/style.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
 <script type="text/javascript" src="../../Scripts/jquery.form.js"></script>
  <script type="text/javascript" src="../../Scripts/BugBase.js"></script>
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />

Next thing we need to do, is add an ID to the /Bug/Create form. As you can see, the HTML is rendered with the help of HTML Helpers (hm, so that's where those helpers get their names from) but I am not sure if HTML is better with or without these helpers. So, I just click on View Source in my browser and copy the generated HTML to Create.aspx. Next, I can add an ID to the form, which is important because this is how the jquery.form.js references the submit form.

<form action="/Bug/Create" method="post" id="BugSubmitform"> 
            <div class="editor-label"> 
                <label for="Name">Name</label> 
            <div class="editor-field"> 
                <input id="Name" name="Name" type="text" value="" /> 
            <div class="editor-label"> 
                <label for="Description">Description</label> 
            <div class="editor-field"> 
                <textarea cols="20" id="Description" name="Description" rows="2"> 
                <input type="submit" value="Create" /> 

Next step is edit the (still empty) BugBase.js and add the following code:

$(document).ready(function () {
        dataType: 'json',
        success: function (response) {
              $('h6').text("Bugname: " + response.Name + ".  
                     And the description is: " + response.Description);

Hmm, this is pretty self-explanatory I think? The first line you should know by heart if you plan to write more jQuery.
The next thing you see how we reference the id of the form, i.c. #BugSubmitform. So the form plugin knows at which point it should wake up. Then we are specifying the dataType, which is json. On success, we're going to display an alert, with the Description of our bug. Also, we will display the bug name and bug description between H6 tags, which I added on the Create.aspx page.

You see, 'response' in line 5 is actually the submitted bug serialized in json format. So, we can use all the properties of the Bug class here!

We're not completely finished though. We'll have to make sure the Create function of our controller actually returns JSON. Which is in fact very easy:

public ActionResult Create(Bug bug)

            if (Request.IsAjaxRequest())
                return Json(bug);

            return new RedirectResult("Create");

That's it. Let's try it.

To see that we really really Ajaxified things, we should fire Firebug form Firefox. If you check out the console, you'll notice the XMLHttpRequest, which proves that this was an AJAX request and the returnformat is JSON:

So now we know how we can speed up our app by using AJAX and jQuery and how we can provide the user feedback with the JSON result. As soon as I completed the BugBase app, I will post it here for you to download.