Using Google Closure Compiler with .NET

on Tuesday, January 26, 2010

Well, with C#.NET.

I maintain a service which updates the minified versions of reused Javascript libraries. It runs at a specified time each night, and will check through all javascript code within a directory for two things:

1) If a .js doesn’t have a .min.js file; then a minified version of the file is created.

2) If a .js file does have a .min.js file which is out of date; then a new minified version of the file is created.

(aka, its a nightly run service which updates all minified version of javascript librarys on a server)

This service has a couple of problems on the surface. Why doesn’t it also make a packed file version? Does the minified version always perform (without error) the same as the development version? And, what “minifier” does it use?

Here’s are some quick answers:

1) “Packed Version”:

Unfortunately, when I first created the service only minified files were being created (aka, a long time ago in a land far far away). And, I haven’t yet had time to implement “packed versions”. It should only take a night to do update the source code. But when will I have that night?

2) What language?

C#. Sorry all, but it’s the easiest for me to use.

3) Does the minified version always perform (without error) the same as the development version?

It depends on the “minifier”.

I have found that “jsmin” doesn’t really translate the code that well. YUI is pretty good; but not 100% accurate. It’s about 99% accurate.

This system does support the Microsft Implementation of javscript minifying … but I have never used it. Because …

Google’s implementation was pretty damn good. I have never had an error/problem with a file minimized through the google closure compiler (http://closure-compiler.appspot.com/home).

3) What “minifier” does it use?

Thankfully, I made the program agnositic to what minifier was used. Currently, it supports “jsmin”, “ajaxmin” (MS), “YuiCompressor”, and “Closure” (Google).

Hopefully, you can copy/paste this into your project and be able to use Google Closure-Compiler.

//    So, this is different than most of the other compilers because it uses a remote (web) service.
// the first thing is to read in the javascript file.
string fileContents;
using( var fileReader = new StreamReader( info.FullName ) )
{
fileContents = fileReader.ReadToEnd();
}

// The files contents have been read. Now they need to be formatted in a POST request with the
/// file contents URL encoded.
const string postFormat = "js_code={0}&compilation_level={1}&output_format={2}&output_info={3}";
var data = string.Format(
postFormat,
HttpUtility.UrlEncode( fileContents ),
"WHITESPACE_ONLY",
"text",
"compiled_code"
);

// finally, create the Http Request (POST request)
var request = WebRequest.Create( "http://closure-compiler.appspot.com/compile" );
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

// and, write the contents to the request.
using( var dataStream = new StreamWriter( request.GetRequestStream() ) )
{
dataStream.Write( data );
}

// the response contains the javascript
var response = request.GetResponse();
using( var responseStream = response.GetResponseStream() )
{
var streamReader = new StreamReader( responseStream );
return streamReader.ReadToEnd();
}

If you would like to see more than just the Google Code portion, or even the whole code for the service please email or comment.

Invasion of the Blog-o-Snatchers

on Monday, January 25, 2010

I am thankful for all the blog-o-sphere websites which provide servers and websites for expressing opinions online. This doesn’t just include blogger.com, wordpress.com, or livejournal.com. I also include wikipedia and all of the wikia.com websites. And any website which allows people to add their opinions to the eternal flow of electronic information.

These websites are amazing. And they allow for the 80% of the world which isn’t represented by the mainstream news networks, hollywood movies, or local papers to express their opinions and find a community with those opinions.

But, I hate when those websites undermine the opinions of the bloggers or commenters by adding advertisements to a detriment to their content. Advertisements are a necessary part of every information medium, but it doesn’t need to be in your face. Or even worse, detract from the content which the end-user actually went to the website for.

Earlier tonight, I was trying to write a snippet of code which would use the Google Closure Compiler to condense some javascript used on the UCSB websites and ran into this blog post: http://www.bloggingdeveloper.com/post/C-Wrapper-for-Google-Closure-Compiler-Compressing-Javascript-Files-on-the-fly-with-ASPNET-and-Closure-Compiler.aspx

