Null != Steve

Developer's Thoughts and Musings

Simple Quick Git Common Actions

Create Branch:

Switch to a new branch:

git checkout -b branch-name

Shows the branch your on highlighted by *

git branch

Add files – marks any files to be added

git add .

Check-in changes

git commit -a -m “message”   //I always use the -a even with the git add . usage

Merge (to master)

switch back to the branch you want to merge to

git checkout master

specify the branch you want to merge from

git merge branch-name

optional – remove that branch

git branch -d branch-name

to completely abandon a branch:

git branch -D branch-name //only if you really screw things up

Revert – or rather we can still undo the changes easily by having Git check out the previous commit with the checkout command (and a -f flag to force overwriting the current changes):

git checkout -f

 

Extra Content

Heroku

This is definite OT but to add a few bonus items :)

Initial creation (this assumes you setup heroku):

heroku create --stack cedar
Deploy:
git push heroku master
(if using rails: heroku run rake db:migrate)

Static Properties and Methods with Coffeescript

class Person
   @test: (input) ->
      return input
   @staticProperty : 10
   @get: ->
     return {name:'Steve'}
   nonStatic: ->
     return "non static"

console.log Person.test 'Hello World'  #result is 'Hello World'
console.log Person.get() #result is object
console.log Person.staticProperty   #result is 10

#console.log Person.nonStatic()  this is an error
person = new Person()
console.log person.nonStatic() #result is 'non static'

Should be fairly explanatory :)

KnockoutJs : Toggling CSS class

A common scenario with Javascript is toggling a set of elements based on the selected element add applying, removing css classes.  You’ll see this on menu items, etc… and in my case where we want to have styled ‘button’s instead of a radio list.

An example of this might be handling the selection of the button and then applying a class and removing any other classes, for example:

$(‘.year_item’).bind(‘click’, function(){
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
});

In my first attempt at such a toggle with knockoutjs, I followed a similiar route – calling back to my viewmodel :

setYear: function (year, event) {
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
myViewModel.year(year);
}

The binding in the html looks like this:

<ul data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.setYear” type=’button’/></li>
</ul>

This works fine.  However, I can do better – since KnockoutJs supports setting the CSS class on binding.

ie. <div data-bind="css: { profitWarning: currentProfit() < 0 }">

So let’s take this example and show how we can effectively toggle the CSS class based upon the value of the binding – using our example above:

<ul class=”bigButtons” data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.year, css:{selected_year: $parent.year() === $data}”  type=’button’/></li>
</ul>

That is it.  No more function required in the viewmodel.  To understand what happens here is to understand the $parent.year click event.  Basically in KnockoutJs 2.0 by default $parent.year takes the $data property as a parameter.  The year binding is set, which in turn triggers the css selection on all the items reevaluating if it should have that CSS appended.

This has proved to be very terse and valuable in our UI.

KnockoutJS ‘Addons’, etc…

This is not intended to be a full post – just wanted to highlight a few links to add ons to the javascript knockoutjs library I’ve been using on some recent projects:

Observable Dictionary :  github source  gist of example

Protected Observable: blog post with sample code  gist of example

KO ‘Datagrid’ : link to google group post  github source  samples

I’ll update this with more links – it would be great to have a knockoutjs community

Steve Michelotti has a KnockoutJs course of Pluralsight and an example of building a custom binding

Also just to add – I have an example of KnockoutJS with NodeJs on my github here with a few simple tests using jasmine-node for some specs, and QUnit showing some Knockoutjs test scenarios.

JavaScript Todos–Backbone with asp.net mvc

There are certainly plenty of articles, examples, etc… around creating the ‘Todos’ sample.  To learn more about different frameworks and a more complete example, check out Addy Osmani‘s examples here: http://addyosmani.github.com/todomvc/   This is a fantastic resource to learn about different available frameworks.

