# Monday, August 1, 2016
Monday, August 1, 2016 2:20:00 PM (GMT Daylight Time, UTC+01:00)
# Wednesday, May 18, 2016

The Newtonsoft.Json library contains a number of tools for working with JSON from within your .NET application.

New ASP.NET applications created in Visual Studio already contain a reference to the Newtonsoft.Json library. But if you want to add the library to a different project type or if you want to update the version installed by default with an ASP.NET application, you can right-click your project in the Visual Studio Solution Explorer and select "Manage NuGet Package..." and search for Newtonsoft.Json. Select the "Newtonsoft.Json" package (Fig 1) and click either "Install" or "Update".

Newtonsoft is very good at serializing .NET objects into JSON objects.

One feature that I find useful is its ability to rename attributes in my classes. For example, if I have a class named "SocialSecurityNumber" in my C# class and the client consuming my JSON object expects that same property to be named "ssn", I can make this transformation declaratively by adding the JsonProperty attribute to the class property, as shown in Listing 1.

[JsonProperty("ssn")]
public string SocialSecurityNumber { get; set; } 

By convention, C# developers tend to name public properties with mixed case (capitalize the first letter of each word); while JavaScript and JSON developers tend to name properties using Camel casing (capitalize the first letter of each word, except the first word). In the past, I used the JsonProperty attribute to accomplish this, renaming every variable that would be serialized to JSON, as in the following example:

[JsonProperty("firstName")]
public string FirstName { get; set; }
 
[JsonProperty("lastName")]
public string LastName { get; set; }

For projects with many objects and many properties, this can be a tedious task. Fortunately, I recently learned a shortcut.

ASP.NET contains a Formatters class that controls how items are formatted and Newtonsoft.Json can tap into this. The following code, when run at the start of your application, converts all properties to Camel-Case as you transform them to JSON.

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

I added this code to the Register method of the WebApiConfig class in my ASP.NET MVC project, so that it is run when the application starts up, before any serialization is done.

Another useful setting is to add carriage returns and line feeds to the JSON that is created. This has the disadvantage of making your JSON slightly larger; but it makes it much easier for human beings to read, which can be very useful during debugging. This is accomplished with the following line:

settings.Formatting = Formatting.Indented; 

The full listing in the Register() method is shown below:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

Using the tools in the Newtonsoft.Json library, we can easily adhere to the conventional naming conventions of whatever platform in which our data is used.

C# | JavaScript | Web
Wednesday, May 18, 2016 8:18:48 PM (GMT Daylight Time, UTC+01:00)
# Sunday, May 15, 2016

In an earlier article, I described how to call the Cognitive Services API from JavaScript. The key parts of the code (using the jQuery library) is shown below:

var subscriptionKey = "cd529ca0a97f48b8a1f3bc36ecd73600";
var imageUrl = $("#imageUrlTextbox").val();
var webSvcUrl = "https://api.projectoxford.ai/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=true&returnFaceAttributes=age,gender,smile,facialHair,headPose,glasses";
$.ajax({
    type: "POST",
    url: webSvcUrl,
    headers: { "Ocp-Apim-Subscription-Key": subscriptionKey },
    contentType: "application/json",
    data: '{ "Url": "' + imageUrl + '" }'
}).done(function (data) {
        // ... 
        // Code to run when web service returns data...
        // ...
        }); 

Do you spot the problem with this code?

Although it works very well from a functional point of view, it has a security flaw” As with all Cognitive Services APIs, the Face API requires you to pass a key in the header of your HTTP request. Because there is no easy way to hide this key, it is easy for a hacker to steal your key. Using your key, they can make calls and charge them to your account - either using up your quota of free calls or (worse) charging your credit card for their calls.

One way to hide the key is to make the call to Cognitive Services from a custom web service. This web service can be a simple pass-through, but it allows you to hide the key on the server, where it is much more difficult for a hacker to find it.

We can use Web API to create this custom web service. With Web API, is a simple matter to store the Subscription Key in a secure configuration file and retrieve it at run time. The relevant code goes in an ApiController class as shown below.

// POST: api/Face
public IEnumerable<Face> Post([FromBody]string imageUrl)
{
    return GetFaceData(imageUrl);
} 
 
