Realtime connections between web servers and web browsers

In the early days of the web, web pages were very static in content, once the page was loaded nothing on the page would change until you reloaded it. Then came Ajax and allowed us to do partial reloads of the page. During the last few years the web has evolved even more. Today you see a lot of web applications, such as Facebook and Google+, where content is updated as you are watching the page. This has been made possible by using different techniques to keep a connection to the web server open and be able to push content from the web server to the connected clients. The main technique to allow this in web browsers today is what is called Comet.

Comet – using browser connections

Comet is a web application model in which a long-held HTTP request allows a web server to push data to client browsers, without the browser explicitly requesting it. It works the way that the web browser requests an url from the server, and the server deliberately keeps it open, allowing it to work as a stream of data between the server and the client web browser. In this stream the web server can push content to the client. Read more Realtime connections between web servers and web browsers

Javascript on the server side

For the last decade javascript has been a language that has almost exclusively been run on the client side, in the web browser. But during the past year it seems like Javascript has found its way to the server side as well, to the joy of some developers while others wrinkle their nose and wonders why you would ever use Javascript for something more advanced than client side processing.

The fact is that Javascript is a very powerful language, unfortunately it has had a bad reputation for many years. I admit, for a long time I also looked at JavaScript as a second-class citizen in the programming world. A programming language used only to glue together HTML pages, while the heavy lifting was done on the server side in C#, Java, Ruby or in any other “real” language. However, my view of Javascript has drastically changed during the last few years. The language have “grown up”, and by that I don’t really mean the language itself, instead I am thinking about the libraries and tools available for Javascript, such as jQuery, JSON, Node.js, and HTML5. jQuery was a major game changer on the client side and now we have Node on the server side.

Node is a low level framework for building high performance web applications. It contains of an interpreter based on Google’s V8 and a framework library. HTTP is a first class protocol in Node and it is very easy to get a web server up running. Read more Javascript on the server side

Reference types are always passed by value in C#

Last week i had a discussion with a friend about C# and passing parameters to methods. My friend asked why it is possible to use the ‘ref’ keyword for a reference type in C# when passing it to a method, he was under the impression that reference types are passed by reference to methods. This seems to be a quite common misunderstanding about C#, to make it clear:

Reference types are always passed to methods by value (unless you use the ‘ref’ keyword)

Read more Reference types are always passed by value in C#

A simple image sprite generator in C#

Last week I posted the source code to a small program I wrote in Java to merge images into a sprite. This week I present the same application but in C#, pretty much translated line by line 🙂

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace NSpriteGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: NSpriteGenerator {path to images} {output file}");
                return;
            }

            var imagePath = args[0];
            var outputFile = args[1];
            
            var imageFolder = new DirectoryInfo(imagePath);
            

            // Read images
            var imageList = imageFolder.GetFiles("*.png")
                    .Select(file => Image.FromFile(file.FullName));


            // Find max width and total height
            var maxWidth = 0;
            var totalHeight = 0;

            foreach(var image in imageList)
            {
                totalHeight += image.Height;

                if (image.Width > maxWidth)
                    maxWidth = image.Width;
            }

            Console.WriteLine(string.Format("Number of images: {0}, total height: {1}px, width: {2}", imageList.Count(), totalHeight, maxWidth));


            // Create the actual sprite
            var currentY = 0;

            using (var bitmap = new Bitmap(maxWidth, totalHeight))
            {
                using (var canvas = Graphics.FromImage(bitmap))
                {
                    foreach (var image in imageList)
                    {
                        canvas.DrawImage(image, 0, currentY);
                        currentY += image.Height;
                    }
                    canvas.Save();
                }

                Console.WriteLine("Writing sprite: "+ outputFile);
                bitmap.Save(outputFile, ImageFormat.Png);
            }
        }
    }
}

Output from a run:


PS C:\dev\NSpriteGenerator> .\NSpriteGenerator.exe C:\temp\gfx c:\temp\sprite.png
Number of images: 10, total height: 640px, width: 34
Writing sprite: c:\temp\sprite.png

Nginx: Protecting a folder using htaccess

First we need to install the htpasswd application, it is located in the apache2-utils package. This package has no dependencies on apache, so it is safe to install it – it will not download the full apache for you 🙂

To install it on ubuntu type:

sudo apt-get install apache2-utils

Once installed we can use it to create an htaccess file.

htpasswd -c -b /path/to/htpasswd NewUser NewPassword

Now we need to add one block to the nginx config. Bellow is the config for this site, the part in bold is what needs to be added.

server {
    listen   80;
    server_name sourcecodebean.com;

    index index.php index.html;
    root /path/to/web/root;

    location ^~ /secret-dir/ {
        auth_basic            "Restricted";
        auth_basic_user_file  /path/to/htpasswd;
    }

    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass  127.0.0.1:9200;
        fastcgi_index index.php;
        fastcgi_param  SCRIPT_FILENAME  /path/to/web/root$fastcgi_script_name;
    }
}

Woho! All done!

A simple image sprite generator in Java

For some time I have been playing around with writing games for Android. The game loads the graphics in form of image sprites, so I needed a way to easily stick several png images into one image. I though there would be tons of free applications available for this purpose, but I didn’t find any, so I decided to create my own sprite generator.

The code is short and simple. Please feel free to use it as you please! 🙂

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

public class SpriteGenerator {

