Archive for Software Dev & Productivity

24 Jan 2012

The Return of Javascript

No Comments Software Dev & Productivity

A few years ago, I remember complaining that Javascript is a lost art.  I was working with a .Net offshore team who claimed not to know HTML or Javascript—they only knew Asp.Net.  When we were trying to come up with solutions to a particular web problem, I recommended we use Ajax.  They didn’t know any ajax outside of the Microsoft Ajax extensions.

I did a lot of Javascript back in the day.  I can remember sitting down on a Saturday night in 1999 reading through a giant copy of the “Javascript Bible”.  Before ajax was mainstream, you used to have to know how to store data islands in your source and store all kinds of arrays locally.  The sites I did work on where Javascript was heavily used were cumbersome and difficult to maintain.  They usually supported only IE.

Anyone who has ever worked with me knows how much I hate Asp.net web forms.  I prefer classic ASP to webforms.  I admire PHP developers who had full control over their html and javascript.

But now . . . Javascript is back.

When Silverlight was dropped in favour of HTML5, I moaned. I remember the bad old days of trying to write to the lowest common denominator in browsers.  I don’t want to go back to that.  I’m happy to stay in the Silverlight haven.  They supported Macs at least, but not Lynux or tablets.

But in the past few months, I’ve been able to use Javascript to write games (Impact JS), phone apps (jQuery Mobile and Phone Gap(, and server applications (node.js). 

Javascript is better than I ever remember it being.  It seems to be experiencing a renaissance.  While all the coders of other languages are having pointless arguments about which one is better, Javascript is proving the be the uniter.  Learn JS, and you can do anything.

These are exciting times.  Right now, everyone seems to have a Javascript framework.  There are so many to choose from. 

Javascript is beautiful.  And no one is trying to control it.

I’m really looking forward to the next year.  I’m sold.  HTML5 is the way of the future.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

02 Jan 2012

Running ImpactJs in Visual Studio 2010 with a Project Template

1 Comment HTML5, Software Dev & Productivity

I took December off to spend time with family and invest in some professional My Gamedevelopment.  I worked mostly with HTML5 and javascript, but I did do some Drupal work too.

For HTML5, I played with local storage, the new tags, backwards compatibility, PhoneGap, and finally the canvas tag.  One thing I wanted to do was learn how to build games in HTML5.  There are some great tutorials on starting a project from scratch—I’ll post more on them later, but there’s also a very good javascript game engine called ImpactJS.

ImpactJS is written almost entirely in javascript, but it does us a few php files (and a server) to allow it to do things like read from and write to files.  According to the instructions, you need to set up in Apache (but an IIS port is available). 

But I spend most of my life in Visual Studio 2010 (and occasionally Eclipse).  I work faster in that IDE and all the keyboard shortcuts come second nature. After purchasing Impact and creating a few games, I found it tedious assigning a new port in the Apache conf on my local machine for every game.  Also, the Komodo IDE is very good, but I prefer my boring ol’ Visual Studio.

So, I looked at the php files and created my own Visual Studio template.  This may sound a little heavy using this big IDE only for javascript and html, but I find it very helpful that it will create a new server port each time I create a new web project.

I created a project template was going to post it online, but it includes all the ImpactJS source (which costs $99—but I got for $49 on a Christmas sale), so that probably wouldn’t be doing the developer any favours if I put it on all online.  So, here are my contributions and the instructions for anyone else who has purchased ImpactJS and wants to use it in Visual Studio 2010.

Step 1:  Create a New Project.

Create an empty ASP.Net Web project.  Make sure to choose an empty project—otherwise you have to delete all the plumbing they give you.  All you want is the web.config (and you can get rid of that if you don’t need it).

Step 2:  Add ImpactJS framework

Drag all your ImpactJS source into the new project from Windows Explorer.  This should include all the folders.  The two root documents should be index.html and weltmeister.html.

image

At this point, you can right-click on index.html and choose “View In Browser”.  It will give you the “It Works!” text on the canvas (but it will create a server instance like localhost:12345).  This is unimpressive.  The game itself does not use the server—the Weltmeister tool does.

Step 3: Add the Generic Handlers.

You can right-click and view the Weltmeister tool in the browser now, but it will not work the way it should.  The Weltmeister level editor uses 4 php files:

  • /lib/weltmeister/api/browse.php (browses for files in the filesystem)
  • /lib/weltmeister/api/config.php (provides the $fileRoot variable and a few methods).
  • /lib/weltmeister/api/glob.php (gets files matching a certain pattern in the directories)
  • /lib/weltmeister/api/save.php (saves files edited in Weltmeister to the directory)

The contents of these four files are pretty straight forward and easy to convert to C#.  I initially created a aspx pages to replace them, but then found Generic Handlers to be more effective since I didn’t need a front end webform.

So, we will create four files to replace these four (they can sit side by side—the php files won’t get in our way). 

First add a Web.config file to the api folder (it will limit the scope to this folder only).  In this file add the fileRoot variable:

<?xml version="1.0"?>
<configuration>   <appSettings>     <add key="fileRoot" value="../../.."/>   </appSettings>
</configuration>

Now, add three more files of type “Generic Hander” to the api folder.

 image

Give these files the same names as their PHP counterparts:

  • browse.ashx
  • glob.ashx
  • save.ashx

Here is the code for each file:

browse.ashx:

using System.IO;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace SpaceShooter.lib.weltmeister.api
{
    /// <summary>
    /// Summary description for browse
    /// </summary>
    public class browse : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var fileRoot = context.Request.MapPath(System.Configuration.ConfigurationManager.AppSettings["fileRoot"].ToString());
            if (!fileRoot.EndsWith("/"))
                fileRoot += "/";

            var dir = fileRoot + context.Request.QueryString["dir"].ToString();
            if (!dir.EndsWith("/"))
                dir += "/";

            var find = "*.*";
            switch (context.Request.QueryString["type"].ToString())
            {
                case "images":
                    find = "*.{png,gif,jpg,jpeg}";
                    break;
                case "scripts":
                    find = "*.js";
                    break;
            }

            var dirs = Directory.GetDirectories(dir, "*", SearchOption.AllDirectories);
            var files = Directory.GetFiles(dir, find, SearchOption.AllDirectories);

            var fileRootLength = fileRoot.Length;
            for (var i = 0; i < files.Length; i++)
            {
                files[i] = files[i].Replace(fileRoot, "");
            }
            for (var i = 0; i < dirs.Length; i++)
            {
                dirs[i] = dirs[i].Replace(fileRoot, "");
            }

            var parent = dir.Substring(0, dir.ToString().IndexOf("/"));

            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            var jserializer = new JavaScriptSerializer();
            context.Response.Write(jserializer.Serialize(new Response()
            {
                parent = parent,
                dirs = dirs,
                files = files
            }));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public class Response
        {
            public string parent { get; set; }

            public string[] dirs { get; set; }

            public string[] files { get; set; }
        }
    }
}

glob.ashx:

using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace SpaceShooter.lib.weltmeister.api
{
    /// <summary>
    /// Summary description for glob
    /// </summary>
    public class glob : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var fileRoot = context.Request.MapPath(System.Configuration.ConfigurationManager.AppSettings["fileRoot"].ToString());
            if (!fileRoot.EndsWith("/"))
                fileRoot += "/";

            var globs = context.Request.QueryString["glob[]"].ToString();
            List<string> files = new List<string>();
            //get the files
            foreach (var glob in globs.Split(','))
            {
                var pattern = glob.Replace("..", "").Replace("/","\\");
                files.AddRange(Directory.GetFiles(fileRoot, pattern));
            }

            //remove the fileRoot and reverse slashes
            for (var i = 0; i < files.Count;i++ )
            {
                files[i] = files[i].Replace(fileRoot, "");
                files[i] = files[i].Replace(@"\","/");
            }
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            var jserializer = new JavaScriptSerializer();
            context.Response.Write(jserializer.Serialize(files));

            //   return "";
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

save.ashx:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace SpaceShooter.lib.weltmeister.api
{
    /// <summary>
    /// Summary description for save
    /// </summary>
    public class save : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var fileRoot = context.Request.MapPath(System.Configuration.ConfigurationManager.AppSettings["fileRoot"].ToString());
            if (!fileRoot.EndsWith("/"))
                fileRoot += "/";
            var path = context.Request.Form["path"].ToString();
            var data = context.Request.Form["data"].ToString();

            var result = new Result();

            if (!string.IsNullOrEmpty(path) &&
                !string.IsNullOrEmpty(path))
            {
                path = fileRoot + path.ToString().Replace("..", "");

                if (path.EndsWith(".js"))
                {
                    try
                    {
                        //if the file already exists, delete it
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        var streamWriter = File.CreateText(path);
                        streamWriter.Write(data);
                    }
                    catch (Exception ex)
                    {
                        result.error = "2";
                        result.msg = string.Format("Couldn't write to file: {0}", path);
                    }
                }
                else
                {
                    result.error = "3";
                    result.msg = "File must have a .js suffix";
                }

            }
            else
            {
                result.error = "1";
                result.msg = "No Data or Path specified";
            }
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            var jserializer = new JavaScriptSerializer();
            context.Response.Write(jserializer.Serialize(result));

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public class Result
        {
            public string error { get; set; }
            public string msg { get; set; }
        }
    }
}

Your final api folder should look like this:

image

You can get rid of the php files if you wish, but they should not be interfering with anything.

Step 4:  Amend config.js

Finally, you need to tell the javascript classes to run these ashx files instead of the php files, this is can in the file /lib/welbmeister/config.js under the api property.  Simply change the php extension to ashx:

'api': {
		'save': 'lib/weltmeister/api/save.ashx',
		'browse': 'lib/weltmeister/api/browse.ashx',
		'glob': 'lib/weltmeister/api/glob.ashx'
	}

Step 5: Save the project as a template

Now, you don’t want to have to do this for every new game project, so you need to turn this into a template (but you might want to test out the Weltmeister tool first and make sure everything is running as it should).

To create a new template, simply go to the file menu of Visual Studio and choose “Export Template”.  Then you can go through the wizard to create a new template on your pc to quickly create new ImpactJS game projects.

You may also want to create an “entity” template to speed things up when you create new entities for your game using the same menu (but choose Item Template instead of Project Template).

What about Baking?

Okay, there are two other php files in the framework that could be converted.  When you finish your ImpactJS game, you can use a command line tool to “bake” the game and get it ready for deployment.  This basically consolidates all the javascript files into one file and minifies it.  This is done in the tools folder using a file called bake.php. 

I have not converted the bake file to c# yet.  I don’t deploy too often. However, I may convert it in the future.  I would use the aspx port of jsmin written by Laurent Bugnion and convert bake.php to an aspx or ashx file.  The ImpactJS developer has put very little reliance on php, so conversion should not be difficult.

Let me know how it goes

That’s it.  I hope, if you found this post, this gets you building games in Visual Studio (with your familiar shortcuts, plug ins, and code-completion).  If you found it useful, please add a comment below.  And if you convert the baking file, please let me know too.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

15 Dec 2011

Warming up to HTML5

No Comments Software Dev & Productivity

Last week, I finally got around to reading the Microsoft announcements from September about Windows 8 and WinRT.  Like a lot of people, I was surprised by the dropping of Silverlight for the Metro UI.  HTML5 (along with XAML) would be used prominently.

HTML5 again.

I’m old school and I can’t get rid of the memories of coding conditional blocks of code for different browsers.  A lot of web apps would only adhere to one browser because of the different capabilities.  In corporate environments, this was mostly IE.  The difference capabilities still exists, so I was not pleased about using conditional coding again.  Silverlight was a nice hiding place—write once run anywhere (except Linux, and tablets, and phones—okay just Windows and Macs!).

But, things are much better than they were before.  Now, we have Modernizr and jQuery.  Now we have devices which, for the most part, adhere to one browser only (If I write for IOS, I only have to worry about Safari). 

I’m at the point now where I’m excited about HTML5.  I’ve taken December off from my current contract to really have a good play with it.  I’m very impressed with localStorage and GeoLocation.  Canvas is what I’m playing with next.

And, after months of learning Android, I discovered PhoneGap.  PhoneGap allows you to host html5 in a compiled application  (IOS, Android, Windows Phone) and release it in an app store.  It also provides a javascript library to interface with device libraries like GPS, camera, and the accelerometer.  I’m struggling with the intricacies of Java (C# keeps getting in the way), but I can do just as much in javascript.

HTML5 allows for mobile apps (web and compiled) and MetroUI.

Once again, the future is bright.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

08 Dec 2011

I love coding for WP7

No Comments C# Coding

So, I’ve spent ages trying to learn to code on an Android.  I’ve read a few books.  I’ve got my dev environment all set up.  I’ve coded a few test apps and put them on my phone.  But the going is slow.  If I were a Java developer, I’d probably be all over it.

A friend asked me to do a quick Windows Phone 7 app and I could not believe how easy it was.  Since I’ve been working heavily with Silverlight for the past few years, I know most of the code already.  I had to do minimal reading to get a full app up and running.  It was was nice to work in Visual Studio again.  Using Resharper, I was flying through the code.

I only wish more people had Windows Phone 7. 

I would get a phone myself, but 3 things are holding me back currently:

  1. I don’t want to be one of 5 people in the UK with a Windows Phone 7.
  2. It’s not open, like Android is.  I would be at the mercy of the phone manufacturers for upgrades (like with an iPhone).
  3. It doesn’t have expandable memory (to my knowledge).
  4. My current contract isn’t up until April.

But it’s nice to be able to write apps so quickly (since I spent so much time learning the trivial details of Silverlight).  Maybe.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

18 Oct 2011

The “View Source” belongs to me too.

No Comments ASP.Net, C# Coding

For me, the sign of a good web developer (or web application developer) is someone who can right-click a web page to view the source and tell you why he did things the way he did.  “I used this div to position this element over here, and used the unordered list for a sub-menu, . . . “

A bad web developer is someone who says “It looks fine in my browser” and “Well, I’m not a designer . . . “

One of the biggest crimes of ASP.net Web Forms was to strip HTML skills from new web developers.  They view the source of their code (in the browser—not Visual Studio) as gobbledy-gook.  And ASP.net ensures that it is.  It’s full of ViewState and control names like ctl_100_className_ctrlName which the developer didn’t put there.  It tried to remove the whole stateless-http challenges and make web development accessible to desktop developers.

I’m so very pleased every time I see a new site created with the Microsoft MVC Framework.  MVC is making up for the ASP.Net webform crimes.  Just like Ruby  on Rails or PHP (or classic ASP), it allows the developer to think about what gets sent from the web server to the browser.  When I do a site in MVC framework, I can view the source and recognize my own handy-work.  I can make full use of CSS3 and jQuery.  I know that everything in my user’s browser is something I put there intentionally.

CSS, Javascript, and HTML (along with images, flash movies, Silverlight, or other plugins) are the ingredients of any web application.  Server languages like ASP, PHP, and Ruby are only tools to deliver these ingredients to the browser in unique and creative ways.  A good web application developer (like a good chef) can look at his source and tell you exactly what everything does.  ASP.Net webforms are like ready-meals.  Everything is done for you, but you don’t really know everything that’s in it.

Now, don’t get me wrong, I’ve known some fantastic ASP.Net devs who build apps free of ViewState and server controls.  But I’ve worked with too many who could drag a control onto a web canvas, set a few properties, and call themselves web developers.

I recently worked on a DotNetNuke project where we customised a third-party component.  The page was not rendering as it should.  ViewSource gave me a bunch of ViewState and nested tables.   I knew of a 100 ways to get css to make the site look the way I wanted, but this wasn’t my source.  It wasn’t even the developer’s source—it was the clientIds of the server control.  Since I was struggling, a web guy (proper Mac-using, firebug-toting, standards-compliant, web guy) asked to see the source so he could suggest something.  When he saw the source, he was mortified.  I was embarrassed –“It’s not mine!  I didn’t write it.”  In the end, I hacked it with jQuery.  I didn’t have the sourcecode to modify it properly. 

The legacy of Web Forms lives on.  Sharepoint 2010 is full of it.  Young Microsoft developers (in the last 5 years or so) know nothing but how to use WebForms.  (An ASP.net dev told me a few years ago “But I don’t know html.”).  But, hopefully, one day we will get around this idea of creating tools that “do everything for you” for developers who should know to do it themselves.  Just like I wouldn’t create ready meals for people who call themselves chefs.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

04 Aug 2011

DNN, Orchard, and Joomla–some thoughts

1 Comment C# Coding, Software Dev & Productivity

I’ve been looking at CMS systems a lot recently.  Here are some of my thoughts:

DotNetNuke

I’m using DotNetNuke for a contract right now.  Although it’s written in Asp.Net and I can code in that easily, it’s a pig to run.  Even version 6, which was released last week, seems sluggish when run in the browser (even on my local machine with 8gb ram). 

DNN is advanced—don’t get me wrong.  There is no lazy-ness there.  In fact, there is so much available in DNN, that it pains me that it runs so slowly.

It’s an okay platform.  But compared to MVC or PHP counterparts, the ASP.Net webforms are still far too slow and lack elegance.  DNN will always have that Asp.Net webform dependency hanging around its neck.

Orchard

Orchard is a new CMS which was started by Microsoft.  I fell in love with it last month.  It’s based on MVC3 with the razor engine.  It supports multiple sites, just like DNN.  There aren’t many extensions or themes, but it’s written in C# so I can easily create what I need.

But, then . . .

But then I looked at the page source after it has been rendered in the browser.  Although it doesn’t have a lot of ugly ViewState like DNN (and all other webform pages have), it does include a lot of stuff that I didn’t put there.  There is huge amount of javascript added which would at least triple the size of my source.  The beauty of MVC is that I have more control of the html—but Orchard adds a stunning amount of code.  Most of it is serialised model information—but I’m not sure why it is on the client.

This really bothers me because I spent a lot of time working with Orchard.  It is not easy to use as an Admin.  While DNN is simple and I could give it to any client to customise, you have to really study Orchard just to add a few things onto a page.  You can’t just add something to a sidebar, for example, you have to create a layer and add a shape, and add some code so it only shows when a page uses that layer or shape.  Really, it was ridiculously difficult.

So, Orchard adds too much to the source and is too difficult to use.  But, in terms of speed, it is very fast.

Joomla

Okay, Joomla is PHP.  I’ve done PHP projects for clients before, so I’m fine with that—but I prefer C#.  I looked at Joomla and Drupal just to see how they compare.

Joomla puts the .net CMS alternatives to shame.  It is easy to set up, the code is very current, and it delivers pages super-fast.  The admin interface is not as easy to use as DNN (in my opinion), but much easier than Orchard.  There are loads of themes and extensions available.  When I did a viewSource, all the html was what I expected it to be.

Why can’t the .net projects be this good?

 

One thing I hear a lot in my contracts are developers comparing .Net, PHP, and Java (and sometimes Rails).  DotNet developers always say .Net is better.  PHP and Java developers talk about how sluggish .Net is and how it is inferior because it requires being hosted on Windows (except for Mono—but who really uses that?).  The truth is, all these languages pretty much do the same thing—they deliver HTML to the browser.  You can write a site in any language and it wouldn’t matter.  I’ve seen .Net sites outperform PHP sites (but unfortunately, it is the other way around). 

I’ve looked at other .net CMS systems lately too (Umbraco, Sitefinity, etc) and didn’t like the look of those enough to even install.

I might start using Joomla.  Page speed is far more important than how easy it is to code.  Hopefully, someone will write a decent .Net CMS system one of these days.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon