Jonathan Creamer's Dev Diary Writing Coldfusion, .net, PHP, or anything interesting in my daily developing…

10Jan/120

Minify Javascript using UglifyJS and NodeJS

Minifying JavaScripts has many benefits. A few advantages are it reduces the amount of code the user has to download, removes unnecessary comments, and reduces the number of Http requests. There are many minify-ers out there, things such as YUI Compressor, JSMin, Google Closure Compiler, and UglifyJS.

I recently started using the standalone UglifyJS tool that can run in NodeJS. This makes the tool available via command prompt as well as accessing it inside of Node applications with require.

To use Uglify in Windows. First, download and install NodeJS. Once it is installed, you can then run applications in Command Prompt simply by typing node. It installs by default into C:\Program Files\NodeJS or C:\Program Files(x86)\NodeJS on a 64-bit machine.

It drops the node.exe, and the npm.bat file into that directory and makes it available in CMD by adding it to your %PATH%.

NPM is the Node Package Manager that was just recently made available for Windows. It allows you to download Node packages to be easily used in your projects.

The next step is to install UglifyJS and make it global so it’s available everywhere.

Open Command Prompt and run…

npm -g install uglify-js

This put’s the files for Uglify in the %AppData% file, usually around C:\Users\{username}\AppData\Roaming\npm\

As of 1/9/2012, there is a slight bug in the command to actually run Uglify, so in order to fix it, navigate to the folder just mentioned and find uglifyjs.cmd and replace it with…

:: Created by npm, please don't edit manually.
@IF EXIST "%~dp0"\"node.exe" (
  "%~dp0"\"node.exe"  "%~dp0\.\node_modules\uglify-js\bin\uglifyjs" %*
) ELSE (
  node  "%~dp0\.\node_modules\uglify-js\bin\uglifyjs" %*
)

Now, you will be able to just run Uglify by…

cd c:\place\where\files\are\
uglifyjs -o myFile.build.js myFile.js myOtherFile.js myAnotherFile.js etcetcetc.js

And wham bam, you’ll find a nicely compressed file. You can string along as many files as you need to compress; the –o flag tells Uglify where to place the built file. Then you could save the commands out to some build.bat file and run it at your plessure.

Cross posted on freshbrewedcode.com/jonathancreamer/2012/01/10/minify-javascript-using-uglifyjs-and-nodejs/

Filed under: Uncategorized No Comments
9Dec/110

BackboneJS modular app using RequireJS

Write the App

Everyone knows that large scale JavaScript applications can get out of control really quickly really fast. Tools like jQuery are helpful in providing easy access to the DOM, but provide little to no help when piecing together a full fledge application. You’ll begin writing a few selectors here and there, manipulating some data, making some Ajax requests, and next thing you know your knee deep in a big bowl of Spaghetti code!

Bring on RequireJS.

RequireJS is a framework that adheres to the ComonJS specification for Asynchronous Modular Definitions (AMD). See this post by a fellow brewer, Derek Greer for some more info on getting started with Requirejs.

The basic idea behind RequireJS and AMD is to separate your code into Modules, and by Modules, I mean this definition found by Nicholas Zakas…

Module: An independent self-contained unit of a spacecraft.

spacer

Here, each module can exist separately, or together with the rest of the space ship.

This is a common way to solve JavaScript architecture as well.

To build a BackboneJS app with RequireJS…

  1. Download RequireJS (I used the Sample Require + jQuery App)
  2. Download the Order plugin
  3. Download UnderscoreJS (Backbone depends on Underscore)
  4. Get one of the AMD versions of Backbone from @jrburke off of one of his optamd branches. I used this one https://github.com/jrburke/backbone/blob/optamd/backbone.js
  5. Create a folder structure, and files like… (Bold means create a new empty file)
    /r.js (Copy from the RequireJS download)
    /app/index.htm
    /app/scripts/
    /app/scripts/require-jquery.js (Copy from the RequireJS download)
    /app/scripts/main.js
    /app/scripts/app.js
    /app/scripts/order.js
    /app/scripts/lib/underscore.js
    /app/scripts/lib/backbone.js
    /app/scripts/routers/home.js
    /app/scripts/views/welcome.js
    /app/scripts/models/movie.js
    /app/scripts/collections/movies.js
  6. Build models, views, routers, and collections at your leisure