Most of these examples tend to use the localStorage.  Not that it’s a big deal, but I wanted to put together something very very simple that showed some connections between using Backbone.js to make calls to a backend server.  In this case, I have decided to use asp.net mvc.

The example uses IISExpress to be hosted.  To reduce some of the friction, there is no database, just a static List object on the server.  I am not handling edits in this simple example – just a GET call to show todos and POST call to add a new todo.

To get an example – you can get it on github https://github.com/sgentile/MvcBackbone

First, this is not a ‘how to use backbone’ nor a ‘how to use asp.net mvc’ – I’d probably fail you on both subject matters!  The goal here is to highlight the aspects of backbone that help in making the connection to the backend server.  Backbone is providing an abstraction over the ajax calls.  You certainly CAN use ajax directly if you want. 

So, let’s get started.   The ‘todo’ model is quite simple – see todo.js line 5 :

Todo = Backbone.Model.extend({
    // Default attributes for the todo.
    defaults: {
      content: "empty todo..."
    },
        // Ensure that each todo created has `content`.
    initialize: function() {
      if (!this.get("content")) {
        this.set({"content": this.defaults.content});
      }
    },
    
    url: "home/todos"
});

If you check the backbone.js document for Model url http://documentcloud.github.com/backbone/#Model-url

Returns the relative URL where the model’s resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "/[collection.url]/[id]", falling back to "/[urlRoot]/id" if the model is not part of a collection.

The key here is to let backbone know the url for Todos.  We will be making a ‘save’ call on our Todo model object when we add a new model  ( save: http://documentcloud.github.com/backbone/#Model-save ).  This will look for the url on the server:

the save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

 

The TodoFormView on line 38, handles connecting the forum submit call to our save function, which maps the form to the Todo model.  Calling ‘save’ directly on the model results in an ajax call – ie:

TodoFormView = Backbone.View.extend({
    initialize: function () {
        this.template = $("#formTemplate");
    },
    events: {
        "submit #todo-form": "save"
    },
    render: function () {
        var content = this.template.tmpl();
        $(this.el).html(content);
        return this;
    },
    save: function () {
        var val = this.$("input").val();
        var model = new Todo({ content: val });
        model.save();
        this.$("input").val('');
    }
});

The key items to see here is the save function call  – where we save the model – model.save();

So the ‘home/todos’ matches up to the HomeController Todos action – with is a new Todo, so therefore it cooresponds to the following:

        [HttpPost]
        public ActionResult Todos(Todo todo)
        {
            todo.id = Guid.NewGuid();
            TodoList.Add(todo);
            return Json(TodoList, JsonRequestBehavior.AllowGet);
        }

As you see, backbone is handling the underlying ajax POST calls to the server!

Obviously GET calls are equally as straightforward.  I have a collection of Todos defined:

Todos = Backbone.Collection.extend({
    model: Todo,
    url: "home/todos"
});

I am able to do a GET call with ‘fetch’ as seen below:

TodoListView = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, "render");
        this.collection.bind("change", this.render);
        this.collection.bind("add", this.render);
        this.collection.bind("fetch", this.render);

        todos.fetch({ add: true });
        
    },
    render: function () {
        //clear out the existing list to avoid "append" duplication
        $(this.el).empty();
        //use an array here rather than firehosing the DOM
        //perf is a bit better
        var els = [];
        //loop the collection...
        this.collection.models.forEach(function (todo) {
            //rendering a view for each model in the collection
            var view = new TodoItemView({ model: todo });
            //adding it to our array
            els.push(view.render().el);
        });
        //push that array into this View's "el"
        $(this.el).append(els);
        return this;
    }
});

The key here is the todos.fetch call.  You can learn more about collections and fetch here: http://documentcloud.github.com/backbone/#Collection-fetch

This is all for now, should be a good start – there is much to learn here obviously (ie bootstrapping). 

Next time, I hope to share more about using backbone with asp.net mvc and then add jquery mobile to the mix.  Thanks!

JavaScript: Revealing Module Pattern and Namespacing

This is a basic post regarding namespacing and revealing module pattern.  When starting a new JavaScript application it’s important to have a good starting foundation.  First let’s show how to use namespacing in JavaScript:

window._ns = window._ns || {};

_ns is attached to the global window object.  Alex MacCaw in his book ‘’JavaScript Web Applications’ describes this well:

We’re setting on the window object to ensure that it’s globally accessible.

Also, by using this pattern, it’s easy to see which global variables a script is declaring,

just look through the script for window references

Let’s show this in use, first using what is referred to as the singleton pattern:

_ns.Singleton = {
    _somethingConsideredPrivate: function () {
        document.write("Singleton doSomething complete<br/>");
    },
    doSomething: function () {
        this._somethingConsideredPrivate();
    }
};

 

_ns.Singleton.doSomething();   //note, everything is public – some use an underscore : _privateFunction : function … to denote private, but it’s still accessible

<html>
<head>
    <title>Module</title>
    
    <script src="/Scripts/Module.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <script>
            _ns.Singleton.doSomething();
        </script>
    </div>
</body>
</html>

But what if we want to use the revealing module pattern which gives us the concept of private and public ?

basically we return what is public.

_ns.RevealingModule = function () {
    var privateData = {
        message: "RevealingModule doSomething complete"
    };

    var privateFunction = function () {
        document.write(privateData.message);
    };

    var doSomething = function () {
        privateFunction();
    };

    return {
        //since returned - it's public:
        doSomething: doSomething
    };

} ();   //end of module

 

It’s usage pattern as follows:

<!DOCTYPE html>

<html>
<head>
    <title>Module</title>
    
    <script src="/Scripts/Module.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <script>
            _ns.Singleton.doSomething();
            _ns.RevealingModule.doSomething();
        </script>
    </div>

</body>
</html>

If you try to access the private function – it would fail:

 

_ns.RevealingModule.privateFunction();

would result in:

_ns.RevealingModule.privateFunction is not a function
[Break On This Error] _ns.RevealingModule.privateFunction(); 

I hope this helps clarifying namespacing and the revealing module pattern.  There are certainly some great resources to describe both. 

Recommended reading followup: http://www.klauskomenda.com/code/javascript-programming-patterns

Alex MacCaw’s book ‘JavaScript Web Applications’: http://shop.oreilly.com/product/0636920018421.do

Javascript/jQuery contains and not contains sample

<div class="navigationelementsContainer clear_fix">
{{each navelement}}
        {{if name != 'null'}}                             
            <div class="navigatorModifier pointer" data-name='${name.toUpperCase()}' data-modifier='${modifier}'>${name} (${count})</div>
        {{/if}}                                   
    {{/each}}
</div>

$(".navigatorModifierSearch").live('keyup', function (event) {
            var $navigationelementsContainer = $(this).parent().parent().find(".navigationelementsContainer");
            var searchTerm = $(this).val();

            if (searchTerm.length > 0) {
                $navigationelementsContainer.find('div[data-name*="' + searchTerm.toUpperCase() + '"]').removeClass("hideNavElement");
                $navigationelementsContainer.children().not('div[data-name*="' + searchTerm.toUpperCase() + '"]').addClass("hideNavElement");                
            } else {
                //make sure all are showing
                $navigationelementsContainer.children().removeClass("hideNavElement");
            }
        });

https://gist.github.com/1207961.js

 

Key section:

$navigationelementsContainer.find(‘div[data-name*="' + searchTerm.toUpperCase() + '"]‘).removeClass("hideNavElement");

$navigationelementsContainer.children().not(‘div[data-name*="' + searchTerm.toUpperCase() + '"]‘).addClass("hideNavElement");

Not the best blog post.. but it’s pretty nice way to select elements by attribute with ‘contains’ as well as ‘not contains’ Smile

‘Restoring’ Git after Upgrade to OSX Lion