public static IEnumerable<Face> GetFaceData(string imageUrl)
{
    var webSvcUrl = "https://api.projectoxford.ai/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=true&returnFaceAttributes=age,gender,smile,facialHair,headPose,glasses";
    string subscriptionKey = ConfigurationManager.AppSettings["SubscriptionKey"];
    if (subscriptionKey == null)
    {
        throw new ConfigurationErrorsException("Web Service is missing Subscription Key");
    }
    WebRequest Request = WebRequest.Create(webSvcUrl);
    Request.Method = "POST";
    Request.ContentType = "application / json";
    Request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
    using (var streamWriter = new StreamWriter(Request.GetRequestStream()))
    {
        string json = "{"
        + "\"url\": \"" + imageUrl + "\""
        + "}"; 
 
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close(); 
 
        var httpResponse = (HttpWebResponse)Request.GetResponse(); 
 
        string result = "";
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }
        httpResponse.Close(); 
 
        List<Face> faces = JsonConvert.DeserializeObject<List<Face>>(result);
        return faces;
    }
} 

Of course, we could also use the .NET library to abstract the call to the Face API, but I wanted to keep this code as close to the original JavaScript code as possible.  This method returns a List of Face objects. The Face object maps to the JSON data returned by the Face API. You can see this class below.

public class Face
{
    public string FaceId { get; set; }
    public FaceRectangle FaceRectangle { get; set; }
    public FaceLandmarks FaceLandmarks { get; set; }
    public FaceAttributes FaceAttributes { get; set; }
}

Now, we can modify our JavaScript code to call our custom API, instead of calling Face API directly, and we can eliminate the need to pass the key from the client-side JavaScript, as shown below:

var imageUrl = $("#imageUrlTextbox").val();
webSvcUrl = "api/face";
$.ajax({
    type: "POST",
    url: webSvcUrl,
    data: JSON.stringify(imageUrl),
    contentType: "application/json;charset=utf-8"
}).done(function (data) { 
// ... 
// Code to run when web service returns data...
// ...
}); 

In this listing, we have removed the Subscription-Key from the Header and we have changed the Web Service URL. This is JavaScript is calling a web service in its own domain, so it is trusted. The default Cross-Site scripting settings of most web servers will keep JavaScript outside this domain from accessing our custom web service.

This pattern works with any of the Cognitive Services APIs. In fact, it works with any API that requires the client to pass a secure key. We can abstract away the direct call to that API and hide the key on the server, making our code more secure.

Code

  • You can find the full code of the sample described above here.
  • You can find the code for the “unprotected” sample here.
Sunday, May 15, 2016 12:50:49 AM (GMT Daylight Time, UTC+01:00)
# Saturday, March 26, 2016

In the last article, we described the 2-way data binding with the ng-binding directive. In this article, I will introduce the ng-repeat directive.

Recall that a directive is a well-known attribute defined by AngularJS or your AngularJS application that is applied to an HTML element to provide some functionality.

The ng-repeat directive acts in a similar way to foreach loops or other constructs in a programming language. We point ng-repeat to an array of objects and Angular will loop through this array, repeating the HTML contained in the attributed element once for each element in the array.

In the following example, our controller creates an array of "customers" and adds it to the $scope directive, making the customers stateful and available to the HTML. Each customer has a firstName, lastName, and salary property.

var app = angular.module("myApp", []);
app.controller("mainController", function($scope) {
    $scope.customers = [{
      id: 1,
      firstName: "Bill",
      lastName: "Gates",
      salary: 200000
    }, {
      id: 2,
      firstName: "Satya",
      lastName: "Nadella",
      salary: 100000
    }, {
      id: 3,
      firstName: "Steve",
      lastName: "Balmer",
      salary: 300000
    }, {
      id: 4,
      firstName: "David",
      lastName: "Giard",
      salary: 1000000
    }];
}); 

In our HTML, we can loop through every customer in the array by applying the ng-repeat directive to a <tr> element, such as:

<tr ng-repeat="customer in customers"> 

Because the array contains 3 customers, the <tr> tag and all markup within this tag (including any bound data) will be repeated 3 times. As a result, the user will see 3 rows.

Here is the markup for the entire table.

