Steve Michelotti

A .NET Developer's Toolbox

  Home  |   Contact  |   Syndication    |   Login
  193 Posts | 0 Stories | 1077 Comments | 51 Trackbacks

News

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Archives

Post Categories

Code

Publications

Friday, June 7, 2013 #

Thanks to everyone who attended my presentation at last week’s CMAP code camp. All code samples and slides can be found here.


Monday, May 6, 2013 #

A few months back, Ryan Niemeyer posted about a simple editor pattern for Knockout.js (anyone doing any significant Knockout development should be subscribing to his blog). Historically, I have used the “protected observable” which Ryan outlined in a post in 2011. In short, there are times when you are typing in a value and you need to ability to be able to “accept” or “cancel” user changes. The idea is that in addition the the observables for your object, you have 3 methods: 1) update() – which stores the latest values in a “local cache”, 2) revert() – which reverts the entire object back to the previous state, and 3) commit() which updates the “local cache” to the latest state.

The resulting code from Ryan’s post looks like this:

   1:  var Item = function(data) {
   2:      this.name = ko.observable();
   3:      this.price = ko.observable();
   4:      this.cache = function() {};
   5:   
   6:      this.update(data);
   7:  };
   8:   
   9:  ko.utils.extend(Item.prototype, {
  10:    update: function(data) {
  11:      this.name(data.name || "new item");
  12:      this.price(data.price || 0);
  13:   
  14:      //save off the latest data for later use
  15:      this.cache.latestData = data;
  16:    },
  17:    revert: function() {
  18:      this.update(this.cache.latestData);
  19:    },
  20:    commit: function() {
  21:      this.cache.latestData = ko.toJS(this);
  22:    }
  23:  });

This is an extremely useful pattern that is used frequently in Knockout development. However, I wanted a way to quickly and easily apply this to any object I was working with.

Lately I’ve been working with TypeScript so my thought was to create a base class in TypeScript that any class could inherit from to give the commit/revert functionality. This actually turned out to be quite easy with TypeScript. The first step is the create a base class called “EditableItem”:

   1:  /// <reference path="knockout.d.ts" />
   2:   
   3:  module EditableExample {
   4:      export class EditableItem {
   5:          private cache: any;
   6:   
   7:          constructor() {
   8:              this.cache = function () { };
   9:          }
  10:   
  11:          revert() {
  12:              this.updateValues(this.cache.latestData);
  13:          }
  14:   
  15:          commit() {
  16:              this.cache.latestData = ko.toJS(this);
  17:          }
  18:   
  19:          updateValues(data) {
  20:              this.cache.latestData = data;
  21:   
  22:              for (var property in data) {
  23:                  if (data.hasOwnProperty(property) && this.hasOwnProperty(property)) {
  24:                      this[property](data[property]);
  25:                  }
  26:              }
  27:          }
  28:      }
  29:  }

The code is not much different from Ryan’s example but TypeScript let’s me work with class syntax. Notice I’m importing the TypeScript type definition file for Knockout – this can be found in the Definitely Typed repository. The revert and commit methods are practically identical. However, I wanted something more re-usable for assigning the values of the observables so I loop through each property of the data objects to do the assignment automatically. On line #24 above, the assignments happen by sending values into a function rather than assigning with the equals – this is because Knockout observables are all functions so we need to use function syntax. The JavaScript that TypeScript generates is not much different from the original example:

   1:  var EditableExample;
   2:  (function (EditableExample) {
   3:      var EditableItem = (function () {
   4:          function EditableItem() {
   5:              this.cache = function () {
   6:              };
   7:          }
   8:          EditableItem.prototype.revert = function () {
   9:              this.updateValues(this.cache.latestData);
  10:          };
  11:          EditableItem.prototype.commit = function () {
  12:              this.cache.latestData = ko.toJS(this);
  13:          };
  14:          EditableItem.prototype.updateValues = function (data) {
  15:              this.cache.latestData = data;
  16:              for(var property in data) {
  17:                  if(data.hasOwnProperty(property) && this.hasOwnProperty(property)) {
  18:                      this[property](data[property]);
  19:                  }
  20:              }
  21:          };
  22:          return EditableItem;
  23:      })();
  24:      EditableExample.EditableItem = EditableItem;    
  25:  })(EditableExample || (EditableExample = {}));

 