It’s a pretty decent post, but the code wasn’t complete. At this point I assumed that their website would have a download section to get the original source code. Near the bottom of the post there is text “Download Closure.cs”, which leads to nothing.

So far this website is zero for three.  I wanted to find some code that “just worked with Closure Compiler”. And I was blown away that the top google result that I found had an image for source code (which I couldn’t copy/paste), had missing variable definitions, and I couldn’t get the source code.

The strange thing is that none of that annoyed me. The source code on the website was very similar to the source code I wrote in my early attempts; so I felt that I was doing the right thing. I had already created a string format, and I didn’t think the real implementation of “data” would solve my problem. But, the idea that I couldn’t download the source from the website bugged me. There was explicit text that said “Download Closure.cs”.

Have you ever created a website that had a link “Download PDF”, and the link didn’t work? How many people complained? Everybody that tried it would complain. Even people that would never use the PDF document would complain that the link didn’t work.

BUT … BUT … That text is not that big on the screen. There is a huge image which says “Download” right below it. That image probably appears on every page, and it probably confuses every person that sees it. The HUGE  “DOWNLOAD” link only allows users to subscribe to an RSS feed. FTW??

What the hell does RSS feeds have to do with Downloading? What RSS feed on the planet Downloads? When has the term download ever been associated with RSS?

At this point I started to look at the website layout and started to notice the big images which say SUBSCRIBE and SPONSORS. Direct advertising! I understand that everybody needs to make money to survive. But, is it neccessary?

What is the business model of blogger, wordpress, and livejournal? How do they make money without pissing off their users?

Any why is anyone using a blogging website that would add content to your posts which you never asked for?

Creating your own javascript namespaces with jQuery

This isn’t cutting edge by a long shot, but if I had found a post on this a couple months ago it would have kept me from refactoring my code two or three times. One of the amazing things about working with jQuery is the programmers have dealt with every impossible situation you could imagine. And, when you look through their code you are given an insight into javascript best practices.

(function ($) {

if (!window.baseNamespace) { window.baseNamespace = {}; }
if (!baseNamespace.subNamespace) { baseNamespace.subNamespace = {}; }

var pseudoGlobal = 10;

$.extend(baseNamespace.subNamespace, {
someVariable: 10,

someFunction: function () {
alert(pseudoGlobal);
}
});

})(jQuery);

Unfortunately, this description doesn’t follow the exact same best practices that jQuery does. But, it works well when defining your own namespaces.