I was surprised to find out my ‘git’ command didn’t work after upgrading to Lion.

It is still there (verify by checking for this directory: /usr/local/git/bin), just needs to be mapped.

I was able to find out that the git installer uses paths.d to add it to the path.

I went to /etc/paths.d and did ls  – but there was not git file.

open Terminal

cd /etc/paths/d

sudo vi git

enter /usr/local/git/bin at the top of the file (if new to vim, hit ‘I’ to enter ‘insert mode’)

hit escape – type :wq to save and quit

open new terminal – run ‘which git’

Should work now

Code Generation: T4Scaffolding with Custom C# Assembly

I’ve been working on using the T4Scaffolding to generate code in a project.  One of the things I want to accomplish is to keep the main code logic in a C# assembly and use the powershell couped with the T4 templating to just handle the code gen vs. the logic.

The first step required is to get the T4Scaffolding nuget package.  Next, we want to create our own custom scaffolder.  To learn more about creating a custom scaffolder, as well as to learn how MvcScaffolding is built on top of T4Scaffolding, you can read Steve Sanderson’s blog post series.

I will attach my code example, first let’s go through the series of steps here.

1. Create a C# solution with two class library projects, I used default ‘ClassLibrary’ and ‘Test’ to prototype and test out the concept.

2. In the powershell console, install the T4Scaffolding nuget package:

