source code bean

07 Jun, 2011

Javascript on the server side

Posted by: Peter In: Javascript|Web

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.

Read the rest of this entry »

02 May, 2011

Reference types are always passed by value in C#

Posted by: Peter In: .NET|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 the rest of this entry »

18 Apr, 2011

A simple image sprite generator in C#

Posted by: Peter In: .NET|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 :)

  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Imaging;
  4. using System.IO;
  5. using System.Linq;
  6.  
  7. namespace NSpriteGenerator
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             if (args.Length != 2)
  14.             {
  15.                 Console.WriteLine("Usage: NSpriteGenerator {path to images} {output file}");
  16.                 return;
  17.             }
  18.  
  19.             var imagePath = args[0];
  20.             var outputFile = args[1];
  21.            
  22.             var imageFolder = new DirectoryInfo(imagePath);
  23.            
  24.  
  25.             // Read images
  26.             var imageList = imageFolder.GetFiles("*.png")
  27.                     .Select(file => Image.FromFile(file.FullName));
  28.  
  29.  
  30.             // Find max width and total height
  31.             var maxWidth = 0;
  32.             var totalHeight = 0;
  33.  
  34.             foreach(var image in imageList)
  35.             {
  36.                 totalHeight += image.Height;
  37.  
  38.                 if (image.Width > maxWidth)
  39.                     maxWidth = image.Width;
  40.             }
  41.  
  42.             Console.WriteLine(string.Format("Number of images: {0}, total height: {1}px, width: {2}", imageList.Count(), totalHeight, maxWidth));
  43.  
  44.  
  45.             // Create the actual sprite
  46.             var currentY = 0;
  47.  
  48.             using (var bitmap = new Bitmap(maxWidth, totalHeight))
  49.             {
  50.                 using (var canvas = Graphics.FromImage(bitmap))
  51.                 {
  52.                     foreach (var image in imageList)
  53.                     {
  54.                         canvas.DrawImage(image, 0, currentY);
  55.                         currentY += image.Height;
  56.                     }
  57.                     canvas.Save();
  58.                 }
  59.  
  60.                 Console.WriteLine("Writing sprite: "+ outputFile);
  61.                 bitmap.Save(outputFile, ImageFormat.Png);
  62.             }
  63.         }
  64.     }
  65. }
  66.  

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

18 Apr, 2011

Nginx: Protecting a folder using htaccess

Posted by: Peter In: Linux|Web

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!

12 Apr, 2011

A simple image sprite generator in Java

Posted by: Peter In: Android|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! :)

  1.  
  2. import javax.imageio.ImageIO;
  3. import java.awt.*;
  4. import java.awt.image.BufferedImage;
  5. import java.io.*;
  6. import java.util.*;
  7.  
  8. public class SpriteGenerator {
  9.  
  10.     public static void main(String[] args) throws IOException {
  11.  
  12.         if (args.length != 2)
  13.         {
  14.            System.out.print("Usage: SpriteGenerator {path to images} {output file}");
  15.            return;
  16.         }
  17.  
  18.         String imagePath = args[0];
  19.         String outputFile = args[1];
  20.  
  21.         File imageFolder = new File(imagePath);
  22.         File[] files = imageFolder.listFiles();
  23.  
  24.         // Read images
  25.         ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();
  26.  
  27.         for (File f : files)
  28.         {
  29.             if (f.isFile())
  30.             {
  31.                 String fileName = f.getName();
  32.                 String ext = fileName.substring(fileName.lastIndexOf(".")+1,
  33.                                      fileName.length());
  34.  
  35.                 if (ext.equals("png"))
  36.                 {
  37.                     imageList.add(ImageIO.read(f));
  38.                 }
  39.             }
  40.         }
  41.  
  42.         // Find max width and total height
  43.         int maxWidth = 0;
  44.         int totalHeight = 0;
  45.  
  46.         for (BufferedImage image : imageList)
  47.         {
  48.             totalHeight += image.getHeight();
  49.  
  50.             if (image.getWidth() > maxWidth)
  51.                 maxWidth = image.getWidth();
  52.         }
  53.  
  54.         System.out.format("Number of images: %s, total height: %spx, width: %spx%n",
  55.                                       imageList.size(), totalHeight, maxWidth);
  56.  
  57.  
  58.         // Create the actual sprite
  59.         BufferedImage sprite = new BufferedImage(maxWidth, totalHeight,
  60.                                                       BufferedImage.TYPE_INT_ARGB);
  61.  
  62.         int currentY = 0;
  63.         Graphics g = sprite.getGraphics();
  64.         for (BufferedImage image : imageList)
  65.         {
  66.             g.drawImage(image, 0, currentY, null);
  67.             currentY += image.getHeight();
  68.         }
  69.  
  70.         System.out.format("Writing sprite: %s%n", outputFile);
  71.         ImageIO.write(sprite, "png", new File(outputFile));
  72.     }
  73. }
  74.  

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

06 Apr, 2011

AppHarbor – Heroku for .NET?

Posted by: Peter In: .NET|C#|Web

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 the rest of this entry »

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 :)

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: (0×80070643)

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!

08 Mar, 2011

The must have tools for C# development

Posted by: Peter In: .NET|C#

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.

Really impressive to see that it actually is possible to upgrade all the way from Windows 1.0 (DOS 5.0) to Windows 7 and keep some of the applications and user settings. The only OS I missed was Windows ME (not that any sane person used that OS but anyway), Andy explains that Windows ME did not provide an upgrade path to Windows 2000 and that is why he left it out. Read more details on his blog.

It would be fun so see someone do the same with for example Ubuntu or Redhat, upgrade from the earliest version to a current version.


  • Joe: It looks like IceCoffee Script may provide the 'await' keyword to JavaScript. http://maxtaco.github.com/coffee-script/
  • Florian: Dealing with events has two primary fashions: imperative (synchronous) code, and callback (asynchronous) code. Both are legitimate styles, for some
  • Joe: I think we haven't seen true PaaS offering yet in Azure. If you use a webrole you're still running on your own VM. This is still not true multi-tena

About

Welcome to source code bean! On this site I post stuff that I encounter in my job and spare time. The content is mostly related to .NET development, but my interest in techonology is very broad, so often you will find posts on totally different subjects!