Archive

Author Archive

Changing Visual Studio Registration Information

March 17th, 2010

This morning as I started Visual Studio it bugged me that the splash screen reported my registration information as “User” at “Microsoft”. My name isn’t “User” and I don’t work for “Microsoft”, at least not directly. This is something that has bothered me in the past but I’ve never dug into it far enough to figure out how to fix it.

This afternoon after a little research I was able to piece together the steps necessary to update the information. I found this question on Stack Overflow that had some useful information but not a complete solution. I also came across this post on John Robbins’ blog and between the two of them I was able to close the gap.

Updating Company Name and User for Windows
The first step is to open the registry editor and navigate to:

32 bit: HKLM\Software\Microsoft\Windows NT\CurrentVersion
64 bit: HKLM\Software\Wow6432Node\Microsoft\WindowsNT\CurrentVersion

Here you can edit the RegisteredOrganization and RegisteredOwner values.

CompanyNameKey

Updating Visual Studio User Registry Key
The next step is to update the user name for your Visual Studio registration. This is also a key in the registry at:

32 bit: HKLM\Software\Microsoft\VisualStudio\9.0\Registration
64 bit: HKLM\Software\Wow6432Node\Microsoft\VisualStudio\9.0\Registration

VisualStudioRegistrationKey

Getting Visual Studio to Use the New Information
Modifying the keys is the first step. However, it turns out that Visual Studio actually stores the information to be displayed in a SplashInfo key. The info is stored in binary data. Fortunately we do not need to modify the binary value in the registry. Instead simply run devenv /setup and the information will be updated automatically.

Run DevEnv Setup SplashInfoKey

Verifying the Information
To verify that the information was updated correctly you can either view the SplashInfo key in the registry or simply run Visual Studio. I’m now “Stuart Thompson” at “SoftSource Consulting”. Much better!

SplashScreen

Disclaimer
This process worked for me. Your mileage may vary. This information is provided as is without any implied warranty of fitness for any purpose. I am not responsible for corrupted Visual Studio installations or registry hives nor for any other problems that may arise as a result of using these steps. USE AT YOUR OWN RISK.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Tools ,

Serialize SQL parameters

March 15th, 2010

Convert a collection of SQL parameters into a name:value string suitable for writing to a log.

/// <summary>
/// Serializes a collection of
/// <see cref="System.Data.SqlClient.SqlParameter"/>s.
/// </summary>
/// <param name="parameters">
/// The collection of parameters to serialize.
/// </param>
/// <returns>
/// A <see cref="System.String"/> that contains the parameter values.
/// </returns>
public string SerializeSqlParameterCollection(
    SqlParameterCollection parameters)
{
    StringBuilder sb = new StringBuilder();
    foreach (SqlParameter parameter in parameters)
        sb.Append(
            String.Format("{0}:{1} ",
                parameter.ParameterName, parameter.Value));
    return sb.ToString();
}

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

.NET Framework, Programming, Snippets , , ,

What’s new in the .NET Framework 4?

March 12th, 2010

This article gives a great overview of the new features that are coming in the next version of the .NET framework.

http://msdn.microsoft.com/en-us/library/ms171868(v=VS.100).aspx#core_new_features_and_improvements

I’m very excited for April 12th 2010.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Uncategorized

Http Modules

February 18th, 2010

The .NET framework provides several mechanisms for extending the behaviors of web pages and other endpoints. One such technique is the http module. Modules are often either overlooked as a solution or are considered too heavyweight or scary for use. This is unfortunate as they are a powerful item in the ASP.NET development toolbox.

An http module is a single unit of code that is executed as part of the web request pipeline. When a web request is received, the list of registered modules are afforded the opportunity to inject themselves at several stages in the execution pipeline. Each module has the opportunity to inspect or modify parts of the request before or after it is processed. This makes them a powerful mechanism for attaching custom behaviors. Modules also have a flexible activation model as they can be attached or detached via configuration allowing them to be enabled or disabled at will without affecting a production site.

The full source code for this example can be found here.

How to Create an HttpModule
The ASP.NET Module type is in the Web category under the Add New Item dialog.

241@229_tmp6C6D

Remove the default sample code that is included in the template. The LogContext event handler is implemented in the template for demonstration purposes but is not used in this example. Your class should now look similar to the following:

