source code bean

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 »

24 Mar, 2011

Comparing every version of Internet Explorer

Posted by: Peter In: General

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.

04 Mar, 2011

How bad is your tweeting disorder?

Posted by: Peter In: Stupidity

For the last week the news that Nokia has chosen Windows Phone 7 as their main operating system for all their new smart phones has been all over the news. A lot of people are very upset and say that Nokia should have gone with Android instead, or that they should have invested more in their own linux os Meego. Personally, looking at the options Nokia had, I think this is might be the best move Nokia could have done. Let me explain why.

For years Nokia has been struggling keeping Symbian alive. Symbian is an old operating system and has well served it purpose in millions of Nokia phones. However, during the last few years Nokia has totally failed on innovating, pretty much every other vendor now have smart phones running Andriod that offers more features and a better user experience then what Nokia can offer. Nokia needed to make a drastic change and the choices at this time were not that many.

  • Meego
  • Android
  • Windows Phone 7

Meego is Nokias in house developed linux based operating system. The vision behind Meego is great, but development has been too slow. From what I have seen of Meego it is a great operating system if you want to customize and geek around with your phone, but it is not yet ready for prime time. Read the rest of this entry »

Recently I decided to switch hosting provider from a shared server to a VPS. My choice of linux is Ubuntu so i installed the latest version, Ubuntu 10.10 server. Instead of using Apache as webserver, which has been my choice of webserver for years, I decided to go for Nginx. Nginx is known for its great performance, but what really caught my attention (and the main reason to why I picked it) is that it is so easy to install and configure.

Installing Nginx and configuring the site
The first step is to install the Nginx webserver and PHP.

apt-get install nginx php5-cli php5-cgi spawn-fcgi
update-rc.d nginx defaults
/etc/init.d/nginx start

Then we need to create the configuration for our site.
/etc/nginx/sites-enabled/sourcecodebean:

server {
        listen 80;
        server_name www.sourcecodebean.com;

        location / {
                rewrite ^/(.*) http://sourcecodebean.com/$1 permanent;
        }
}

server {
    listen   80;
    server_name sourcecodebean.com;

    index index.php;
    root /var/www/sourcecodebean.com/public_html;

    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:9000;
        fastcgi_index index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/sourcecodebean.com/public_html$fastcgi_script_name;
    }
}

Read the rest of this entry »

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!