<table>
  <thead>
    <tr>
      <th>First</th>
      <th>Last</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="customer in customers">
      <td>{{customer.firstName}}</td>
      <td>{{customer.lastName}}</td>
      <td style="text-align:right">{{customer.salary | currency:$USD}}</td>
    </tr>
  </tbody>
</table> 

The beauty of this is that we don't need to know in advance how many customers we have or how many rows we need. Angular figures it out for us.

The ng-repeat directive allows us the flexibility of repeating HTML markup for every element in an array.

Saturday, March 26, 2016 11:35:00 PM (GMT Standard Time, UTC+00:00)
# Friday, March 25, 2016

In the last article, we discussed Angular controllers. In this article, we will add code to a controller to do 2-way data binding.

The $scope object exists to hold stateful data. To use it, we add this object to the arguments of our controller, as shown in Listing 1.

app.controller("mainController", function($scope) {
...
} 

Because JavaScript is a dynamic language, we can create new properties on an object simply by assigning values to those properties. We can maintain state by adding properties to to the $scope object. For example, in Listing 2, we add the FirstName and LastName properties and assign the values "David" and "Giard", respectively.

app.controller("mainController", function($scope) {
  $scope.firstName = "David";
  $scope.lastName = "Giard"; 
}

Now that we have these values assigned, we can bind HTML elements to these properties in our web page, using the ng-bind attribute, as shown in Listing 3.

First: <input type="text" ng-model="firstName" />
<br /> 
 
Last: <input type="text" ng-model="lastName" /> 

We don't need to add the "$scope." prefix because it is implied. In this example, we bind these properties to 2 text boxes and the browser will display the property values.  But unlike the {{}} data binding syntax, this binding is 2-way. In other words, changing the values in the textbox will also change the value of the properties themselves. We can demonstrate this by adding a <div> element to the page to output the current value of these properties, as shown in Listing 3.

<div>Hello, {{$scope.FirstName}} {{$scope.LastName}}!</div> 

When the user modifies the text in the 2 textboxes, the text within the div immediately changes because both are bound to the same properties.

We can do the same with objects and their properties, as in the following example:

JavaScript:

$scope.customer = {
  firstName: "David",
  lastName: "Giard"
}; 

HTML:

First: <input type="text" ng-model="customer.firstName" />
<br /> 

        Last: <input type="text" ng-model="customer.lastName" />
By adding and manipulating properties of the $scope object and using the ng-model directive, we can implement 2-way data binding in our Angular applications.

Friday, March 25, 2016 10:26:00 AM (GMT Standard Time, UTC+00:00)
# Thursday, March 24, 2016

In the last article, I showed you how to set up your page to use Angular and do simple, one-way data binding.

In this article, I will describe modules and controllers.

A module is a container for the parts of an Angular application, including its controllers. This helps provide a separation of concerns, which helps us organize large, complex applications.

We create a controller in JavaScript with the following syntax:

app.controller("mainController", function() {
  ...
});

In the example above, we named the controller "mainController", but we can give it any name we want. The function argument contains the controller's code and we can pass into this function any Angular objects that we want the function to use.

One common parameter to pass to a controller function is $scope. $scope is a built-in object designed to hold stateful data. We can attach properties to $scope and they will be available in both the view (the web page) and the controller.

The ng-controller directive is an attribute that identifies which controller is available to a page or a section of a page. We can add this attribute to any element, but the controller is only available to that element and the objects contained inside it. If we add it to the body tag, it is available to anything within the body, as in the following example:

<body ng-controller="MyController"> 

which points to the MyController controller and makes it available to everything in the page body.

Once I do this, I can write JavaScript in this controller to add and update properties of the $scope object and those properties become available to the affected part of my page, as in the following example:

JavaScript:

var app = angular.module("myApp", []); 
 
app.controller("mainController", function($scope) {
  $scope.message = "Hello";
  $scope.customer = {
    firstName: "David",
    lastName: "Giard"
  }; 

HTML:

<body ng-controller="mainController">
  <h3>
    {{message}}, {{customer.firstName}} {{customer.lastName}}!
  </h3>
</body> 

In the above example, we use the one-way data binding to display the properties of $scope set within the controller. The output of this is:

Hello, David Giard

This is a simple example, but you can do what you want in a controller and anything created or manipulated in that function is availabe to your web page.

In this article, we introduced Angular controllers and showed how to use them in an Angular application.

Thursday, March 24, 2016 4:51:50 PM (GMT Standard Time, UTC+00:00)
# Wednesday, March 23, 2016
AngularJS is a popular framework that takes care of many common tasks, such as data binding, routing, and making Ajax calls, allowing developers to focus on the unique aspects of their application. Angular makes it much easier to maintain a large, complex single page application.

Angular is an open source project that you can use for free and contribute to (if you are skilled and ambitious).

As of this writing, AngularJS is on version 1.x. The Angular team is still actively working on the 1.x version; but they have already begun work on AngularJS 2.x, which is a complete rewrite of the Angular framework. AngularJS 2 is currently in beta and features some different paradigms than AngularJS 1. This series will initially focus on AngularJS 1, which has been out of beta for many months. In the future, after AngularJS is out of beta, I hope to write more about that version.

To get started with Angular 1, you need to add a reference to the Angular libraries.

You can either download the Angular files from http://angularjs.org or you can point your browser directly to the files on the Angular site. In either case, you need to add a reference to the Angular library, as in the examples shown below.

<script 
src="https://code.angularjs.org/1.5.0-rc.0/angular.js"></script> 

or

<script src="angular.js"></script> 

Angular uses directives to declaratively add functionality to a web page. A directive is an attribute defined by or within Angular that you add to the elements within your HTML page.

Each Angular page requires the ng-app directive, as in the examples below.

<html ng-app>

or

 
<html ng-app="MyApp"> 

The second example specifies a Controller, which is a JavaScript function that contains some code available to the entire page. We'll talk more about Controllers in a later article.

You can add this attribute to any element on your page, but Angular will only work for elements contained within the attributed element, so it generally makes sense to apply it near the top of the DOM (e.g., at the HTML or BODY tag). If I add ng-app to the HTML element, I will have Angular available throughout my page; however, if I add ng-app to a DIV element, Angular is only available to that DIV and to any elements contained within that DIV. Only one ng-app attribute is allowed per page and Angular will use the first one it finds, ignoring all others.

Once you have the SCRIPT reference and the ng-app attribute, you can begin using Angular. A simple use of Angular is one-way data binding. There are several ways to perform data binding in Angular. The simplest is with the {{}} markup. In an AngularJS application, anything within these double curly braces is interpreted as data binding. So, something like

The time is {{datetime.now()}} 

will output the current date and time. Below are a few other examples.

<h3>{{"Hello" + " world"}}</h3>
<div>{{5+2+3}}</div> 

which will output the following:

Hello World
10

If your controller contains variables, you can use those as well, such as:

<div>{x} + {y} = {x+y}! </div>

Although working with AngularJS can be complex, it only takes a small amount of code to get started.

You can see a live example of the concepts above at this link.

In this article, we introduced the Angular JavaScript framework; then, showed how to add it to your web application and perform simple, one-way data binding.

Wednesday, March 23, 2016 11:54:00 AM (GMT Standard Time, UTC+00:00)
# Tuesday, March 22, 2016

User expectations for web applications have increased exponentially the past few years. Users now expect applications to respond quickly to their interactions and to render appropriately for different size devices. In addition, users have pushed back against using browser plug-ins, such as Flash and Silverlight.

Developers can meet these expectations by writing an application that performs much of its activity on the client, rather than on the server. The default browser client languages are HTML, JavaScript, and CSS. But these are relatively small languages and they were not originally developed with the idea of building large, complex applications.

Enter: Frameworks. A framework is a combination of pre-built components and utilities that sit on top of HTML, JavaScript, and CSS to manage some of the complexity of large applications.

Some frameworks are very specific, such as jQuery which eases the process of selecting and acting on the DOM elements of a browser; and MustacheJS, which provides automatic data binding. And some are very general frameworks, such as Knockout, Ember, Angular, and React, that provide complex functionality for most aspects of your application and allow you to build custom modules of your own.

Of course, the frameworks themselves add overhead - both in terms of learning time for the developer and download time for the user.  For very simple pages, this overhead might not be worthwhile; but for even moderately complex applications, a framework can manage said complexity, making your code easier to maintain, deploy, debug, and test; and freeing you up to focus less on the application plumbing and more on the code that is unique to your application.

Choosing a framework can be overwhelming. You can find a list of hundreds of JavaScript frameworks and Plug-Ins at http://www.javascripting.com/. Some factors to consider when choosing a framework are:

Does it meet the needs of my application

Do you need a do-everything framework or just data binding. Is the User Interface the most important thing or is synchronizing with backend data more important. Each framework has its strengths. Determine what you need; then find the framework that suits you.

How difficult is it to learning

Look for a framework with good documentation and tutorials. Often, ease of learning is a function of your current knowledge. If you are already familiar with the Model-View-Controller pattern, it may make sense to use a framework that implements this pattern.

How popular is it?

This may strike you as a frivolous criterion, but a popular framework will have more people blogging about it; more people answering forum questions; and bugs will get found and fixed more quickly.

Will it be popular next year?

Future popularity is difficult to predict; but it may be more important than current technology. You are likely to keep this framework for a long time - possibly the life of your application and you want your technologies to remain relevant and supported.

Whichever framework you choose, you will learn it best by diving in and beginning your project.

Tuesday, March 22, 2016 11:18:00 AM (GMT Standard Time, UTC+00:00)
# Wednesday, February 24, 2016

semjs-large When I lived in Michigan, I was a regular attendee of the Southeast Michigan JavaScript meetup – a local user group that attracted close to a hundred attendees each month and excellent speakers from all over the country.

One thing I admired about this meetup is their habit of recording meeting presentations. 

Those recordings are now available on Microsoft’s Channel 9 site. You can view dozens of these presentations at https://channel9.msdn.com/Blogs/semjs.

In the past 2 weeks, over 50,000 people have watched these videos on Channel 9.

Below are some of the more popular presentations:

 
 
 
Wednesday, February 24, 2016 9:11:23 PM (GMT Standard Time, UTC+00:00)
# Tuesday, February 16, 2016

I spent years as a software consultant and I wrote a lot of web applications during that time.

I remember when I first discovered Active Server Pages  (which we now call "Classic ASP") and I remember how excited I was by this technology. It empowered me to write dynamic applications that the whole world could see.

When Microsoft introduced ASP.NET, I quickly embraced it and when ASP.NET evolved to MVC, I was excited to move to this new paradigm.

I even wrote a bit of JavaScript, enhancing my web applications with client-side validation and interactivity. I wrote even more JavaScript after discovering how jQuery made the DOM manipulation easier to write, debug, and maintain.

But, about 5 years ago, I stopped writing web applications. It wasn't because I disliked anything about them; it was only because my customers were looking for different solutions. So, for a few years, I wrote middleware services and web services and rich client applications and I built databases and I set up continuous integrations systems and I barely looked at web development.

But Web Development technologies did not stand still; if anything, they changed faster than almost any other area of software.

Web Development has moved largely from the server to the client. Interactions that were once handled by a form post and full page refresh are now done using Ajax calls to a web service and client-side DOM manipulation. An asynchronous callback from the server to client triggers a JavaScript function to update elements on the page, eliminating the need for a disruptive repainting of an entire page.

The user experience of a Single Page Application tends to be far superior to the older multi-page applications, so users are demanding more and developers are now writing large, complex applications that run almost entirely inside a browser.

JavaScript wasn't designed with this complexity in mind, so a number of JavaScript frameworks emerged to help developers manage this complexity. These frameworks take care of things like data binding, DOM manipulation, input validation, and separation of concerns, freeing developers to focus their efforts on business logic and other features unique to their own applications.

These frameworks help, but they come at a cost. It takes time to learn a new framework and each framework has its own set of rules and idiosyncrasies.

Even more challenging is the speed at which these frameworks are released. A year after the popularity of ember.js and backbone.js peaked, developers began flocking to Angular.js. Last year, Angular seemed to lose ground to React.js. It's hard to tell what will be the next hot JavaScript framework (Angular 2.0? Aurelia? Something else?), but the rate at which new frameworks appear is accelerating.

Of course, it is not practical to re-write every application every year, simply because you discover a new framework - even one with advantages over your existing framework of choice. And most of us don't have the time to become familiar with a new framework every few months. We have to balance the increased productivity of a new framework against the time spent learning (as opposed to building).

This is the world in which I now find myself as I return to Web Development after a half decade absence. Everything has changed and continues to change at a startling rate.

In many ways this constant innovation is exciting and energizing. But it can also be overwhelming as I try to select the appropriate tools from a plethora of options and as I spend the time and effort learning how to use these tools.

meerkats I feel like I'm in a science fiction movie where the hero departs the Earth at light speed; then returns to discover the planet is ruled by talking meerkats: All the rules have changed while I was gone and I need to adapt. Quickly.

The approach I've taken is to pick a JavaScript framework, learn it, and build an application with it. I chose Angular to start - partly because I had heard good things about it and partly because its popularity ensured I would be able to find samples, tutorials, videos, and other reference materials to assist me. Next, I'll rebuild this functionality in ReactJs, followed by some other framework, until I have a feel for the paradigms involved in JavaScript development and for the relative strengths of each framework.

You can track my progress at https://github.com/DavidGiard/tvdg and on this blog.

So far, I'm enjoying the ride.

Tuesday, February 16, 2016 2:41:04 PM (GMT Standard Time, UTC+00:00)
# Monday, November 16, 2015
Monday, November 16, 2015 9:39:00 AM (GMT Standard Time, UTC+00:00)
# Monday, October 19, 2015
Monday, October 19, 2015 3:00:40 PM (GMT Daylight Time, UTC+01:00)
# Monday, September 21, 2015
Monday, September 21, 2015 1:02:31 PM (GMT Daylight Time, UTC+01:00)
# Monday, August 24, 2015
Monday, August 24, 2015 9:46:19 PM (GMT Daylight Time, UTC+01:00)
# Saturday, August 22, 2015

Last week, I had a chance to attend, sponsor, and present at the Midwest JS conference in Minneapolis, MN.

I was excited because, I used to do a lot of web development but switched to other technologies a few years ago. During my time away from web development, JavaScript technology has had some amazing advances as many frameworks were created, rose to great popularity and fell out of favor to be replaced by a new framework. I watched from a distance as the web I knew changed from mostly server side code generating HTML to powerful client-side code calling back-end web services and dynamically updating content in the browser. Although my historical experience began with "classic" ASP and continued through ASP.NET Web Forms and MVC, I've spent the past few weeks learning how to build a site with Angular.

This conference featured very little Microsoft technologies and most of the attendees did not development with Microsoft tools. A quick glance around the room revealed more Macs than PCs. I was nervous because I didn't know many attendees and speakers and because I didn't know how they would respond to a Microsoft employee in their midst.

It turns out that I worried for nothing. I met so many people who were interested in hearing about what Microsoft was doing. Our support of open source technologies the past few years really resonated with this crowd and there was a lot of interest in tool like TypeScript.

I created a talk on Microsoft Edge - the new browser that ships with Windows 10 and replaces Internet Explorer. The audience was interested in the speed of this browser (it's a total rewrite of the rendering engine) and with its support of web standards. During Q&A, one attendee expressed frustration that the Edge team had not announced a version for the Mac.

It wasn't long ago that a non-Microsoft conference would have also been an anti-Microsoft conference. But I experienced none of this. Everyone I met kept an open mind about other technologies - including ours. And I learned a great deal from them about the tools and frameworks that they embrace.

I left with a favorable experience of the JavaScript community and a desire to connect with them more. Of course, my education in this area continues as I try to catch up with the advances of the past 4 years, but conferences like Midwest JS help.

Saturday, August 22, 2015 3:48:07 PM (GMT Daylight Time, UTC+01:00)
# Monday, August 17, 2015
Monday, August 17, 2015 9:41:30 PM (GMT Daylight Time, UTC+01:00)
# Monday, August 3, 2015
Monday, August 3, 2015 4:06:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, February 2, 2015
Monday, February 2, 2015 3:31:00 PM (GMT Standard Time, UTC+00:00)
# Monday, November 17, 2014
Monday, November 17, 2014 1:05:00 PM (GMT Standard Time, UTC+00:00)
# Wednesday, October 1, 2014

Here is my interview with Todd Gardner of Track:js, describing his company and how they used BizSpark and Azure to grow.

Wednesday, October 1, 2014 7:24:06 PM (GMT Daylight Time, UTC+01:00)
# Monday, September 1, 2014
Monday, September 1, 2014 10:25:23 PM (GMT Daylight Time, UTC+01:00)
# Monday, December 30, 2013
Monday, December 30, 2013 5:31:02 PM (GMT Standard Time, UTC+00:00)
# Monday, December 16, 2013

Episode 296

Ward Bell on Breeze

Monday, December 16, 2013 10:58:00 PM (GMT Standard Time, UTC+00:00)
# Monday, November 11, 2013
Monday, November 11, 2013 11:05:00 PM (GMT Standard Time, UTC+00:00)
# Tuesday, September 3, 2013

Overview

The Google GeoCode API offers a service for retrieving driving directions between 2 addresses.

Syntax

The service is exposed through a URI. The syntax of the URI is

http://maps.googleapis.com/maps/api/directions/output?parameters

output is the format in which I want to receive result – either “json” or “xml”. I prefer the simplicity of json.

parameters is an ampersand-delimited list of name value pairs to pass to the API. The parameters I care about are

Origin

The starting address

destination

The ending address

alternatives

”true”, if you want the service to return more than one possible route. Unless I have a reason to provide multiple routes, I prefer “false”

Units

”imperial” to return data in feet and miles; “metric” to return data in meters and kilometers. This should depend on the country where the data is going to be used.

Sensor

”true”, if I am using a sensor to provide location; otherwise “true”. I don’t own such a sensor, so I set this to false.

Sample Code

Here is a sample URI to request directions from my old office to my new one, returned as JSON data.

http://maps.googleapis.com/maps/api/directions/json?origin=31555 W 14 Mile Road, Farmington Hills, MI, 48334&alternatives=false&units=imperial&destination=26957 Northwestern Highway, Southfield, MI, 48076&sensor=false

This is a nice function to call from JavaScript. I prefer the simple jQuery syntax for making Ajax calls like this.

var startAddress='439 East 31st Street #214, Chicago, IL 60616';

var endAddress='30 North LaSalle St, Chicago, IL 60616’;

var requestUrl = 'http://maps.googleapis.com/maps/api/directions/json?origin=' + startAddress + '&alternatives=false&units=imperial&destination=' + endAddress + '&sensor=false';

$.ajax({ 
url: requestUrl, 
dataType: "json", 
type: "GET", 
data: {}, 
error: function (err) { 
$(#distanceDiv).html("Error calling Web Svc.<br/>Calculate."); 
}, 
success: function (data) { 
var distance = data["routes"][0]["legs"][0]["distance"].text; 
$(# distanceDiv).text(distance); 
} 
});

The code above calls the service; then parses the resulting JSON to retrieve the distance and displays that distance in a DIV with the ID distantDiv. In this example, I hard-coded the 2 addresses, but you could use jQuery selectors to retrieve the address from elements on the page or user input.

Response

Below is part of the Json response to the service call

JSON Results

Limitations

There are some limitations you should be aware of. I am a cheapskate, so I’m using the free version of this API. With the free version, I can only send 2500 addresses per day. If I try to send more, the service will respond with a status of “REQUEST_DENIED” and no results will be returned.

Also, Google expects you to display the results on a Google Map. I’m not sure how they enforce this, but they don’t allow you to use the Geocoding API to display data on someone else’s map.

Tuesday, September 3, 2013 6:02:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, June 24, 2013
Monday, June 24, 2013 12:47:31 PM (GMT Daylight Time, UTC+01:00)
# Monday, June 3, 2013
Monday, June 3, 2013 7:10:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, September 24, 2012
Monday, September 24, 2012 2:03:36 PM (GMT Daylight Time, UTC+01:00)
# Sunday, August 19, 2012

JavaScript’s popularity proves how useful people have found the language. Novices use it to add simple validations to web forms, while advanced build amazing applications with JavaScript.

Yet, for all its utility, many look at JavaScript with disdain and fear, pointing to dangerous features and to the difficult of dealing with the browser's Document Object Model.

In JavaScript: The Good Parts, Douglas Crockford distinguishes between the good features of JavaScript that make it and elegant and powerful language; and the bad parts that make it dangerous and difficult to understand. Crockford’s message is to use the good parts and avoid the bad parts and stop fearing JavaScript.

According to Crockford, most people misunderstand JavaScript and so they misuse it; then, they complain about the language.

Crockford acknowledges that the designers of JavaScript made some mistakes (global variables, for example), but that there are enough good features of the language to make it appealing to a wide range of users writing a wide range of applications. He notes that JavaScript succeeded as a platform for creating client code for the web – something that that the more powerful Java language attempted and failed badly – and that this proves JavaScript’s power.

Applications will be better and developers happier, notes Crockford, if developers avoid the bad parts of the language. For example, always use the "===" operator, which returns what most users expect because it doesn't do any type coercion. Avoid the confusion of the "==" operator, Crockford recommends.

Crockford's style is concise and straightforward. At fewer than 200 pages, the book has no room for distractions. Regular Expressions are presented and described and examples are shown how to use them. Crockford clearly describes Closures, a feature that is likely new to many developers; and he spells out how callbacks are implemented in JavaScript.

Before reading this book, I was unaware of implied semicolons in JavaScript and whey they can be dangerous. Crockford spelled out the dangers and how to avoid them very clearly.

JavaScript can be a great language if you confine your programs to using the best parts of the language and steer clear of most of the dangerous features. This book will help distinguish the two.

Sunday, August 19, 2012 3:36:23 AM (GMT Daylight Time, UTC+01:00)
# Monday, July 30, 2012
Monday, July 30, 2012 4:57:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, May 28, 2012
Monday, May 28, 2012 10:34:00 PM (GMT Daylight Time, UTC+01:00)
# Friday, May 4, 2012

At Codeslingers last night, someone pulled out some coding Katas. For those who don’t know, a Kata is a coding exercise that is designed to practice your programming skills, rather than to solve a particular business problem. I was handed the classic “FizzBuzz” problem. The assignment:

Create a function that will print the integers from 1 to 100 with the following exceptions:

  • If a number is divisible by 3, print the word “Fizz” in place of that number.
  • If a number is divisible by 5, print the word “Buzz” in place of that number.
  • If a number is divisible by both 3 and 5, print the word “FizzBuzz” in place of that number.

The output should look something like the following:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16

I started with a C# console application because that is the language with which I am most familiar. It was able to finish the following in under 2 minutes. It took me 5 minutes to write the unit tests.

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i < 100; i++)
        {
            var p = FizzBuzz(i);
            Console.WriteLine(p);
        }
        Console.ReadLine();
    }

    protected static string FizzBuzz(int i)
    {
        if (i % 15 == 0)
            return "FizzBuzz";
        if (i % 3 == 0)
            return "Fizz";
        if (i % 5 == 0)
            return "Buzz";
        return i.ToString();
    }
}

I only occasionally code in JavaScript, so I tackled that language next. Someone recommended using http://jsfiddle.net/
as an online IDE for writing and sharing JavaScript, so I tried it and liked it. Of course, JavaScript is a dynamic language and one of my big challenges was spelling things correctly without all the help Visual Studio provides when writing in a statically-typed language. In my case, I misspelled the id of a div, which cost me at least 15 minutes. I created the following boilerplate HTML:

<html>
    <body>
        <div id="fizzbuzz"></div>
    </body>
</html>

Then, I used the following JavaScript (plus a bit of jQuery) to output the FizzBuzz results:

for (i = 1; i <= 100; i++) {
    $("#fizzbuzz").append(function() {
        var newLine = i;
        if (i % 3 === 0) {
            newLine = "Fizz";
        }
        if (i % 5 === 0) {
            newLine = "Buzz";
        }
        if (i % 15 === 0) {
            newLine = "FizzBuzz";
        }
        var newDiv = $("<div>").text(newLine);
        return newDiv;
    });
}

A simple program like this provides a fun way to practice an old language and to learn a new language. Next up, I’ll try this program with F# and Ruby, since I have very little experience with these languages.

Friday, May 4, 2012 12:40:00 AM (GMT Daylight Time, UTC+01:00)
# Monday, January 16, 2012
Monday, January 16, 2012 4:15:00 PM (GMT Standard Time, UTC+00:00)
# Monday, June 27, 2011
Monday, June 27, 2011 7:25:37 PM (GMT Daylight Time, UTC+01:00)