using System;
using System.Web;

namespace ModuleWebApp
{

    ///

    /// Custom http module.
    /// 

    public class MyNewModule : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose() {}

        ///

        /// Initializes the module.
        /// 

        /// <param name="context">The application context.</param>
        public void Init(HttpApplication context)
        {

        }

        #endregion

    }
}

Initializing the Module

Modules perform work by registering handlers for events in the request execution pipeline such as BeginRequest and EndRequest. It is within the event handlers that they perform their task. In the example below, the Init method is used to register handlers for the BeginRequest and EndRequest events.

///

/// Raised when the module is initialized.
/// 

/// <param name="context">The application context.</param>
public void Init(HttpApplication context)
{
    context.BeginRequest += new EventHandler(context_BeginRequest);
    context.EndRequest += new EventHandler(context_EndRequest);
}

Implementing the Event Handlers and Finishing the Module

Next provide implementations for the event handlers. This example module is going to calculate and display the time it takes to execute a page within the application. The code example below is for the completed module class. It contains the following changes:

  • Declaration of a dictionary of stopwatches that stores the execution timers.
  • Implementation of the BeginRequest and EndRequest handlers to start and stop the timers.
  • Instantiation of the dictionary of timers in the Init method.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web;

namespace ModuleWebApp
{

    /// <summary>
    /// A custom http module used to time request execution.
    /// </summary>
    public class RequestTimer : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose() { }

        /// <summary>
        /// Raised when the module is initialized.
        /// </summary>
        /// <param name="context">The application context.</param>
        public void Init(HttpApplication context)
        {
            _timers = new Dictionary<Guid, Stopwatch>();

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Raised when the request begins.
        /// </summary>
        /// <param name="sender">The source of the event; the <see cref="System.Web.HttpApplication" />.</param>
        /// <param name="e">An <see cref="System.EventsArgs"/> that contains event data.</param>
        protected void context_BeginRequest(object sender, EventArgs e)
        {
            Guid timerId = Guid.NewGuid();
            Stopwatch timer = new Stopwatch();
            _timers.Add(timerId, timer);

            HttpContext.Current.Items.Add(EXECUTION_TIMER_KEY, timerId.ToString());

            timer.Start();
        }

        /// <summary>
        /// Raised when the request ends.
        /// </summary>
        /// <param name="sender">The source of the event; the <see cref="System.Web.HttpApplication" />.</param>
        /// <param name="e">An <see cref="System.EventsArgs"/> that contains event data.</param>
        protected void context_EndRequest(object sender, EventArgs e)
        {
            string timerId = HttpContext.Current.Items[EXECUTION_TIMER_KEY] as string;

            if (String.IsNullOrEmpty(timerId))
                return;

            Stopwatch timer = _timers[new Guid(timerId)];
            if (timer == null)
                return;

            timer.Stop();

            double elapsedSeconds = (timer.ElapsedMilliseconds) / (double)1000;

            HttpContext.Current.Response.Write(
                String.Format(
                    "Request executed in {0} seconds ({1} ticks).",
                    elapsedSeconds.ToString(),
                    timer.ElapsedTicks.ToString()));
        }

        #endregion

        #region Fields

        /// <summary>
        /// The collection of execution timers.
        /// </summary>
        private Dictionary<Guid, Stopwatch> _timers;

        #endregion

        #region Constants

        private const string EXECUTION_TIMER_KEY = "__ExecutionTimer_Id";

        #endregion

    }

}

Some of the concepts used here are beyond the scope of this discussion. Research the Stopwatch class for more information on how to use timers. See the HttpContext class to learn more about request and response objects.

Registering the Module

The final step is to register the module so that it is instantiated and executed on every request. This is done via the web.config file. The <system.web> section contains an <httpModules> section. The registration configuration line for the module should be added to the <httpModules> section as shown below:


	
	
		
		
    
	

That’s it! Running the web application should display the default.aspx page, which now shows the execution time in elapsed seconds (and ticks). This information is displayed at the end of every web request so it works on every page in the system. If you inspect the context_EndRequest handler you can see the following lines:

HttpContext.Current.Response.Write(
	String.Format(
		"Request executed in {0} seconds ({1} ticks).",
		elapsedSeconds.ToString(),
		timer.ElapsedTicks.ToString()));