The outer function ensures the inner statements will be executed with jQuery as the definition of $. This will help out if you ever need to reuse your code in “no conflict” mode (http://api.jquery.com/jQuery.noConflict/).

Then, inside of the function, first check that the root namespace is defined under “window”, the global namespace. It took me longer than I would have liked to understand that “window” was the global namespace; I was under the sad impression that “document” was the global namespace.

Once the namespace you are looking to work with is created, then the $.extend() function gives the means to create the functionality you want.

You can then interact with your namespace the same way google of yahoo call their namespaced code:

alert(baseNamespace.subNamespace.someVariable); // 10
baseNamespace.subNamespace.someFunction(); // Also, 10

I hope this saves you a little bit of time when developing reusable javascript.

Wizmo: Have Windows go to sleep on commad

on Thursday, December 24, 2009

I can’t find the original blog post which pointed out Wizmo. But, it’s a command line utility which handles a lot of the shutdown/restart/sleep mode capabilities of windows. I needed it to turn my monitors off when I leave home.

When I go out I like to turn off my monitors. It would be nice to think I was saving electricity, but really I just want to save the monitors. Unfortunately, when I turn off the monitors all of my open windows rearrange themselves onto a single screen. My setup isn’t normal, so I wouldn’t expect for any software or hardware vendor to accommodate it.

However, Wizmo is able to handle the problem. By creating a simple desktop shortcut, I can turn off all the screens without any of the problems which DisplayPort creates.

The command line shortcut:

"C:\Program Files (x86)\Wizmo\wizmo.exe" monoff


jBreadCrumb: 0.3.0

http://code.google.com/p/jbreadcrumb/

jBreadCrumb gains the ability to start working in a Web 2.0 world. The addition of methods for ‘add’, ‘remove’, and ‘clear’ allows for a webpage which dynamically loads content into a sub-div or iframe to also update the breadcrumb trail. It’s definitely not perfect, but allows for breadcrumbs to start becoming a dynamic part of the webpage design.

The new methods can be used by:

(*note: #addBreadCrumb, #removeBreadCrumb, and #clearBreadCrumb are input buttons on the page. #breadCrumbAdd is the breadcrumb list element to update.)

Add:

The options are:

  • text: (required) the text to display on screen.
  • url: (optional, default: ‘#’) the url to apply to the hyperlink
  • index: (optional, default: add the breadcrumb to the end of the list) the position to place to breadcrumb (1 based index)
$('#addBreadCrumb').click(function(e) {
var options = {
text: $('#addDisplayValue').val(),
url: $('#addUrl').val(),
index: $('#addIndex').val()
};

$('#breadCrumbAdd').jBreadCrumb('add',options);

e.preventDefault();
});

Remove:

The options are:

  • index: (optional, default: the last breadcrumb) the position to remove (1 based index)

$('#removeBreadCrumb').click(function(e) {
var options = {
index: $('#removeIndex').val()
};
$('#breadCrumbAdd').jBreadCrumb('remove',options);
e.preventDefault();
});

Clear:

$('#clearBreadCrumb').click(function(e) {
$('#breadCrumbAdd').jBreadCrumb('clear');
e.preventDefault();
});

These functions are useful for my usages. But, do they do what you need?

Using JSONP with ASP.NET MVC

on Thursday, December 17, 2009

(I am using the Beta 2 of ASP.NET MVC. It isn’t supposed to be ready for production; but it seems pretty stable.)

Earlier today I needed create some Cross Domain javascript requests. At first I tried to use the ASP.NET MVC JsonResult to provide data for these requests, but the serialized objects that were returned were unable to be used through JSONP (the cross domain javascript).

After a little research on StackOverflow (what a great site), I was able to find some JSONP code to use. This was a real timesaver, and it was documented to boot.

The creators of this code posted their code at:

http://stackoverflow.com/questions/758879/asp-net-mvc-returning-jsonp

http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx

I’ve added a small update. Just enough to make the Controller handle the new ASP.NET MVC 2 JsonRequestBehavior. I hope someone will improve on this code and add an “extensions” library to allow for Jsonp to be available in all controllers without using the JsonpController or JsonpFilterAttribute.

JsonpResult.cs:

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Ucsb.Sa.Enterprise.Utility.Web.Mvc
{
/// <summary>
/// A Jsonp wrapper for the JsonResult.
///
/// Created by:
/// stimms (http://stackoverflow.com/questions/758879/asp-net-mvc-returning-jsonp)
/// Ranju V (http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx)
/// </summary>
public class JsonpResult : JsonResult
{

#region constructor

/// <summary>
/// Initializes a new instance of <see cref="JsonpResult" />.
/// </summary>
public JsonpResult()
{
// http://compactprivacypolicy.org/compact_token_reference.htm
CompactPolicy = "NON DSP COR STP COM";
}

#endregion

#region properties

/// <summary>
/// Gets or sets the javascript callback function that is
/// to be invoked in the resulting script output.
/// </summary>
/// <value>The callback function name.</value>
public string Callback { get; set; }

/// <summary>
/// Gets or sets the compact policy values. By default the compact policy
/// says "We provide noinformation to 3rd party sources".
/// </summary>
public string CompactPolicy { get; set; }

#endregion

#region methods

/// <summary>
/// Enables processing of the result of an action method by a
/// custom type that inherits from <see cref="T:System.Web.Mvc.ActionResult"/>.
/// </summary>
/// <param name="context">The context within which the
/// result is executed.</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}

if ( string.IsNullOrEmpty( Callback ) )
{
Callback = context.HttpContext.Request.QueryString["callback"];

if ( string.IsNullOrEmpty( Callback ) )
{
Callback = context.HttpContext.Request.QueryString["jsoncallback"];
}
}

if( string.IsNullOrEmpty( CompactPolicy ) == false )
{
// TODO: uncomment when we get an IIS 7 server
//response.Headers.Add( "compact-policy", CompactPolicy );
}

if (Data != null)
{
// The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1
#pragma warning disable 0618
var serializer = new JavaScriptSerializer();
var ser = serializer.Serialize(Data);
response.Write(Callback + "(" + ser + ")");
#pragma warning restore 0618
}
}

#endregion

}

}


JsonFilterAttribute.cs:



using System;
using System.Web.Mvc;

namespace Ucsb.Sa.Enterprise.Utility.Web.Mvc
{
/// <summary>
/// A Jsonp attribute to override older JsonResult objects.
///
/// Created by:
/// stimms (http://stackoverflow.com/questions/758879/asp-net-mvc-returning-jsonp)
/// Ranju V (http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx)
/// </summary>
public class JsonpFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if(filterContext == null)
throw new ArgumentNullException("filterContext");

//
// see if this request included a "callback" querystring parameter
//
string callback = filterContext.HttpContext.Request.QueryString["callback"];
if (callback != null && callback.Length > 0)
{
//
// ensure that the result is a "JsonResult"
//
JsonResult result = filterContext.Result as JsonResult;
if (result == null)
{
throw new InvalidOperationException("JsonpFilterAttribute must be applied only " +
"on controllers and actions that return a JsonResult object.");
}

filterContext.Result = new JsonpResult
{
ContentEncoding = result.ContentEncoding,
ContentType = result.ContentType,
Data = result.Data,
Callback = callback
};
}
}
}
}