With this base class in place, it becomes a VERY easy matter to create sub-classes with this automatic functionality:

   1:  class Person extends EditableItem{
   2:      constructor(data: any) {
   3:          super();
   4:          this.updateValues(data);
   5:      }
   6:   
   7:      firstName: KnockoutObservableString = ko.observable();
   8:      lastName: KnockoutObservableString = ko.observable();
   9:      age: KnockoutObservableNumber = ko.observable();
  10:  }

 

This enables me to primarily just concentrate on my Person class without worrying about all of the plumbing details in the base class to make commit/revert work. Now we can use the Person object as follows:

   1:  var person = new Person({ firstName: "Steve", lastName: "Michelotti", age: 21 });
   2:  person.commit(); // commit current state
   3:  person.revert(); // reverts to previous state

 

You can customize this example even further for your application. For example, the constructor takes a data object typed as “any” but you could constrain this further – the underlying updateValues() function can still take any value. Additionally, you could consider passing the initial data object directly to the constructor of the base class – that is, pass it to the super() function. However, there is a major caveat you need to be aware of if you are thinking of going this route. Take a look at the generated JavaScript code for the Person class:

   1:  var Person = (function (_super) {
   2:      __extends(Person, _super);
   3:      function Person(data) {
   4:              _super.call(this);
   5:          this.firstName = ko.observable();
   6:          this.lastName = ko.observable();
   7:          this.age = ko.observable();
   8:          this.updateValues(data);
   9:      }
  10:      return Person;
  11:  })(EditableItem); 

Notice the call to the super() function is the first thing that is called. Then after that is the assignments to the observable fields. After that is the call to the updateValues() function. Therefore, if you want to pass the data directly to the super() function, you’ll need to explicitly assign each field as an observable before calling the super() function to avoid the fields being null when the EditableItem’s updateValues() function is trying to assign the observable values. The class would look like this:

   1:  class Person extends EditableItem {
   2:      constructor(data: any) {
   3:          this.firstName = ko.observable();
   4:          this.lastName = ko.observable();
   5:          this.age = ko.observable();
   6:          super(data);
   7:      }
   8:   
   9:      firstName: KnockoutObservableString;
  10:      lastName: KnockoutObservableString;
  11:      age: KnockoutObservableNumber;
  12:  }

Ultimately, I didn’t favor this approach because it requires me to put extra lines of code in my constructor as compared to just initializing the observables inline. Either way, TypeScript enables rich scenarios for code re-use and helping better organize your JavaScript into object-oriented code.


Monday, April 29, 2013 #

Thanks to everyone to attended my presentation on Web API at dotnetConf. It was a great virtual conference and I hope to participate in more of them in the future. Code samples and PowerPoint for my presentation can all be found here.


Monday, February 25, 2013 #

This Wednesday my son and I will be presenting “Teach Your Kid to Code” at BaltoMSDN. We did this presentation in November at CMAP and had a great turnout! We hope to see you (and your child!) on Wednesday night! This is the presentation abstract:

Have you ever wanted a way to teach your kid to code? For that matter, have you ever wanted to simply be able to explain to your kid what you do for a living? Putting things in a context that a kid can understand is not as easy as it sounds. If you are someone curious about these concepts, this is a “can’t miss” presentation that will be co-presented by Justin Michelotti (5th grader) and his father. Bring your kid with you to BaltoMSDN for this fun and educational session. We will show tools you may not have been aware of like SmallBasic and Kodu – we’ll even throw in a little Visual Studio. Concepts such as variables, conditionals, loops, and functions will be covered while we introduce object oriented concepts without any of the confusing words. Kids are not required for entry!


Wednesday, February 20, 2013 #

I just posted an article on my company’s blog on Sharing Code Between Windows 8 and Windows Phone 8. It covers portable class libraries, view model patterns, linking source files, and more. Check it out here: http://blog.appliedis.com/2013/02/20/sharing-code-between-windows-8-and-windows-phone-8/.


Wednesday, November 14, 2012 #

Thanks to everyone who came out to our CMAP presentation last week! Despite being Election Day, we had a packed house with almost 70 people including a large number of kids. My son loved having the clip-on microphone Smile and it was great having such an enthusiastic audience.