The HttpContext class exposes the current Request and Response. These are the http request and response that are received from and sent to the client respectively. The execution time was displayed on the page because this handler wrote to the response object after the request had finished executing. The timer was started when the request started and stopped when the request ended. The time taken for the page to performing its processing and the request to finish is then displayed in the response. It is in this way that modules interact with all requests in the system and provide global level behaviors that are attached via configuration.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

.NET Framework, ASP.NET, Programming , ,

Android Emulator Problems in Eclipse

September 9th, 2009

I’ve recently been playing with the Android SDK using Eclipse 3.5 as a development environment.  I coded up the Hello World sample and all was progressing smoothly.  However, I then coded my own project and after a couple of runs the Android emulator simply refused to initialize.  I would always get the same error message about how the runtime had requested to terminate the emulator in an unexpected way.  A few short Googles later and it seemed as though I was not alone in experiencing this problem.

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application’s support team for more information.

I tried rebooting my machine but to no avail as well as completely cleaning out my project.  It seemed that several people had even tried uninstalling and reinstalling the Android SDK without success.  It was at this point that I remembered I’d switched some of the emulator settings right around the time that the failure started to occur.  A little investigation showed that I’d added support for an 8MB  SD card to my virtual device in an attempt to more closely emulate the G1 that I own.  I quickly adjusted the settings back to their defaults and the emulator started functioning again.  I’m hopeful that with more experience I’d have been able to diagnose the problem via logging output or a more detailed debug mode.  As it is right now I’m something of a newbie to Android development so I just figured that some temporary files for the emulator were borked.

Every so often I seem to need to do this sort of thing to remind myself of the age old truth.  If software starts to break without any clear indication of why, it’s most likely due to something seemingly innocuous that the developer intentionally changed.  Always question your own actions first. :)

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Android, Programming , , ,

Mathematical Notation on the Web

August 27th, 2009

I’ve recently been researching ways of displaying math equations online. To my surprise I have found that the packaged options for doing this are quite limited, especially on the Microsoft technology stack. There is fairly good coverage for Java and in the form of php and perl scripts, but very little natively for the .NET framework. As usual there are several formats for storing equations, including OMML from Microsoft, a recommendation from W3C called MathML and what is best described as the lingua franca in the form of LaTeX.

image001

Native Browser Support
Several google searches showed that I was not alone in this search. However, most of the solutions I found came with caveats about which browsers they would work with and required the installation of additional software on client machines in order to work. Installing additional software on client machines defeats the purpose of providing a browser-based experience and in some environments isn’t even an option. I needed to find something that would work all modern browsers without requiring changes on the client.

Internet Explorer – MathPlayer
Design Science (who originally created the Equation Editor that is now part of Microsoft Office) offer a product called Math Player. Math Player is an ActiveX control that renders MathML equations within Internet Explorer. It provides good accessibility support, is free for non-commercial uses, and as ActiveX controls go it was a painless installation. However, because it is an ActiveX control is requires a client installation and only works in IE. Furthermore, the player only seemed to work for pages with the .xhtml extension that declared that XHTML doctype and exhibited some strange visual artifacts if either the MathML or containing page were not formatted correctly.

FireFox MathML Support
FireFox has made some good progress towards natively supporting MathML. However, at present it does not contain a full solution and instead requires downloading the latest nightly build and the installation of several fonts.

Chrome MathML Support
Despite being widely requested, Chrome does not natively support MathML. I could not find conclusive information either way as to whether MathML support is on the Chrome development roadmap.

For the next part of my research I’m going to look into LaTeX as it really seems to be the de facto standard from a tools and community support perspective. I have seen several examples, including WikiPedia that stores equations and diagrams in LaTeX format and then renders them to images on the fly as part of the page. That sounds like it could be a good way to go.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Internet , , , , , , ,

The Secret to Organizational Agility

December 8th, 2008

Mike Cottmeyer wrote an excellent article about the importance of eliminating dependencies in agile projects:
http://www.leadingagile.com/2008/12/secret-to-organizational-agility.html

How many times have the following been true:

  • “Many teams are trying to sprint through product development using a traditional MRD or PRD.”
  • “Many teams are working with traditional project managers who are doing their best to be agile, but have been trained to manage dependencies and tell people what to do.”
  • “Teams are trying to be agile with tightly coupled software architectures, insufficient test coverage, legacy code bases, and unable to do a daily build.”