First up is the index.htm file…

<!DOCTYPE html>
<html>
<head>
<title>BackboneJS Modular app with RequireJS</title>
<script data-main="scripts/main" src="/img/spacer.gif"> 

Then there’s main.js. This is where you’ll define the base of how your application will load…

require.config({
    'paths': {
        &quot;underscore&quot;: &quot;libs/underscore&quot;,
        &quot;backbone&quot;: &quot;libs/backbone&quot;	</pre>

}
}); 

require([
	'order!libs/underscore',
	'order!libs/backbone',
	'order!app'
	],
	function(_,Backbone,app){
          app.init();
});

The require.config set’s up some paths for the modules that are defined with a name. Next, the require function takes in 2 arguments. First is an array of dependencies that main.js will load in. The order plugin makes sure that Underscore and Backbone get loaded in order as Require typically loads things in asynch which is bad for Backbone since it requires Underscore. Using the require-jquery verion includes jQuery 1.7 which now has AMD built in.  app references the app.js file you will create in a second. The function callback takes the loaded dependencies and passes them as arguments in the order you loaded them in, _, Backbone, and app.

Now for the app.js

define(['routers/home'], function(router){
    var init = function(){
        console.log(&quot;App Started...&quot;);
    };

    return { init: init};
});

Here we use define to create a new module. The first argument is an array of dependencies, and the second is a callback like the one on main.js which will fire once the dependencies have loaded. For now I am just requiring the home.js router.

The home.js router looks like…

define(['backbone','views/welcome'],function(Backbone,welcome){
    var homeRouter = Backbone.Router.extend({
        initialize: function(){
            Backbone.history.start();
        },
        routes: {
            '': 'home' // Default route
        },
        'home': function(){
            welcome.render();
        }
    });

    return new homeRouter();
});

Here we load in Backbone, and the welcome.js view…