(make sure you have ‘classlibrary’ selected in the ‘default project’, ie

image

3. Create your custom scaffolder:

image

You should see the folder structure inside your project created, it will generate a simple example for you:

image

4. Next step is to create some code in our Test project that we can use in our template.  My example is simple – but shows a object graph common perhaps in your solution:

image

(see attached code sample)

5. Now that we have this code in place – time to get into our Generator ps1 code – please note, I’m a powershell newbie, so if there is a better way, ping me  Smile

I need to load the assembly, there are several ways to accomplish this:

image

(the # is commented out powershell).  It is required that we load the assembly so that ps can reflect over the types and be able to execute the c# code.

Now we want to execute our generator, my assembly is ‘Test’ with namespace ‘Test’ – with a Generator class that has a static  ‘Get’ call:

image

Now that we have our ‘Entity’ object – we can pass this entity to our t4 template to create our class:

image

I am adding a new property to the ‘Model’ called ‘Entity’ that contains our Entity from our Get() call.

Now take a look at the T4 template- I need to include the assembly and namespace’s that will be used:

image

Lastly, we can get to the property collection, looping through it to create a class member (or any other logic needed).

image

Note: there is a add-classmember cmdlet in T4 Scaffolding, but for now I had to resort to this because the performance of it at the time of this writing was horrific.

But regardless, this type of logic could be used for other things – ie. building up a fluent validator in a constructor, etc…

After building the code, we can run our custom scaffolder:

image

 

Hope this helps anyone else working through this.   The key was to get the correct assembly loaded code in the ps1 file and the correct ‘assembly’ and ‘import’ statements in my T4 template.

Attached is the source code.

Html5 & Silverlight– an opinionated post–‘what if’

Yes, it wouldn’t be in my character to hold off on yet another opinionated post!  Smile

Let me reference Davy Brion’s post on ‘why were going with html5 instead of silverlight’.  To break this down, what I see and continue to see is are the pros – the development environment, use of a single language (although minor I do see two here, we have XAML and C# – in same manner as Html + Javascript).  And yet the usability is down, it’s not as accessible, it’s a plug-in, etc…

And while I’m on this topic, I’d venture to say I believe the same solution I’m going to propose would be good for Adobe’s Flash/Flex applications as well.

I think the biggest concern I have isn’t whether ‘Linux’ can run Silverlight (we have Moonlight), it’s more along the lines of ‘any device anywhere’.  Let’s take the iPad or Xoom – these new devices, that I predict will continue to infiltrate businesses as they have consumers – will lead us to requests such as ‘why can’t I view this Silverlight webpart in my internal Sharepoint site that was done in Silverlight’.

There have been two tools that I know of, that in my opinion solve a big chunk of the plugin issue:  Google Web Toolkit (GWT) – and Script#.  Now, Script# was supposedly used on Microsoft’s Office on the web, but it’s currently done by one person and it’s not really supported, and it’s usage has some issues imo because of this.  So, for now I’ll just look at the model Google has provided with GWT.

GWT provides a common environment – a plugin in Eclipse – where you write java code.  There is an API to handle common dom tasks.  Similar to Silverlight, you typically would have asynchronous calls back to the server code through the GWT API.   Any client side behaviors are output as  javascript – in a best practice format.  The javascript is compressed.  The output uses compression and is minified.  In addition it created compiled javascript through Google javascript’s compiler.  That all said, I know there are issues with GWT, and my concern would be the flexibility of it, but I consider it the best conceptual solution to creating html/javascript using a single language.

So – that is my scenario – we have Silverlight that is producing a plugin that can’t run anywhere.  It can’t run on iPhone, iPad, Xoom, it can’t run on different systems.  It’s a ‘foreign entity’ in that it doesn’t comply with html standards and usability – that all said – the development environment of Silverlight is great – top of the line really – as your writing C# code and using a very flexible XAML.

My solution would be for Microsoft to shift how Silverlight is outputted.  I think the environment is good – the Blend, Silverlight, etc… dev experience is good.   My proposal would be to provide an option that the underlying Silverlight code OUTPUT generates compliant HTML5 source, compiled, compressed and minified javascript and CSS3.  So you would select your output – ‘XAP’, ‘HTML5’, ‘Mobile HTML5’, etc… and then thethe tooling would handle conversion of the events, elements, etc… in the XAML/code behind ie.  A XAML ‘storyboard/animation’ would be equated to a series of javascript animations – ie. jQuery animations.  XAML controls would output the corresponding html5 controls.  Binding would implement the html4 data binding, etc… I know this is no small task – but the benefit is huge.  Move forward a few steps, and we would have targeting capability – ‘create a HTML5 mobile equivalent’ for example. 

I think Script# was starting to take this path, it has the core fundamentals.  But just not the support it needed.  I’m not sure why Nikhil didn’t open source is at the very least.  Perhaps because Microsoft will eventually take it and use it – not sure.  It did provide what I would considering a R&D into the capabilities of taking C# to Javascript.

I want to say I’m not someone that thinks we need to hide away javascript.  I’m not necessarily looking at it that way.  I’m looking at the developers who are attached to and have been sold on all the benefits of Silverlight.  I’ve worked with Silverlight as well.  I like the client side architecture of it.  I liked working with XAML, etc… and see a ton of flexibility there.  Not that this is a big deal, but I see it as a ‘gateway’ for WPF developers to also be able to use those same skills to write to something that outputs html5.

It’s ironic, and I’m going to take note of this – the webforms model was an attempt to abstract away the web.  And it’s abstraction in many ways became a hinderance.  Doing simple formating requires knowing all these custom controls – how to bind and postback on a GridView for instance.  And what I’m proposing is even more of an abstraction. 

I truthfully would rather just see better tooling from Microsoft on HTML5/CSS and javascript – and to stop treating javascript like the redheaded stepchild. 

That all said, I see potential in Microsoft leveraging the development model of Silverlight to produce what Google has accomplished with the GWT.  So I would take that toolset and provide those capabilities.  Seemlessly to the point of being able to do things such as ‘creating a silverlight webpart that produces compliant html5’, etc…

I see value in several different directions for Silverlight – the embedded – with wp7, etc…, the out of browser ‘app’ model – where I think it makes the most sense for a future Microsoft AppStore – because these apps are well sandboxed, and then this final option of an HTML5/CSS3/Javascript output.

What do you think?

Post Navigation

Follow

Get every new post delivered to your Inbox.