JsonController.cs:



using System.Text;
using System.Web.Mvc;

namespace Ucsb.Sa.Enterprise.Utility.Web.Mvc
{
/// <summary>
/// Controller which adds Jsonp ActionResults to the base Controller.
///
/// Created by:
/// stimms (http://stackoverflow.com/questions/758879/asp-net-mvc-returning-jsonp)
/// Ranju V (http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx)
/// </summary>
public abstract class JsonpController : Controller
{

/// <summary>
/// Creates and returns a Jsonp result.
/// </summary>
/// <param name="data">The data/object to serialize.</param>
/// <returns>A Jsonp ActionResult.</returns>
protected internal JsonpResult Jsonp(object data)
{
return Jsonp(data, null /* contentType */);
}

/// <summary>
/// Creates and returns a Jsonp result.
/// </summary>
/// <param name="data">The data/object to serialize.</param>
/// <param name="behavior">Allow Get requests.</param>
/// <returns>A Jsonp ActionResult.</returns>
protected internal JsonpResult Jsonp(object data, JsonRequestBehavior behavior )
{
return Jsonp(data, null /* contentType */, behavior );
}

/// <summary>
/// Creates and returns a Jsonp result.
/// </summary>
/// <param name="data">The data/object to serialize.</param>
/// <param name="contentType">The contentType to return.</param>
/// <returns>A Jsonp ActionResult.</returns>
protected internal JsonpResult Jsonp(object data, string contentType)
{
return Jsonp(data, contentType, null);
}

/// <summary>
/// Creates and returns a Jsonp result.
/// </summary>
/// <param name="data">The data/object to serialize.</param>
/// <param name="contentType">The contentType to return.</param>
/// <param name="behavior">Allow Get requests.</param>
/// <returns>A Jsonp ActionResult.</returns>
protected internal JsonpResult Jsonp(object data, string contentType, JsonRequestBehavior behavior)
{
return Jsonp(data, contentType, null, behavior);
}

/// <summary>
/// Creates and returns a Jsonp result.
/// </summary>
/// <param name="data">The data/object to serialize.</param>
/// <param name="contentType">The contentType to return.</param>
/// <param name="contentEncoding">The contentEncoding type.</param>
/// <returns>A Jsonp ActionResult.</returns>
protected internal virtual JsonpResult Jsonp(object data, string contentType, Encoding contentEncoding)
{
return Jsonp( data, contentType, contentEncoding, JsonRequestBehavior.DenyGet );
}

/// <summary>
/// Creates and returns a Jsonp result.
/// </summary>
/// <param name="data">The data/object to serialize.</param>
/// <param name="contentType">The contentType to return.</param>
/// <param name="contentEncoding">The contentEncoding type.</param>
/// <param name="behavior">Allow Get requests.</param>
/// <returns>A Jsonp ActionResult.</returns>
protected internal virtual JsonpResult Jsonp(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonpResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}

}
}