Removing dependencies is a key step that can be taken towards a truly agile development environment.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Agile

Be careful with your online brand…

December 8th, 2008

As the popularity of Web 2.0 is growing, so is the ability for others to observe and evaluate your story and your personal online brand.  This article from JASE marketing reports that a “survey of 500 top colleges found that 10 percent of admissions officers said they look at MySpace and Facebook to evaluate applicants.”

I’ve always lived by two golden rules with regards to blogging:
1) Blog only something you would wish to see printed and cited at any time in the future.
2) Do not edit or update a blog assuming that a printed/archived/cached copy of the original does not exist.

It’s a general faux pas to update a blog post for any reason.  The web is alive with caches and indexes so the chances are that the original is still out there for people to compare.  Spelling errors are generally ok, but if the content of an article is to be updated it is good form to list at Updated: [description of update] at the top or bottom of the post.  If an opinion is being revised, be clear about why there is a change in stance.  Comments are a great way to revise an opinion after learning new information as it allows readers to see the thought processes and perhaps benefit from the same line of thinking that provoked your own turn around.

Web 2.0 means we are all ultra-connected.  This can be great not only for staying in touch with friends but also for business networking and establishing a reputation and a brand in the online world.  However, remember that this “permanent record” can go both ways: and this one is for the world to see.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Uncategorized

Ruby on Rails Setup with DreamHost

October 28th, 2008

As step 1 of my latest experiment, I’ve started by configuring a Ruby on Rails site with DreamHost.  This actually involved quite a bit of setup work, which is not unusual when remotely hosting a new website.  I have documented the steps as fully as I can for anyone else curious about trying development in Rails.

Step 1 – Signup with DreamHost
You can sign up using this link or use the promo code LETMETRYRAILS and receive $50 off (i.e. no setup fee).

Step 2 – Configure your domain
The next step is to configure your domain.  We’ll start at the DreamHost configuration panel.  Select Domains and then Manage Domains from the left-hand sidebar.  This will bring up the list of domains in your account.  Click the Edit button in the Web Hosting column.

This will open the settings page for that domain.  Check the FastCGI and Passenger (mod_rails) checkboxes.  Finally click the Change fully hosted settings now! button (note that this button is not at the bottom of the page, rather at the end of the first section).

FastCGI support allows your Rails project to run much faster.  The Passenger (mod_rails) option allows your Rails application to be configured much more easily and is the preferred DreamHost method for hosting Ruby on Rails applications.

Step 3 – Configure your FTP/SSH user
We will be performing much of the setup and configuration of the website via SSH.  We will need to setup a user account for this purpose.  During your initial setup you should have created an ftp account for your domain, probably with the same name as that domain (if you accepted the defaults).  Select the Users and then Manage Users options from the left side-bar.  Click the Edit button next to your user in the Actions column.

This will open the following page where you can edit your user.  Change the User Account Type to Shell account and select the /bin/bash shell type.  Finally, hit the Save Changes button at the bottom of the page.

This enables the user to connect using a Telnet/SSH client, which is exactly what we are going to do next.

Step 4 – Download some tools
Next we’re going to download the tools we’ll need to create and configure our rails website.  We’ll need the latest release of Ruby, MySQL, HeidiSql, and PuTTY.  HeidiSql is a free gui for maintaining MySQL databases.  PuTTY is a free Telnet/SSH client that we’ll use for remote configuration of our site.  Note that you do not need to signup on the MySQL site to get the download.  Click the No thanks, just let me download link.

Step 5 – Installing Rails
Now that we have the necessary tools installed it is time to setup Rails locally.  Fortunately, Ruby comes with everything we need to get setup and running, including the WEBrick web server that we can use to run and test our site before deployment.  When installing Ruby, be sure to check the Enable RubyGems option on the first page of the installer.

Once the installer completes, open up a command window and execute the following commands:

cd ruby/bin
gem update –system
gem install rails –version 2.1.2

This will use the gem system to install rails locally.  If everything is successful, your command window should look something like this:

You may need to restart your system at this point.  Ughh.  This is because Windows Vista and XP sometimes struggle to detect that new environment variables were added to the $PATH.  Unless you relish fully qualifying the C:/Ruby/bin directory on the next few commands, I’d advise you restart now.  It’s also not a bad idea since we did just install four new programs.  I’ve found Windows seems to run more smoothly if you reboot after installing new things.

Step 6 – Create your Rails site locally
Now that we have Rails setup, let’s create a simple site locally.  I created a new directory on C:\ called projects in which to develop the site.  Open a command prompt and type the following:

cd \
md projects
cd projects
rails MyRailsSite

This will create your rails site in C:\projects\MyRailsSite.  Before we add our first view and controller, let’s quickly check that everything wired up properly.  To do this we need to start the WEBrick server:

cd C:\projects\MyRailsSite
ruby script/server

Vista may ask if you wish to unblock Ruby, which you do.  Your command prompt should look something like the following:

You can now navigate to http://127.0.0.1:3000 to see your site.  If everything is configured correctly you should see the Ruby on Rails welcome page:

We can shutdown the WEBrick server by pressing Ctrl-C in the command prompt window.

Now let’s create our first controller and view.  We’re going to keep it simple and put up a page that displays the message “Hello World!”.  At the command prompt type the following:

cd projects\MyRailsSite
ruby script/generate controller HelloWorld


This will generate a new controller for you as well as a new view.  If you aren’t familiar with MVC development, just follow along for now until the sample becomes clear.  The rest will come in time and with additional reading and practice.  For now it is suffice to say that a controller will perform the work for a web page request where the view will display the results of that work.

Let’s edit the controller that was generated.  To do this, open up an explorer window, navigate to C:\projects\MyRailsSite\app\controllers, right-click over the hello_world_controller.rb file and select Edit from the context menu.  This should open the controller file in the SciTE editor.  We need to add lines to the class to respond to the index action.  The index action is the default action that will be performed for a controller.  To do this, edit the file to look like the following:

This controller will now set the variable @message to the literal “Hello World”; when the index action is requested.  Controllers perform actions.

Save the file and close it.  Now we will create a view to display the message.  Navigate to the C:\projects\MyRailsSite\app\views\hello_world directory in explorer (notice how Rails created the view directory for us).  Right-click in the directory and create a new file called index.html.erb.  Now right-click this file and open it in your favorite editor (Notepad will suffice).  Add the following to the file:

Save the file and close the editor.  We’re almost ready to test out our new controller and view.  First, however, we need to configure a route for our site.  A route is a mapping from an end-point (url) in our site to an actual controller and view that will fulfil the request.  In explorer, navigate to C:\projects\MyRailsSite\config, right-click the file routes.rb and select Edit from the context-menu.  This will open your routes file in the SciTE editor.  Almost the entire file is commented out.  Most of this file contains instructions for configuring custom routes.  We’re going to comment out the last two lines of the file and insert a single mapped route of our own.  Edit the end of the file to look like the following:

This line connects the helloworld route to the hello_world controller for the index action.  The action specification isn’t actually necessary as the index action is assumed by default if none is specified, but I prefer to be explicit.

There is one final thing we’ll need to do before we can browse to our page locally.  We need to install and configure MySQL.

Step 7 – Install and configure MySQL
This is a very short step.  Run the MySQL setup package you downloaded earlier and select the Typical installation option.  Then hit Next->Next->Finish all the way to the end.  When the configuration wizard runs, choose Detailed Configuration, then Developer Machine, then Multifunctional Database.  When asked for a location for the Inno files, I used C:\projects\MySQL.  Choose Decision Support (DSS)/OLAP then leave both boxes checked on the next dialog with 3306 as the port number.  Choose Standard Character Set, then check Install As Windows Service and leave Include Bin Directory in Windows PATH unchecked.  Enter a new root password, leave Create An Anonymous Account unchecked.  Finally, hit Execute to finish the configuration wizard.  MySQL is now installed and configured.

Step 8 – Create a database for our project
We’ll need to create a database for our project.  To do this we’ll need to install HeidiSql.  Let’s run that installer now.  I use the defaults from the installer except on the Select Additional Tasks dialog where I uncheck Associate .SQL Files with HeidiSQL. When the installer completes it will launch the HeidiSQL gui.  Click the New button at the top of the first dialog.  Name the connection MyRailsSite, click OK, and then enter the password you selected during your MySQL installation into the password box provided.  The first thing we’re going to do is create a new database.  Right-click over root@127.0.0.1 in the left side-bar and select Create database from the context menu.  Enter MyRailsSite as the database name and click ok.  Now select Tools->User-Manager from the top menu.  We’re going to create a new user to avoid using the root user in our application.  For the Username type myrailsdbuser, set From Host to localhost, and type a password for your new user.  Don’t use the same password you used for root.  In the Allow access to list, left-click over the myrailssite database (it will turn yellow).  Now click Add User.  Then click Close to close the user manager dialog.  Now we’ve created a database and a specific user for our Rails application to use.