define(['jquery','backbone','underscore', 'collections/movies'], function($, Backbone, _, movies){
    var welcomeView = Backbone.View.extend({
        el: &quot;#main&quot;,
        initialize: function(){
            this.movies = new movies();
            this.template = _.template($(&quot;#moviesTemplate&quot;).html());
            this.movies.bind('add', this.addMovie, this);
        },
        render: function(){
            this.movies.add({ name: 'Empire Strikes Back'});
            this.movies.add({ name: 'Jurrasic Park'});
            this.movies.add({ name: 'The Last Crusade'});
        }
        addMovie: function(model){
            $(this.el).append(this.template({ model: model.toJSON() });
        }
    });
});

This one loads in jQuery, backbone, underscore, and our movies collection which looks like…

define(['backbone','underscore','models/movie'],function(Backbone,_,movie){
    var movies = Backbone.Collection.extend({
        model: movie,

    });

    return movies;
});

From here we get down to the model, movie…

define(['backbone','underscore'],function(Backbone,_){
    var movie = Backbone.Model.extend({});

    return movie;
});

So that's how to create a basic app with a router, view, collection, and model.

Build with Node or Java

One of the cool parts about Require is it’s ability to build and compress your application for you. It requires an app.build.js file, r.js(which you download with the RequireJS) jQuery app, and if you want to compile with Java, you’ll need Rhino and Clojure (Thanks to @jrburke again for this help page on r.js) or if you want to use NodeJS you’ll just need Node for your OSOC (Operating System of Choice) . The app.build.js file will typically look something like…

({
    appDir: "..",
    baseUrl: "scripts/",
    dir: "../../app-build/",
    //Comment out the optimize line if you want
    //the code minified by UglifyJS
    //optimize: "none",

    paths: {
        "jquery": "require-jquery",
		"underscore": "libs/underscore",
		"backbone": "libs/backbone";
    },

    modules: [
        //Optimize the require-jquery.js file by applying any minification
        //that is desired via the optimize: setting above.
        {
            name: "require-jquery";
        },

        //Optimize the application files. Exclude jQuery since it is
        //included already in require-jquery.js
        {
            name: "main",
            exclude: ["jquery"]
        }
    ]
})

This file is used to tell r.js how to build the application. There is help on requirejs.org/docs/optimization.html about the file. Basically r.js will look at the main module, and trace all of it’s dependencies, minify them, and combine them for you into one fun happy little minified package at your dir from the app.build.js file.

To run the optimizer in Java, go to the file above the root of app where r.js is located and use the command…

java -cp c:/path/to/rhino/js.jar;c:/path/to/compiler/compiler.jar; org.mozilla.javascript.tools.shell.Main r.js -o "c:/path/to/your/app/scripts/app.build.js"

If you are using node, then run this command…

node r.js app/scripts/app.build.js

And next thing you know, you’ll have an app-build folder with a shiny new minifed version of your app. The node optimizer is quite a bit faster than the java one, so I’d use that one.

So, that’s basically it! If you have any questions, let me know as I spent many hours figuring this thing out. The biggest help was when jQuery and UnderscoreJS both added AMD, and then once the Backbone AMD branches came out, it was much easier!

I have a simple working app called Savefavs up here at js.jcreamerlive.com and the source for it on Github. So take a look at that for a little more advanced stuff.

Tagged as: amd, backbonejs, commonjs, module, requirejs, underscorejs No Comments
17Nov/117

BackboneJS simple inheritance first run

I have been experimenting with Backbonejs recently and I am loving what it has to offer. Based on MVC, Backbonejs offers a great deal of flexibility in how to implement MVC and promotes that MVC pattern nicely.

Backbone defines MVC in this way.

  • Model: Backbone.Models, contains all of the "fat" logic for retrieving the model information from the database. Also within the M there is a concept of Backbone.Collection, which is essentially...A collection of models!
  • View: The V in Backbone is more of a hybird of real Html markup, some templating, and a bit of Backbone.View
  • Controller: Backbone.View is kind of a hybrid of a View and a Controller in the traditional MVC sense. It handles more logic than a traditional view would. Also within the controller realm, Backbone has a concept of Backbone.Router which allows you to tap into the browser hash and perform actions depending on the url. More on that later.

Below is a short sample of a few Backbone fundamentals. In the beginning you'll see an Animal declared as a base model. Then 2 more models will inherit from this basic Animal model and implement the Animal's speak method.

Then you'll see a collection of Animals defined.

Last are the 2 views I am using to render these animals. The first view attaches to a predefined table in the Html markup, while the second view uses the "tagName" property of Backbone.View to generate a new DOM element. It is convention to override Backbone.View's render method when writing views. The window.animals.bind("add", this.render, this) fires the render method on the AnimalView every time that an animal is added to the collection. The render method is then passed the newly added model. Then in the render method I create a new instance of the SingleAnimalView and pass it the newly added model. This allows me to reference this.model in the SingleAnimalView.

The templating in this example is done using the template method of UnderscoreJS which is a dependency of Backbone. UnderscoreJS is a utility library which has a ton of really cool features in it.

Any questions just let me know! I'll probably have several more posts coming after this one...

<script src="/img/spacer.gif"> 

	var Animal = Backbone.Model.extend({
		speak: function(){}
	});

	var Dog = Animal.extend({
		speak: function(){
			return this.get("name") + " says bark";
		}
	});

	var Cat = Animal.extend({
		speak: function(){
			return this.get("name") + " says meow";
		}
	});

	var AnimalCollection = Backbone.Collection.extend({
		model: Animal
	});

	window.animals = new AnimalCollection();

	var AnimalView = Backbone.View.extend({
		el: "#demo",
		initialize: function(){
			window.animals.bind("add", this.render, this);
		},
		render: function(model){
			var singleAnimalView = new SingleAnimalView({model: model});
			$(this.el).append(singleAnimalView.el);
		}
	});

	var SingleAnimalView = Backbone.View.extend({
		tagName: "tr",
		initialize: function(){
			this.template = _.template($("#animalTemplate").html());
			this.render();
		},
		render: function(){
			var model = this.model.toJSON(),
				html = this.template({
					name: model.name,
					breed: model.breed,
					speak: this.model.speak()
				});
			$(this.el).append(html);
		}
	});

	$(function(){
		window.animalView = new AnimalView();

		window.animals.add(new Dog({ name: 'fido', breed: 'terrier' }));
		window.animals.add(new Cat({ name: 'tom', breed: 'siamese' }));
	});
	<table id="demo">
		<th>Breed</th>
		<th>Message from Animal</th>

	</table><!-- End demo -->

	<script id="animalTemplate" type="text/html">
		<td><%= breed %></td>
		<td><%= speak %></td>
	</script>
documentcloud.github.com/backbone/
Tagged as: backbonejs, controllers, inheritance, javscript, models, mvc, simple, views 7 Comments
1Nov/110

String isNullOrWhiteSpace Javascript

Something that irritated me when writing JavaScript code is that checking for null, empty,etc. strings required several lines of code and there is no built in method of doing it. So, I did a bit of looking around and combined a few solutions into one of my own.

(function() {
    String.isNullOrWhiteSpace = function(str) {
        if (typeof str === "string") {
            var isNullOrWhiteSpace = false;

            // Check for null string
            if (str == null || str === "undefined") isNullOrWhiteSpace = true;

            // Check for string with whitespace
            if (str.replace( /\s/g , '').length < 1) isNullOrWhiteSpace = true;

            return isNullOrWhiteSpace;
        }

        if(typeof str === "undefined") {
            return true;
        }
    };
})();

Much better...Now you can do this...

var doSomethingWithAString = function(str){
    if(!String.isNullOrWhiteSpace(str)){
        // Do stuff with it
    }
    else {
        console.log("Why you passing me an empty string???");
    }
}
Tagged as: isnullorwhitepace, javascript No Comments
27Oct/110

Doing a distinct on a Linq Statement

Ran into a problem doing a distinct in a Linq query today. Kind of an interesting issue...

public IList<Stuff> GiveMeStuff()
{
    var listOfStuff = (from s in context.Stuff
                        select s)
                       .Distinct(new StuffEqualityComparer());
}

public class StuffEqualityComparer : IEqualityComparer<stuff>
{
    public bool Equals(stuff x, stuff y)
    {
        return x.Name == y.Name;
    }

    public int GetHashCode(stuff obj)
    {
        return x.Name.GetHashCode();
    }
}

This kept throwing LINQ to Entities does not recognize the method yata yata errors about it... Turns out, if you add an AsEnumerable() right before the Distinct() it works just fine!

This is because eveidentally since the Linq code gets converted into SQL, you can't just pass the EqualityComparer. You have to bring the entities into memory with AsEnumerable first which in effect makes it Linq to Objects, then you can do the distinct.

stackoverflow.com/questions/2296966/linq-to-entities-unions-distinct

Tagged as: asp.net, distinct, Entity framework, linq No Comments
16Aug/119

Knockoutjs and ASP.net MVC3 = PB and J

Client side scripting and ASP.net MVC3 are  a match made in heaven. But, one of the issues I commonly have with Javascript is a general lack of organization and wayyyyy to much code in one file. Even with jQuery's Ajax functions writing a user interface with can be a daunting process. Also, with modern web apps such as Gmail and Hotmail, users are getting used to not seeing the screen flash to white every time they click a button. Users are getting used to smooth rich interfaces.

Enter knockoutjs.

Knockoutjs is a shiny new client side library written by Steve Sanderson, and it is quite an incredible piece of software. It is written following the MVVM (Model-View-ViewModel). Which means:

  • Model - Typically some form of data model whether it be the actual data model or a representation of it. This would be provided by something like ASP.net MVC3, or your favorite server side language.
  • View Model - The javascript object that represents the model.
  • View - The UI experience

A hello world sort of example of knockoutjs goes like this.

<script src="/img/spacer.gif"> 

jQuery is required for knockoutjs, so include the latest jQuery and then the knockout library. The viewModel declared in the javascript is the JS object that represents either the data model or a ViewModel from your server side language you are using. This could be retrieved with an Ajax call which I'll show later. Currently on the viewModel I have one property storeName which is marked as a ko.observable(). This marks this property as one that will be tracked by knockout. Anytime you use modify the storeName in any way throughout the UI, the viewModel will update with the correct data, and update the corresponding UI elements.

The next thing you will notice is the data-bind="text: storeName" on the span. This is simply a text binding that displays the storeName, nothing too fancy here, let's continue on.

Note, you'll need &lt;script src="/img/spacer.gif">


<span data-bind="text: storeName"></span>

<ul data-bind="template: { name : 'moviesTemplate', foreach: movies }"></ul>

<script type="text/html" id="moviesTemplate">
     <li data-bind="text: name"></li>
</script>

<script>
var viewModel = {
     storeName : ko.observable("My Movie Store"),
     movies : ko.observableArray([{ name : 'The Matrix' },
          { name : 'Mission Impossible' },
          { name : 'Casino Royale' }])
}
ko.applyBindings(viewModel);
</script>

This code introduces the ko.observableArray with an array of movies being added to it. Then in the ul you'll notice the template syntax in the data-bind, with name being the name of the template to use (id of the script tag containing the template) and the foreach being the object to iterate over (the array in the viewModel). Then in the script tag you'll see the data-bind for text: name. This of course corresponds to the name of each movie.

Now how's about retrieving that list of movies via Ajax?

Here is the code you might see in MVC3...

public class Movie{
     public int Id { get; set; }
     public string Name { get; set; }
}

public class MoviesRepository{
     MoviesContext _context;

     public MoviesContext()
     {
           _context = new MoviesContext();
     }
     public IQueryable<Movies> GetAll()
     {
          return _context.Movies;
     }
}

public class MoviesController{

     public ActionResult Index()
     {
          return View()
     }

     public JsonResult GetMovies()
     {
          var movies = new MoviesRepository().GetAll();
          return Json(movies, JsonRequestBehavior.AllowGet);
     }
}

And your javascript code may now look like...


<span data-bind="text: storeName"></span>

<ul data-bind="template: { name : 'moviesTemplate', foreach: movies }"></ul>

<script type="text/html" id="moviesTemplate">
     <li data-bind="text: name"></li>
</script>

<script>
var viewModel = {
     storeName : ko.observable("My Movie Store"),
     movies : ko.observableArray([])
}

var movie = function(){
     this.Id = ko.observable();
     this.Name = ko.observable();
}

$(function(){
     $.get("/Movies/GetAll/","",function(data){
          for(var i = 0; i < data.length; i++){
               var movie = new movie();
               movie.Id = data[i].Id;
               movie.Name = data[i].Name;
               viewModel.movies.push(movie);
          }

          ko.applyBindings(viewModel);
     });
});
</script>

So that is a simple example connecting knockout to MVC, basically you'd have your Ajax call the MoviesController and it would go grab the movies out of the repository, in the GetAll method. Then you return Json(movies,JsonRequestBehavior.AllowGet). Note: that AllowGet is something to not forget as it won't allow you to do get's without it.

Coming soon I'll talk a little about knockout.mapping which eliminates the need to have a JS model for each one of your MVC models.

That's all for now!

Filed under: ASP.NET, jQuery, KnockoutJS, MVC 3 9 Comments
25Jul/111

Audit Fields Using Entity Framework Code First

One common need among database creation is auditing. Fields like DateCreated, DateLastUpdated, etc...etc... Well with EF Code First, there is one pretty easy way of getting it accomplished.

EF Code First uses a class that inherits from a DbContext to store all of the different Entities used in your application. It looks something like...

public class MyContext : DbContext
{
     public DbSet<MyEntity> MyEntities { get; set; }
}

By overriding the SaveChanges method like this...

public override int SaveChanges()
        {
            // var auditUser = HttpContext.Current.User.Identity.Name;
            DateTime auditDate = DateTime.UtcNow;

            foreach (DbEntityEntry<IAuditable> entry in ChangeTracker.Entries<IAuditable>())
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Entity.CreatedOn = auditDate;
                    entry.Entity.ModifiedOn = auditDate;
                    // entry.Entity.CreatedBy = auditUser;
                    // entry.Entity.ModifiedBy = auditUser;
                }
                else if (entry.State == EntityState.Modified)
                {
                    entry.Entity.ModifiedOn = auditDate;
                    // entry.Entity.ModifiedBy = auditUser;
                }
            }

            return base.SaveChanges();
        }

You can uncomment the two user fields and update the user with this code as well.

Tagged as: audit, audit fields, code first, datecreated, datelastupdated, ef, ef code first, Entity framework 1 Comment
3Jul/110

MvcScaffolding in ASP.net MVC3 via NuGet

CRUD is one of the most mundane tasks for a web developer to have to work his or her way through developing. It's tedious and annoying!

Enter MvcScaffolding...One of the most useful Nuget packages around.

Start off a new MVC3 project in VS2010 and Choose all of the default options, Tests, HTML5, etc...

Now go to Tools->Library Package Manager->Package Manager Console. This will show the NuGet console at the bottom of the VS2010 Window.

spacer

Typically from here you can create simple models like

public class User
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string Email { get; set; }
}