I hope this helps others get around the JSONP problem until ASP.NET MVC implements a standard method for this.

From Ubuntu to Windows 7

A couple years ago I swore that I would never pay for an Operating System again. It just seemed pointless. No matter what Operating System you choose (Windows, Mac, Linux) you would always have problems. And I hated the idea that I was paying for those problems. So, I made a deal with my workplace (which is a Microsoft shop); if they provided me with an operating system for home then I would remote in when needed. This was just a polite gesture on both of our parts. I was going to remote in anyways and they knew I was going to remote in. So, they were kind enough to provide me with a Windows XP Home copy to use for remote desktoping.

However, at the time, I had already switched to Ubuntu as my home environment. So, Windows XP was loaded up in a VMWare virtual machine (I have used the free version of VMWare for over 6 years and am a big supporter of their virtual software … it’s easy to use and easy to install).

But, after 7+ years of using Linux/Ubuntu as my home Operating System I have switched back to Windows 7. It wasn’t an easy transition because there are a lot of command line features that I loved in Ubuntu which aren’t replicated in Windows. PowerShell (for Windows) really helps bridge the gap, but it’s not the same. The best analogy I can come up with is …

* using the Linux command line is like talking to a college valedictorian. They get it right away.

* using Window’s Poweshell is like talking to a high school valedictorian. They know what your talking about, but you have to be verbose.

* using Window’s normal command line is like talking to a retarded (“mentally-disabled”) high schooler. It doesn’t matter how many times you try to explain it, they still won’t get it.

The switch over was pretty painless. I was able to copy almost all the files I wanted to keep onto a thumb drive, because most of my work was replicated online (For the less Linux established this is a slight at Windows … Linus Torvalds, “Only wimps use tape backup: _real_ men just upload their important stuff on ftp, and let the rest of the world mirror it”).

I was able to get up and running on Windows 7 within less than an hour. So, good on ya’ Windows. The only thing that I had a problem with was rebooting the system. Apparently the Windows copy I bought did something really spectacular!!

Buying a real version of Windows still seems, to me, like paying for an Operating System with problems. So, I choose the cheapest option I could find for my purposes. I wanted to remote desktop into work, and I wanted to make that remote desktop experience the best possible. Only Windows 7 Ultimate had the feature to remote desktop with multiple displays, so I bought Ultimate (a waste of money for 99% of users). But, I didn’t want to pay full price; so I bought a “System Builders” version. The system builder version comes with a couple of ridiculous stipulations which all boil down to one point: You will NOT get support from Microsoft if something goes wrong. It is about $100 cheaper to buy this version, but if something doesn’t work then you need to be really good with Google.

Of course, I had a problem right off the bat. The System Builders version doesn’t overwrite the MBR. Which means, if you restart the system, it will use your old MBR and hang if that MBR doesn’t point to anything usable. Since I had Ubuntu installed before, the MBR was a GRUB loader and pointed to a non-existent partition (since I erased/overwrote all the partitions with the Windows install).

If you have Linux installed on the system, your normal boot sector won’t be overwritten. That makes the “System Builders” version of Windows the perfect installer for dual-boot users. Unfortunately, I wasn’t trying to be a dual-boot user. So, after some searching on the Microsoft website I was able to find a MBR installer. The searching only took about 20 minutes (about 1/10th the amount of time it takes to solve a linux problem), so I was pretty happy with the easy install and quick fixes.


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.