Step 9 – Configure Rails to use the database
Finally we need to configure our Rails site to use our new database.  In an Explorer window, navigate to C:\projects\MyRailsSite\config, right-click the database.yml file and edit it in your favorite editor (I use TextPad but NotePad will suffice).  Edit your file to look like the following:

Step 10 – Testing the site locally
We’re finally ready to test the site locally!  Open up a command window are run the following to start the WEBrick server:

cd c:\projects\myrailssite
ruby script/server

Then open a browser and navigate to http://127.0.0.1:3000/.  You’ll notice that the Rails welcome page still displays.  However, change the url in the browser to point to http://127.0.0.1:3000/helloworld.  You should now see your view displaying the message “Hello World!”.  Let’s remove the default index page now and then make your default route point to your helloworld view.  To do this, open up Explorer and navigate to c:\projects\myrailssite\public.  This is your site’s public directory.  From here, delete the index.html file.  That’s the welcome page gone; we don’t need it anymore.  Now navigate to c:\projects\myrailssite\config and open the routes.rb file again.  Add the following line just before the map.connect line we added earlier:

map.root :controller=>”hello_world”

This configures the root route to point to our hello world controller.  As we stated earlier, there is no need to specify the index action as it is assumed by default.  Save and close the file, then browse to http://127.0.0.1:3000 once more.  Your site should now be displaying your “Hello World!” message.  Note how the url is just http://127.0.0.1:3000 and doesn’t have helloworld at the end.  This is an important point about routes.  You aren’t navigating a particular directory structure on the site, you are simply navigating routes and actions.  The controller could be named anything you like as long as the route for a particular end-point correctly routed requests for that end-point to your controller.  For now, let’s stop the WEBrick server and close the command window.  The final task is to get your Rails site up to DreamHost and serve your “Hello World!” request remotely.

Step 11 – Configuring DreamHost for your site
This final configuration step may seem a little confusing at first, but only if you aren’t familiar with Linux and BASH.  It doesn’t take very long and it isn’t important to understand how it works because you’ll only need to do it once.  We’re going to install version 2.1.2 of rails to your remote host because that’s the version that Passenger (mod_rails) needs in order to run your site.  This is where we’ll need PuTTY.  Fortunately there is no installation step with PuTTY.  It is simply an executable that you download and run.

When you run PuTTY, you will need to supply the username and password of the user we configured in step 3.  This will connect you to the server that will host your site.  The following instructions are commands to enter into the BASH shell as well as instructions on editing your ~/.bash_profile file (which is similar to environment settings for the command shell in Windows).  The first part of these instructions is about editing your ~/.bash_profile file to ensure that some paths and other required settings are configured before beginning installation.  These instructions have been adapted from the DreamHost wiki article on this topic.

Before we update rails, let’s first create our Rails site remotely.  To do this, first run PuTTY.  For the Host Name you will supply your domain name in the form www.MyDomainName.com.  Then click Open.  I choose No from the next dialog as I don’t want to store anything in the registry.  You will now enter the username and password for the user we created in step 3.  When you connect, type ls and hit enter.  This is the BASH command to list the contents of the current directory.  You should see MyDomainName.com listed in the output.  We are going to navigate to that folder and then create a rails site inside that folder.

cd MyDomainName.com
rails MyRailsSite

This will create a Rails site on the DreamHost server, the same way we did it locally earlier.  We’re going to create the site like this and then upload our site files from our local machine to the remote site.  To upload our files, we’ll use an Explorer window and ftp.  First, however, we need to create a copy of our database.yml and environment.rb files.  This is because those files will be different on our remote host than they are locally.  Create a copy of each of those files called database.yml.live and environment.rb.live now.  Now edit the database.yml.live file to look like the following:

Edit your environment.rb.live file and uncomment the following line (its on line 5):

ENV['RAILS_ENV'] ||= ‘production’

This is important because running in development mode under FastCGI will cause memory leaks on the DreamHost server.  They will catch them and clean them up but it’s better to run in full production mode and not cause problems.

One final change we need to make locally is to update the c:\projects\myrailssite\config\environments\production.rb file.  Comment out the config.action_view.cache_template_loading = true line as it causes problems with the Passenger product that will host our site.

Now we’re ready to install Rails 2.1.2 remotely.  Switch back to your PuTTY session (or log in again if you exited).  Let’s first edit the ~/.bash_profile file.  To do this we will be using the nano text editor.  To open the ~/.bash_profile file in nano, type the following:

nano ~/.bash_profile

Now you can use the cursor keys to navigate the file.  We need to add the following lines to the end of the file:

# Path settings
export GEM_HOME=”$HOME/.gems”
export GEM_PATH=”$GEM_HOME:/usr/lib/ruby/gems/1.8″
export PATH=”$HOME/bin:$HOME/.gems/bin:$PATH”
export RUBYLIB=”$HOME/lib:$RUBYLIB”

# Stops the DreamHost processes from killing the gem install process
alias gem=”nice -n19 ~/bin/gem”

To save your changes press Ctrl-O then hit enter.  Press Ctrl-X to exit the editor and return to the shell.  You can now type cat ~/.bash_profile and the contents of the file should be printed out.  This is a good way to check that your changes were saved and that you typed everything correctly.

Now we need to perform the installation.  The following commands will achieve this:

cd ~
mkdir .gems

mkdir bin lib src

cd ~/src
wget http://rubyforge.org/frs/download.php/43985/rubygems-1.3.0.tgz
tar xzvf rubygems-1.3.0.tgz
cd rubygems-1.3.0
ruby setup.rb –prefix=$HOME

cd ~/bin
ln -s gem1.8 gem

For more information on what each of these steps is doing check the DreamHost wiki article.  We can check that the path and gem versions are correct by typing the following:

which gem
gem -v

These commands should return /home/USERNAME/bin/gem and 1.3.0 respectively.  Now we can execute the command to install Rails 2.1.2, which is:

gem install rails –version 2.1.2

What we’ve accomplished here is to install RubyGems and Rails 2.1.2 to our hosted server.  The last thing we need to do to make everything work is to use rake to freeze our version of Rails to 2.1.2 so that Passenger will use our Rails installation when running our site.  The commands to do this are as follows.  Please note that you need to supply your domain name in the format MyDomainName.com and the name of your Rails site in place of MyRailsSite in the first command.  This simply changes the current directory so that we’re running rake in the right place.

cd ~/MyDomainName.com/MyRailsSite/
rake rails:freeze:edge TAG=rel_2-1-2

That’s it!  Phew.  That felt like a lot of work, but at least you only have to do it once.

Step 12 – Deploying and testing your site remotely
Now that we’ve set up the environment with DreamHost, the only task left is to deploy the site remotely and test it out.  Before we do that though, we are going to check one last configuration setting in the DreamHost control panel, just to be sure that everything is setup correctly.  If you navigate to Domains->Manage Domains in the left side-bar and then click the Edit button again (see step 2), then check out the Specify your web directory setting.  This is where DreamHost will send requests to MyDomainName.com.  It should be set to:

/home/username/MyDomainName.com/MyRailsSite/public

By setting the directory to the public directory of your Rails site, it means that users cannot navigate outside of that directory and browse places that they aren’t supposed to be.

Let’s finish up and deploy our Rails site from the local machine to the remote server.  We’ll use Explorer and ftp to do this.  Open up Explorer and type ftp://ftp.MyDomainName.com into the address bar.  Now open up the MyDomainName.com and then MyRailsSite folders.  You will need to copy your app directory from your local machine at c:\projects\myrrailssite\app up to the remote server.  When you have copied these files, navigate to the pubilc directory on the remote server and delete the index.html file.  We don’t need the Rails welcome page on live anymore either!  Then navigate to the config directory and copy the routes.rb, environment.rb.live and database.yml.live files up to the corresponding folder on the server.  Don’t forget to rename these to environment.rb and database.yml on the remote server.  We only renamed them so that we could have two different files locally.  Finally, navigate to the config/environments folder and copy the production.rb file that we edited up to the corresponding location on the remote server.  From now on, when you deploy your site, you will only have to copy the app folder to the remote server (unless you change config settings that is).

The final step before we can test our site on live is to setup the MySQL database on the DreamHost side to match the one we set up locally.  Since we didn’t create any database tables, this is fairly simple to do through the DreamHost interface.  Go to Goodies->Manage MySQL and repeat the same steps here as we did in step 8.  You can also use HeidiSQL if you want to manage your database remotely that way.  However, for now I recommend using the DreamHost web interface to do this work.  All you need to ensure is that the database name and username/password for that database match the settings you specified in your database.yml file.  I’m going to cover using databases in Rails in more detail in a future article.  For now we just need to get an empty database and a user that has access to keep Rails happy.

Congratulations!  Assuming that everything was wired up correctly, you should now be able to open a browser and navigate to http://www.MyDomainName.com to see your site being hosted remotely.

Hopefully this article will help you get up and running with a basic Rails site that is hosted remotely.  The focus of this article was understanding the relationship between running a Rails site locally and hosting it on a remote server.  Setting up your development in this way from day one will save a lot of headaches later when it comes to deployment time.  Developing and testing locally, then deploying to a live host means that problems can be identified early and that changes can be tested locally rather than on a live site.  I’m going to expand upon this article as part of my ongoing experiement with ASP.NET, Silverlight, PHP, and Ruby on Rails.  Next we’re going to develop a database, understand models using ActiveRecord, and dig a little deeper into Rails.  For now: happy hosting!

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Rails, Ruby , , , ,

The ASP.NET, Silverlight, PHP, Rails Experiment

October 27th, 2008

I’ve been working with Microsoft technologies for over ten years, specifically Microsoft’s web development technologies.  During that time I have built a variety of sites ranging in scope from e-commerce, educational, service provision, SaaS, to dashboards, portals, internal tools, and even SAP-migration.  While I praise the technology stack for what it allows me to do, it also comes with a whole host of limitations that make it hard for me to deliver the experience my clients would like.  Throughout this decade of web development I have heard a lot from those around me about alternative technology stacks that promise all manner of improvements and experiences.  Unfortunately there is a lot of resistance from any one technology stack to listen to and learn from the stacks around them, most of the cross-platform feedback comes in the form of “Microsoft sucks” or “PHP is for fan-boy script kiddies”.  The truth is that a large number of successful business are hosted on a wide variety of platforms.  Each technology stack has to at least be viable for that to be true.  The problem is getting at the truth without the zealous noise of “my stacks better than your stack” getting in the way.

I decided that it was time for me to branch out and become more informed on these technologies myself so that I could truly understand the differences and what made each of them unique.  I’m hoping that as part of this experience I can not only become a better developer but also learn the problems that Ruby on Rails or PHP addresses.  I’ll like to be able to speak from an informed standpoint about the differences between the Microsoft and open-source approaches as well as better understand the problems each of those development worlds faces on a daily basis.  Either way, it’s going to be a heck of a lot of fun.

The experiment I have in mind is to build the same web-site using four different technologies.  From the Microsoft camp I have chosen ASP.NET and Silverlight.  From the open-source perspective I have chosen PHP and Ruby on Rails.  I chose PHP and RoR because they are two technologies that I have always wanted to learn.  Learning both of those will also require some digging into Apache and Linux, another two areas that I have too little direct experience with to effectively participate in an informed conversation.

Our horses are ready to race.  In terms of hosting, I have selected DreamHost for the PHP and Rails sites, and I’m going to use StormHosts for the ASP.NET and Silverlight projects (assuming that SH can do .NET 3.5, which I believe I saw at some point).  The reason I’m using remote hosting services for this experiment is that I don’t believe you get the true experience of a technology stack until you host it in this way.  It is very easy to get a Rails site up and running using WEBrick and a local installation of Ruby.  Similarly, it is easy to get an ASP.NET site running on the personal web server that ships with Visual Studio 2008.

The first phase of the experiment is to get a “Hello World!” site up and running for each of the four environments.  The specifications are that a single end-point be accessible that displays the text “Hello World!” and that this end-point is accessible in both Internet Explorer 7 and FireFox 3.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

ASP.NET, PHP, Rails, Ruby, Silverlight , , , , ,