All code samples and PowerPoint can be found here.


Tuesday, November 13, 2012 #

Now that Azure supports .NET Framework 4.5, you can use all the latest and greatest available features. A common scenario is to be able to use Entity Framework Code First Migrations with a SQL Database in Azure. Prior to Code First Migrations, Entity Framework provided database initializers. While convenient for demos and prototypes, database initializers weren’t useful for much beyond that because, if you delete and re-create your entire database when the schema changes, you lose all of your operational data. This is the void that Migrations are meant to fill. For example, if you add a column to your model, Migrations will alter the database to add the column rather than blowing away the entire database and re-creating it from scratch.

Azure is becoming increasingly easier to use – especially with features like Azure Web Sites. Being able to use Entity Framework Migrations in Azure makes deployment easier than ever. In this blog post, I’ll walk through enabling Automatic Code First Migrations on Azure. I’ll use the Simple Membership provider for my example.

First, we’ll create a new Azure Web site called “migrationstest” including creating a new SQL Database along with it:

 

Next we’ll go to the web site and download the publish profile:

 

In the meantime, we’ve created a new MVC 4 website in Visual Studio 2012 using the “Internet Application” template. This template is automatically configured to use the Simple Membership provider. We’ll do our initial Publish to Azure by right-clicking our project and selecting “Publish…”. From the “Publish Web” dialog, we’ll import the publish profile that we downloaded in the previous step:

 

Once the site is published, we’ll just click the “Register” link from the default site. Since the AccountController is decorated with the [InitializeSimpleMembership] attribute, the initializer will be called and the initial database is created.

 

We can verify this by connecting to our SQL Database on Azure with SQL Management Studio (after making sure that our local IP address is added to the list of Allowed IP Addresses in Azure):

One interesting note is that these tables got created with the default Entity Framework initializer – which is to create the database if it doesn’t already exist. However, our database did already exist! This is because there is a new feature of Entity Framework 5 where Code First will add tables to an existing database as long as the target database doesn’t contain any of the tables from the model.

At this point, it’s time to enable Migrations. We’ll open the Package Manger Console and execute the command:

PM> Enable-Migrations -EnableAutomaticMigrations

This will enable automatic migrations for our project. Because we used the "-EnableAutomaticMigrations” switch, it will create our Configuration class with a constructor that sets the AutomaticMigrationsEnabled property set to true:

   1:  public Configuration()
   2:  {
   3:      AutomaticMigrationsEnabled = true;
   4:  }

We’ll now add our initial migration:

PM> Add-Migration Initial

This will create a migration class call “Initial” that contains the entire model. But we need to remove all of this code because our database already exists so we are just left with empty Up() and Down() methods.

   1:  public partial class Initial : DbMigration
   2:  {
   3:      public override void Up()
   4:      {
   5:      }
   6:          
   7:      public override void Down()
   8:      {
   9:      }
  10:  }

If we don’t remove this code, we’ll get an exception the first time we attempt to run migrations that tells us: “There is already an object named 'UserProfile' in the database”. This blog post by Julie Lerman fully describes this scenario (i.e., enabling migrations on an existing database).

Our next step is to add the Entity Framework initializer that will automatically use Migrations to update the database to the latest version. We will add these 2 lines of code to the Application_Start of the Global.asax:

   1:  Database.SetInitializer(new MigrateDatabaseToLatestVersion<UsersContext, Configuration>());
   2:  new UsersContext().Database.Initialize(false);

Note the Initialize() call will force the initializer to run if it has not been run before.

At this point, we can publish again to make sure everything is still working as we are expecting. This time we’re going to specify in our publish profile that Code First Migrations should be executed:

migrations-execcodemigpublish

 