    public static void main(String[] args) throws IOException {

        if (args.length != 2)
        {
           System.out.print("Usage: SpriteGenerator {path to images} {output file}");
           return;
        }

        String imagePath = args[0];
        String outputFile = args[1];

        File imageFolder = new File(imagePath);
        File[] files = imageFolder.listFiles();

        // Read images
        ArrayList imageList = new ArrayList();

        for (File f : files)
        {
            if (f.isFile())
            {
                String fileName = f.getName();
                String ext = fileName.substring(fileName.lastIndexOf(".")+1,
                                     fileName.length());

                if (ext.equals("png"))
                {
                    imageList.add(ImageIO.read(f));
                }
            }
        }

        // Find max width and total height
        int maxWidth = 0;
        int totalHeight = 0;

        for (BufferedImage image : imageList)
        {
            totalHeight += image.getHeight();

            if (image.getWidth() > maxWidth)
                maxWidth = image.getWidth();
        }

        System.out.format("Number of images: %s, total height: %spx, width: %spx%n", 
                                      imageList.size(), totalHeight, maxWidth);


        // Create the actual sprite
        BufferedImage sprite = new BufferedImage(maxWidth, totalHeight, 
                                                      BufferedImage.TYPE_INT_ARGB);

        int currentY = 0;
        Graphics g = sprite.getGraphics();
        for (BufferedImage image : imageList)
        {
            g.drawImage(image, 0, currentY, null);
            currentY += image.getHeight();
        }

        System.out.format("Writing sprite: %s%n", outputFile);
        ImageIO.write(sprite, "png", new File(outputFile));
    }
}

Output from a run:


java -classpath {...classpath hell...} SpriteGenerator ./images ./sprite.png
Number of images: 10, total height: 640px, width: 34px
Writing sprite: /Users/peter/Development/Android/HappyFrog/gfx/sprite.png

AppHarbor – Heroku for .NET?

I have been reading about this new startup that offers a service called AppHarbor. It seems very much as the same idea as Heroku for Ruby, but for .NET. The basic idea is that you deploy your code by pushing your code onto the server using Git, the server then builds, runs unit tests and deploys your application. Super simple!

When I first read about AppHarbor I got the impression that is was running ontop of Microsoft Azure, which turned out to be all wrong. AppHarbor is running in the Amazon Cloud on EC2 instances. When it comes to databases AppHarbor provides access to MySQL and MSSQL. Interestingly they recommend users to use MySQL:

“we expect to be able to offer MySQL on faster hardware and with more redundancy than SQL Server at the same price point. If you are planning to build an app on top of AppHarbor and have the option, we recommend you go with MySQL.”

Another interesting choice is that they have chosen Nginx as their proxy/load balancer.

Ok, let me show you how easy it is to create a simple ASP.NET MVC 3 application and deploy it on AppHarbour Read more AppHarbor – Heroku for .NET?

Comparing every version of Internet Explorer

A few weeks ago I posted a video where Windows was upgraded all the way from Windows 1.0 to Windows 7. This week I found a video of a guy who compared all versions of Internet Explorer, from version 1 to the recently released version 9. Quite hillarious to see that IE5 actually scored better than IE8 in the Acid 3 test 🙂

MVC 3 RTM Install Error (after upgrading to VS2010 SP1)

Yesterday I installed Visual Studio 2010 SP1 on my home computer. After the installation I wanted to upgrade MVC3 to the RTM version (I had the RC version installed), so i uninstalled the RC and downloaded the new version. The installation came half way, then stopped, in the log file i found this:

Installation failed with error code: (0x80070643)

Not very helpful, but at least something to google. Then I found this blog post. The author describes pretty much the same issue that I had, so I did what he suggested, unpacked the installer using 7-Zip and installed the MSI packages in the following order:

  1. 1. aspnetwebpages.msi
  2. 2. aspnetwebpagesvs2010tools.msi
  3. 3. aspnetmvc3.msi
  4. 4. aspnetmvc3vs2010tools.msi
  5. 5. nuget.msi

This happily installed MVC3 without complaining. Thanks Michael!

The must have tools for C# development

Visual Studio 2010

I don’t think Visual Studio needs an introduction. VS 2010 brought us .NET 4.0 that contains a lot of new goodies!

ReSharper

ReSharper is the absolut must have for Visual Studio. It provides very improved navigation and search, refactoring, code generation, code cleanup and unit testing. I have gotten so used to having ReSharper installed so today I have a really hard time using Visual Studio without it.

Some useful shortcuts

  • Ctrl+T : Go to type
  • Ctrl+Shift-T : Go to file
  • Alt-Ins: Generate code (constructors, properties, implementing/overriding members)
  • Alt+Enter : Show available quick-fixes and context actions
  • Ctrl+Space : Symbol Code Completion
  • Ctrl+Alt+Space : Smart Code Completion
  • Shift+F12 : Find usages
  • Ctrl+Shift+R : Refactor this
  • Ctrl+R+R : Rename this
  • Ctrl+R+M: Extract method
  • Ctrl+R+V : Introduce variable
  • Ctrl+R+F : Introduce field
  • Ctrl+R+P : Introduce parameter
  • Alt+Shift+L : Locate in Solution Explore
  • PowerCommands for Visual Studio 2010

    PowerCommands 10.0 is a set of useful extensions for the Visual Studio 2010 adding additional functionality to various areas Visual Studio. This is some of the commands I find must useful:

    • Copy References
    • Paste References
    • Copy As Project Reference
    • Edit Project File
    • Open Containing Folder
    • Open Command Prompt Here
    • Unload Projects
    • Reload Projects

    Visual Studio 2010 – Productivity Power Tools

    Productivity Power Tools from the Microsoft Visual Studio team contains a lot of great extensions

    • Very much improved dialog for add reference
    • Solution Naigator – a enhanced Solution Explorer
    • Improved tab system for editor
    • Highlight current line (isn’t it weird that VS is missing this feature?)

    One annoying ‘feature’ is the triple click to navigate to source, never got it to work properly so I disabled it. Some shortcuts also colide with ReSharper so some tweaking is needed to make it work perfectly.

Older posts
Newer posts