Now go down to the console and type Install-Package MvcScaffolding. This will download a few things and stick them into the Packages directory at the root of your project.

Back in the console type the following. Scaffold Controller User, and just as easy as those 3 words were to type, A controller called Users, a DbContext called UsersContext, and a set of Users views will automatically be created via T4Scaffolding.

So that's all pretty neat and easy stuff, but the other day I ran into an issue where I have classes in a seperate class library outside of my MVC3 project. And I kept getting errors that it could not find the model that I was trying to scaffold.

If you change the arguments of your Scaffold command in the console and do Scaffold Controller User -ModelType OtherProject.Models.User -DbContextType OtherProject.Models.UsersContext then it will use the models from your external class library.

Some more details on the subject can be found below:

blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/

Have fun!

Tagged as: asp.net, mvc3, MvcScaffolding, nuget No Comments
21Jun/113

Dependency Injection ASP.net MVC 3 Castle Windsor

Unit tests, Test Driven Development, Behavior Driven Development, Inversion of Control, and Dependency Injection.... Whew! Don't I sound smart!? These big dev words are concepts that many modern applications are using. TDD and BDD in particular are some great design patterns to help create "bug free code".

Dependency Injection and Inversion of Control (DI and IoC) are two terms that mean relatively the same thing, and they are very useful when doing TDD, BDD, and just regular old unit tests. One of the things that can make testing complicated is when one thing depends on another thing.

public class HomeController : Controller
    {
        //
        // GET: /Home/
        private readonly IMyRepo _repo;

        public HomeController(IMyRepo repo)
             :this(new MyRepo()){
        }

        public HomeController(IMyRepo repo)
        {
            _repo = repo;
        }

        public ActionResult Index()
        {
            var stuff = _repo.GetStuff();

            return View(stuff);
        }

    }

The above code is known as "poor man's dependency injection". The basic point there being, when the default constructor of HomeController is called it shoves in a MyRepo object. This could be problematic during testing because if you need to mock or stub that object, you'd have to mess around with some stuff.

An easier and safer way to promote separation of concerns, another big word, is to use an actual DI framework such as Castle.Windor or Ninject .

I have used both, but this post will cover some Castle.Windsor stuff.

In order for Castle.Windsor to work, you will need to create a custom controller factory in some directory under your main project like Plumbing.

public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="kernel"></param>
        public WindsorControllerFactory(IKernel kernel)
        {
            _kernel = kernel;
        }

        /// <summary>
        /// Release the controller at the end of it's life cycle
        /// </summary>
        /// <param name="controller">The Interface to an MVC controller</param>
        public override void ReleaseController(IController controller)
        {
            _kernel.ReleaseComponent(controller);
        }

        /// <summary>
        /// Resolve a controller dependency
        /// </summary>
        /// <param name="requestContext">The HTTP context</param>
        /// <param name="controllerType">Type of controller to resolve</param>
        /// <returns>IController</returns>
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.",
                    requestContext.HttpContext.Request.Path));
     


gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.