Once we have re-published we can once again navigate to the Register page. At this point the database has not been changed but Migrations is now enabled on our SQL Database in Azure. We can now customize our model. Let’s add 2 new properties to the UserProfile class – Email and DateOfBirth:

   1:  [Table("UserProfile")]
   2:  public class UserProfile
   3:  {
   4:      [Key]
   5:      [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
   6:      public int UserId { get; set; }
   7:      public string UserName { get; set; }
   8:      public string Email { get; set; }
   9:      public DateTime DateOfBirth { get; set; }
  10:  }

At this point all we need to do is simply re-publish. We’ll once again navigate to the Registration page and, because we had Automatic Migrations enabled, the database has been altered (*not* recreated) to add our 2 new columns. We can verify this by once again looking at SQL Management Studio:

migrations-2newcols

 

Automatic Migrations provide a quick and easy way to keep your database in sync with your model without the worry of having to re-create your entire database and lose data. With Azure Web Sites you can set up automatic deployment with Git or TFS and automate the entire process to make it dead simple.


Tuesday, October 30, 2012 #

Next Tuesday I will be at the CMAP main meeting presenting Teach Your Kid to Code. Next Tuesday is of course Election Day so you have to make sure you vote early in order to get over to CMAP for the 7:00PM presentation. I will be co-presenting this talk with my 5th grade son. Here is the abstract:

Have you ever wanted a way to teach your kid to code? For that matter, have you ever wanted to simply be able to explain to your kid what you do for a living? Putting things in a context that a kid can understand is not as easy as it sounds. If you are someone curious about these concepts, this is a “can’t miss” presentation that will be co-presented by Justin Michelotti (5th grader) and his father. Bring your kid with you to CMAP for this fun and educational session. We will show tools you may not have been aware of like SmallBasic and Kodu – we’ll even throw in a little Visual Studio and Windows 8! Concepts such as variables, conditionals, loops, and functions will be covered while we introduce object oriented concepts without any of the confusing words. Kids are not required for entry!

I promise this will be an entertaining presentation! We hope to see you (and your kids) there. Click here for details.


Monday, October 15, 2012 #

I’ll be presenting at VS Live! December 10-14 in Orlando, FL. I’ll be presenting Azure Web Sites. This is the session abstract:

Azure Web Sites brings a whole new level of power and simplicity to cloud computing. This demo-heavy session will show numerous features that allow you to deploy your site in a matter of seconds. Whether you are building a completely custom app or deploying from one of the numerous templates provided (such as WordPress), you’ll be up and running in no time. Want to use Node.js or PHP and deploy from Git? No problem! Azure Web Sites gives you the power of elastic scaling while still providing streamlined development and an effortless deployment experience. This presentation will also cover features including monitoring, custom domains, working with SQL databases or more!

 

SPECIAL OFFER: As a speaker, I can extend $500 savings on the 5-day package. Register here: http://bit.ly/VOSPK19Reg  and use code VOSPK19.

The great part about Visual Studio Live!: four events in one! This year, the event will be co-located with SQL Server Live!, SharePoint Live!, and Cloud & Virtualization Live!. You can customize your conference agenda and attend ANY sessions from all four events. Register now: http://bit.ly/VOSPK19Reg


Sunday, October 7, 2012 #

Thanks to everyone who attend the C-Sharpen Up full-day event yesterday in Philly. It was a great event. The code samples and PowerPoint from my presentation can be found here.


Sunday, September 23, 2012 #

On October 6th, I’ll be presenting at C-Sharpen Up at Philly.NET at the Microsoft Malvern, PA location. I’ll be presenting along with Stephen Bohlen, Andy Schwam, and Danilo Diaz. This is a great one-day event that covers real-world usage of all major C# language features from C# 1.0 to C# 5.0. It also includes a great presentation on the SOLID principles by Stephen Bohlen. Registration won’t be open much longer. You can register here. Hope to see you there!


Tuesday, September 18, 2012 #

Thanks to everyone who attended my Azure presentation this past weekend at the TechGate conference in Reston. The code samples can be found here.


Sunday, July 1, 2012 #

Lately I’ve been playing with Kendo UI Mobile to build iPhone apps. It’s similar to jQuery Mobile in that they are both HTML5/JavaScript based frameworks for buildings mobile apps. The primary thing that drew me to investigate Kendo UI was its innate ability to adaptively render a native looking app based on detecting the device it’s currently running on. In other words, it will render to look like a native iPhone app if it’s running on an iPhone and it will render to look like a native Droid app if it’s running on a Droid. This is in contrast to jQuery Mobile which looks the same on all devices and, therefore, it can never quite look native for whatever device it’s running on.

My first impressions of Kendo UI were great. Using HTML5 data-* attributes to define “roles” for UI elements is easy, the rendering looked great, and the basic navigation was simple and intuitive. However, I ran into major confusion when trying to figure out how to “correctly” build master-detail views. Since I was already very family with KnockoutJS, I set out to use that framework in conjunction with Kendo UI Mobile to build the following simple scenario: I wanted to have a simple “Task Manager” application where my first screen just showed a list of tasks like this:

kendoui-tasks

 

Then clicking on a specific task would navigate to a detail screen that would show all details of the specific task that was selected:

kendoui-taskdetail

 

Basic navigation between views in Kendo UI is simple. The href of an <a> tag just needs to specify a hash tag followed by the ID of the view to navigate to as shown in this jsFiddle (notice the href of the <a> tag matches the id of the second view):

 

Direct link to jsFiddle: here.

That is all well and good but the problem I encountered was: how to pass data between the views? Specifically, I need the detail view to display all the details of whichever task was selected. If I was doing this with my typical technique with KnockoutJS, I know exactly what I would do. First I would create a view model that had my collection of tasks and a property for the currently selected task like this:

   1:  function ViewModel() {
   2:      var self = this;
   3:      self.tasks = ko.observableArray(data);
   4:      self.selectedTask = ko.observable(null);
   5:  }

Then I would bind my list of tasks to the unordered list - I would attach a “click” handler to each item (each <li> in the unordered list) so that it would select the “selectedTask” for the view model. The problem I found is this approach simply wouldn’t work for Kendo UI Mobile. It completely ignored the click handlers that I was trying to attach to the <a> tags – it just wanted to look at the href (at least that’s what I observed). But if I can’t intercept this, then *how* can I pass data or any context to the next view? The only thing I was able to find in the Kendo documentation is that you can pass query string arguments on the view name you’re specifying in the href. This enabled me to do the following:

  1. Specify the task ID in each href – something like this: <a href=”#taskDetail?id=3></a>
  2. Attach an “init method” (via the “data-show” attribute on the details view) that runs whenever the view is activated
  3. Inside this “init method”, grab the task ID passed from the query string to look up the item from my view model’s list of tasks in order to set the selected task

I was able to get all that working with about 20 lines of JavaScript as shown in this jsFiddle. If you click on the Results tab, you can navigate between views and see the the detail screen is correctly binding to the selected item:

 

Direct link to jsFiddle: here.

 

With all that being done, I was very happy to get it working with the behavior I wanted. However, I have no idea if that is the “correct” way to do it or if there is a “better” way to do it. I know that Kendo UI comes with its own data binding framework but my preference is to be able to use (the well-documented) KnockoutJS since I’m already familiar with that framework rather than having to learn yet another new framework.

While I think my solution above is probably “acceptable”, there are still a couple of things that bug me about it. First, it seems odd that I have to loop through my items to *find* my selected item based on the ID that was passed on the query string - normally, with Knockout I can just refer directly to my selected item from where it was used. Second, it didn’t feel exactly right that I had to rely on the “data-show” method of the details view to set my context – normally with Knockout, I could just attach a click handler to the <a> tag that was actually clicked by the user in order to set the “selected item.”

I’m not sure if I’m being too picky. I know there are many people that have *way* more expertise in Kendo UI compared to me – I’d be curious to know if there are better ways to achieve the same results.


Thursday, June 21, 2012 #

Thanks to everyone who attended my Web API presentation this Tuesday at DC DNUG. The code samples and PowerPoint can be found here: https://github.com/smichelotti/WebAPI-presentation

This includes “before” and “after” snapshots of the code including all snippets that were used during the course of the presentation.


Sunday, June 17, 2012 #

This Tuesday (July 19), I’ll be presenting the ASP.NET Web API at the DC DotNet Users Group.

Abstract:

Modern web applications have seen an explosion in Web API creation. Twitter, Facebook, Google, Azure, you name it – it is becoming essential to provide a Web API so that consumers can build applications and mashups on top of your services. Web 2.0 has shown a trend away from SOAP towards a REST architecture style. With the new ASP.NET Web API, Microsoft is now providing first-class support for HTTP services including tools to apply the richness of a REST architectural style. This demo heavy presentation will show how the new ASP.NET Web API will enable you to build rich HTTP services in a REST architectural style while leveraging custom media types, custom HTTP handlers, jQuery and more! The presentation will also cover new features of MVC 4 including Razor enhancements, Web Optimizations, and more.