Using KnockoutJS with SignalR in ASP.NET MVC

KnockoutJS is a MVVM implementation for JavaScript written by Steve Sanderson, in my opinion the author of the best ASP.NET MVC textbooks available. Simply put it lets you bind a JavaScript object model to your HTML UI using a Read more

A MongoDB Tutorial using C# and ASP.NET MVC

In this post I'm going to create a simple ASP.NET MVC website for a simple blog that uses MongoDB and the offical 10gen C# driver. MongoDB is no NOSQL database that stores information as Binary JSON (BSON) in documents. I Read more

Linq To SQL Tutorial

Check out some of my other Linq to SQL posts: EntityBase Inheritance Modifiers with SQLMetal Linq to SQL with WCF Services Linq to SQL Framework (Repository/Business wrapper) ObjectDataSource binding with server side paging and sorting Load Options Generic Framework using reflection This is a basic tutorial for Read more

Show a JavaScript confirm dialog box after client validation

Posted on by Joe in ASP.NET, C#, JavaScript | 6 Comments

It’s quite common to use a JavaScript confirm dialog on a button press to ensure that the user wants to submit the page.  If you are using any of the ASP.NET validators that use client side validation you will find the confirm appears before the validation, whereas it would be better if the confirm box only appeared if the page was valid.

Luckily the framework supplies some JavaScript functions that can be used for validation.  Page_IsValid is a boolean indicating if the page is valid which can be used in client script.  This value is set when the JavaScript function Page_ClientValidate is executed.

For this example I have set CausesValidation to false on the button that will show the confirm dialog, as I will call the client side function myself.  If I don’t to this my validation will be called twice.  In the OnClientClick I then need to add some JavaScript to call Page_ClientValidate if the function exists, and then only show the confirm dialog if Page_IsValid is true:

<asp:LinkButton ID="btnSubmit"
                CausesValidation="false"
                OnClientClick="if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate(); if(Page_IsValid) { return confirm('You are sure?'); } };"
                runat="server"
                onclick="btnSubmit_Click">

Generate a CSV from a generic list of objects using reflection and extension methods

Posted on by Joe in ASP.NET, C# | 9 Comments

Download the source code for this post: ReflectionCSV.zip

Last week I wrote a post about generating a CSV from a DataTable. As I hardly use DataTables these days I thought it would be good to write a function that does this for a generic list of objects using reflection to get the properties of the object and export them.

In this example I have done this using an extension method on the generic list. This approach could also be easily applied to the DataTable example.

Read more

Show ‘Are you sure you want to navigate away from this page’ message like Hotmail

Posted on by Joe in ASP.NET, JavaScript | 2 Comments

If you start typing an email in Hotmail then navigate away without saving or sending it you get the following message:

OnBeforeUnload

This is done by using the onbeforeunload window event.  This event can be used to perform any processing needed before navigating to a new page, but if the event handler returns a string you get this confirmation dialog with your own string replacing “You haven’t sent this message. Are you sure you wan’t to discard it?“.  If you press OK then the navigation continues, and if you press Cancel then you remain on the same page.

Here is an example of how to use the event:

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function() { return "Your message here:"; }
</script>

This could come in useful if you had a form on your page, and you don’t want the user to accidentally navigate away from the page and loose what they have entered.

ObjectDataSource – Cannot convert value of parameter value from System.String to System.DateTime

Posted on by Joe in ASP.NET, C# | 8 Comments

One bug I’ve come across a few times and again just recently is when using an ObjectDataSource with a GridView to update dates.  When doing the update the ObjectDataSource always uses the en-US culture and not the culture defined for the application.

The bug has been acknowledged by Microsoft but never fixed.

If you are in the US then you’ll have no problems, but if you are using a culture that uses the dd/MM/yyyy date format such as the UK or Australia you data will display in the correct format on your page, but you will get the following error when you try to save:

Cannot convert value of parameter ‘value’ from ‘System.String’ to ‘System.DateTime’

Read more

Create a virtual directory in IIS using ASP.NET and C#

Posted on by Joe in ASP.NET, C# | Leave a comment

Update 30th July 2009: After deploying this to a development server there were a few tweaks I needed to make to get it working. I  have amended the post as necessary.

I needed to be able to create a virtual directory in IIS via my ASP.NET application.  I found this nice little example in VB.NET and converted it to C#.  You need to add a reference to System.DirectoryServices to use it.  The VB.NET example always puts the new virtual directory in the default website, so I have amended it to allow choosing the server and website you want to place the virtual directory under.


private void CreateVirtualDir(string serverName, string website, string appName, string path)
{
    DirectoryEntry IISSchema = new DirectoryEntry(string.Concat("IIS://", serverName, "/Schema/AppIsolated"));
    bool canCreate = IISSchema.Properties["Syntax"].Value.ToString().ToUpper() != "BOOLEAN";
    IISSchema.Dispose();

    //get the identifier for the site we want
    int identifier = 0;
    DirectoryEntry root = new DirectoryEntry(string.Concat("IIS://", serverName, "/W3SVC"));
    foreach(DirectoryEntry de in root.Children)
    {
        if (de.SchemaClassName.ToUpper().Equals("IISWEBSERVER") &&
            de.Invoke("Get", "ServerComment").ToString().ToUpper().Equals(website.ToUpper()))
        {
            identifier = Convert.ToInt32(de.Name);
            break;
        }
    }

    if (canCreate && identifier > 0)
    {
        bool pathCreated = false;
        try
        {
            DirectoryEntry iisAdmin = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/{1}/Root", serverName, identifier));

            //make sure folder exists
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
                pathCreated = true;
            }

            //If the virtual directory already exists then delete it
            foreach (DirectoryEntry vd in iisAdmin.Children)
            {
                if (vd.Name.Equals(appName))
                {
                    iisAdmin.Invoke("Delete", new string[] { vd.SchemaClassName, appName });
                    iisAdmin.CommitChanges();
                    break;
                }
            }

            //Create and setup new virtual directory
            DirectoryEntry vDir = iisAdmin.Children.Add(appName, "IIsWebVirtualDir");
            vDir.Properties["Path"][0] = path;
            vDir.Properties["AppFriendlyName"][0] = appName;
            vDir.Properties["EnableDirBrowsing"][0] = false;
            vDir.Properties["AccessRead"][0] = true;
            vDir.Properties["AccessExecute"][0] = true;
            vDir.Properties["AccessWrite"][0] = false;
            vDir.Properties["AccessScript"][0] = true;
            vDir.Properties["AuthNTLM"][0] = true;
            vDir.Properties["EnableDefaultDoc"][0] = true;
            vDir.Properties["DefaultDoc"][0] = "default.htm,default.aspx,default.asp";
            vDir.Properties["AspEnableParentPaths"][0] = true;
            vDir.CommitChanges();

            //the following are acceptable params
            //INPROC = 0
            //OUTPROC = 1
            //POOLED = 2
            vDir.Invoke("AppCreate", 1);
        }
        catch (Exception ex)
        {
            if (pathCreated)
            {
                System.IO.Directory.Delete(path);
            }

            throw ex;
        }
    }
    else
    {
        throw new ApplicationException("Failed to create Virtual Directory");
    }
}

To create a new virtual directory I can then call the method like this:

try
{
    CreateVirtualDir("localhost", "MyWebSite" "MyVirtualDirectory", @"c:\sites\mysite");
}
catch (Exception ex)
{
    lblMessage.Text = string.Concat("An error occurred: ", ex.Message);
}

When I deployed this to a development server I got an ‘Access is denied’ error on this following line:

vDir.CommitChanges();

This is because IIS administration need to be done by a user in the administrator group which is the ASPNET user is not.  To resolve this I created a new window user on the server which was a member of the administrator group.  I then added the following to my Web.config:

<system.web>
    <identity impersonate="true" userName="username" password="password" />
</system.web>

You could also wrap this in an pages element to restrict which pages will impersonate this identity.

How to create a CSV from a DataTable

Posted on by Joe in ASP.NET, C# | Leave a comment

In a project I’ve been working on I came across the need export a DataTable to CSV and this is how I did it.  I have split up the functionality as I also use them to concatenate several DataTables into one CSV.

I need to import for following namespaces in this example.

using System.Data.SqlClient;
using System.Text;

The first method gets the DataTable.  It could easily be changed to use stored procedures and add parameters.


private DataTable GetDataTable()
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM MyTable", con);
    DataTable dt = new DataTable();

    using (con)
    {
        da.Fill(dt);
    }

    return dt;
}

The next method creates the CSV using a StringBuilder.  First it creates the headings by looping through the DataTable’s Columns collection, then creates each row by iterating through the Rows.  I’m also checking for any commas in the value which would break the CSV, and putting the value in quotes which escapes the comma.  Finally it’s checking for any \r or \n characters and replacing them with a space.  There may well be other characters that break the CSV but for now this is fine for what I’m doing, although it is very simple  just to add extra conditions to the method to check for invalid characters.


public string GetCSV(DataTable dt)
{
    StringBuilder sb = new StringBuilder();

    //Line for column names
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append(dt.Columns[i]);

        if (i < dt.Columns.Count - 1)
        {
            sb.Append(",");
        }
    }

    sb.AppendLine();

    //Loop through table and create a line for each row
    foreach (DataRow dr in dt.Rows)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                string value = dr[i].ToString();

                //Check if the value contans a comma and place it in quotes if so
                if (value.Contains(","))
                {
                    value = string.Concat("\"", value, "\"");
                }

                //Replace any \r or \n special characters from a new line with a space
                if (value.Contains("\r"))
                {
                    value = value.Replace("\r", " ");
                }
                if (value.Contains("\n"))
                {
                    value = value.Replace("\n", " ");
                }

                sb.Append(value);
            }

            if (i < dt.Columns.Count - 1)
            {
                sb.Append(",");
            }
        }

        sb.AppendLine();
    }

    return sb.ToString();
}

Now we have the CSV as a string you could easily save it to a file, but I want to write it to the page’s HttpResponse so the user can download it in the browser.  To do this I have the following method.

private void ExportCSV(string csv, string filename)
{
    Response.Clear();
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.csv", filename));
    Response.ContentType = "text/csv";
    Response.AddHeader("Pragma", "public");
    Response.Write(csv);
    Response.End();
}

Now to put this all together I have a button click event like this:

protected void btnCreateCSV_Click(object sender, EventArgs e)
{
    try
    {
        string csv = GetCSV(GetDataTable());
        ExportCSV(csv, "MyCSV");
    }
    catch (System.Threading.ThreadAbortException)
    {
        //Thrown when calling Response.End in ExportCSV
    }
    catch(Exception ex)
    {
        lblMessage.Text = string.Concat("An error occurred: ", ex.Message);
    }
}

When using Response.End in a Try block as the ExportCSV does, a ThreadAbortException is thrown.  For this reason I handle this Exception first, then any other Exception which will be a true error. See here for more info.

Minimize any application to the System Tray

Posted on by Joe in Misc | 1 Comment

In my current job we use Lotus Notes…… enough said.  Anyway, I wanted it to minimize it to the System Tray as Outlook does but there doesn’t seem to be any option to do this.

I came across a freeware application called Tray It! which allows you to minimize any application to the system tray thus relieving much needed task bar space pretty cool!

Linq to SQL Tutorial – ObjectDataSource binding with paging and sorting

Posted on by Joe in C#, Linq | 4 Comments

Update: 31/10/2009 – Added source code

ASP.Net has the LinqDataSource which is a handy control but it embeds the business logic in the page which I don’t like. In this post am I going to use the repository objects I created in my last post to bind a GridView using an ObjectDataSource enabling filtering, sorting, and server side paging.

I have a GridView control with an ObjectDataSource as the object. Below are the properties for my ObjectDataSource:

<asp:ObjectDataSource
    ID="odsStudent"
    runat="server"
    TypeName="Repository.StudentRepository"
    DataObjectTypeName="Entities.Student"
    SelectMethod="GetAll"
    UpdateMethod="Save"
    DeleteMethod="Delete">
</asp:ObjectDataSource>

Here we have the following:

  • TypeName – The object, here this is the repository.
  • DataObjectTypeName – The entity, here this is Student. This tells the ObjectDataSource to pass an instance of Student when inserting, updating or deleting instead of the separate values.
  • SelectMethod – The method to load the data, here this is GetData from the base repository.
  • UpdateMethod – The method to update the data, here this is Save from the base repository.
  • DeleteMethod – The method to delete the data, here this is Delete from the base repository.

Running the application at this point would correctly load the data, but delete would not work and update would insert duplicate records. This is because Linq to SQL doesn’t know which entity to attach. To resolve this I can set the DataKeyNames property of the GridView to include the timestamp column:

DataKeyNames="ID, UpdateDate"

I talk more about timestamp columns in my Linq to SQL with WCF Services post.

Now that this property has been added updates and deletes work fine within the GridView. To add server side paging I need to modify my repository to create an overload for GetAll. In doing this I have also added a protected method in the base repository called PageFilter:

protected List<T> PageFilter(IQueryable<T> entities, int startRow, int maxRows)
{
    return entities.Skip(startRow).Take(maxRows).ToList();
}

This method return a List containing the rows from IQueryable between startRow and maxRows. My overloaded GetAll method accepts startRow and maxRows and uses the PageFilter method:

public List<T> GetAll(int startRow, int maxRows)
{
   return PageFilter(_context.GetTable<T>(), startRow, maxRows);
}

The reason for separating the PageFilter is for reuse within the base class, and derived classes which I will demonstrate later. Now that I have my new GetAll method I need to add some new properties on my ObjectDataSource:

SelectCountMethod="Count"
StartRowIndexParameterName="startRow"
MaximumRowsParameterName="maxRows"
EnablePaging="true"
  • SelectCountMethod – Used to determine the number of pages, here this is Count method in the base repository.
  • StartRowIndexParameterName – The name of the parameter for the start row index, this needs to match the name of the parameter in the overloaded GetAll method in the base repository.
  • MaximumRowsParameterName – The name of the parameter for the maximum rows, this needs to match the name of the parameter in the overloaded GetAll method in the base repository.
  • EnablePaging – This needs to be set to true to enable server side paging, otherwise the paging will still be done at the client.

Note: If you configure the ObjectDataSource through the UI and select the new GetAll method it will add parameters to the datasource. We don’t want this so select the parameterless overload or set up the ObjectDataSource in the markup.

When I run the application it now works using server side paging without really putting in too much work. Next I want to add sorting. To do this I need a new overloaded method for PageFilter and another one for GetAll which accepts the parameters for paging and sorting:


protected List<T> PageFilter(IQueryable<T> entities, int startRow, int maxRows, string orderBy)
{
    if (string.IsNullOrEmpty(orderBy))
    {
        orderBy = "ID";
    }

    return entities.OrderBy(orderBy).Skip(startRow).Take(maxRows).ToList();
}

You may notice I’m using the string variable orderBy as a parameter for the OrderBy method which would not usually be allowed. This is because I have included the Linq Dynamic Library in my project. Scott Guthrie has a post on this here. To use the new dynamic extension methods I have added the Dynamic.cs file to my project and added a reference to System.Linq.Dynamic. I am also checking if orderBy is null or empty and setting a default if so. This is because the dynamic library will throw an exception if it is passed an empty string. ID is fine to use as a default as I know all of my entities will have an ID property.

The new GetAll method looks like this:

public List<T> GetAll(int startRow, int maxRows, string orderBy)
{
    return PageFilter(_context.GetTable<T>(), startRow, maxRows, orderBy);
}

This method takes in the paging and sorting parameters and uses the new PageFilter method. Now the methods have been set up I need to set another property on the ObjectDataSource:

SortParameterName="orderBy"
  • SortParameterName – The parameter name in the select method that will be used for sorting, in this case orderBy.

Now I have binding, updating, deleting, sorting and server side paging all working nicely with very little code! Next I am going to add some simple filtering to filter the results on Forename and Surname. I have added the following to my page:

<fieldset>
    <legend>Search</legend>
    Forename: <asp:TextBox ID="txtSForename" runat="server" />
    Surname: <asp:TextBox ID="txtSSurname" runat="server" />
    <br />
    <asp:Button ID="btnSearch" Text="Search" runat="server" onclick="btnSearch_Click" />
    <asp:Button ID="btnClear" Text="Clear" runat="server" onclick="btnClear_Click" />
</fieldset>

The search button simply resets the GridView’s PageIndex so that it forces it to page 1 after a search, and the Clear button results the values in the TextBoxes:


protected void btnSearch_Click(object sender, EventArgs e)
{
    gvStudents.PageIndex = 0;
}

protected void btnClear_Click(object sender, EventArgs e)
{
    txtSForename.Text = string.Empty;
    txtSSurname.Text = string.Empty;
}

As the Search is student specific I need to add some new functionality to the student repository to handle the search. Firstly I have added a private method called StudentSearch which actually does the filtering and returns IQueryable<Student> accepting parameters for forename and surname:


private IQueryable<Student> StudentSearch(string forename, string surname)
{
    var query = from s in Context.Students
                select s;

    if (!string.IsNullOrEmpty(forename))
    {
        query = query.Where(s => s.Forename.Equals(forename));
    }

    if (!string.IsNullOrEmpty(surname))
    {
        query = query.Where(s => s.Surname.Equals(surname));
    }

    return query;
}

I have also added three different overloads for a public method called search. These all use the private StudentSearch method to handle filtering with no paging, with paging, and paging with sorting:


public List<Student> Search(string forename, string surname)
{
    return StudentSearch(forename, surname).ToList();
}

public List<Student> Search(string forename, string surname, int startRow, int maxRows)
{
    return PageFilter(StudentSearch(forename, surname), startRow, maxRows);
}

public List<Student> Search(string forename, string surname, int startRow, int maxRows, string orderBy)
{
    return PageFilter(StudentSearch(forename, surname), startRow, maxRows, orderBy);
}

I now need to change my ObjectDataSource’s SelectMethod to Search and add the SelectParameters for Forename and Surname:

<asp:ObjectDataSource
    ID="odsStudent"
    runat="server"
    TypeName="Repository.StudentRepository"
    DataObjectTypeName="Entities.Student"
    SelectMethod="Search"
    UpdateMethod="Save"
    DeleteMethod="Delete"
    SelectCountMethod="Count"
    StartRowIndexParameterName="startRow"
    MaximumRowsParameterName="maxRows"
    SortParameterName="orderBy"
    EnablePaging="true">
    <SelectParameters>
        <asp:ControlParameter ControlID="txtSForename" DbType="String" Name="forename" />
        <asp:ControlParameter ControlID="txtSSurname" DbType="String" Name="surname" />
     </SelectParameters>
</asp:ObjectDataSource>

Running the application now throws the following error:

ObjectDataSource ‘odsStudent’ could not find a non-generic method ‘Count’ that has parameters: forename, surname.

This is because the ObjectDataSource is now expecting a Count method with forename and surname parameters to get the number of filtered records. To overcome this I have added a Count method to the student repository which takes in this arguments and uses the StudentSearch method to return the number of records:

public int Count(string forename, string surname)
{
    return StudentSearch(forename, surname).Count();
}

Now everything works! Updating, deleting, server side paging, ordering and filtering witch very little code at the page level. I am sure I will come up with a more generic way to perform filtering but for now this way is fairly straight forward and doesn’t require too much code to implement.

Linq to SQL Tutorial – Base Repository/Business Logic wrapper

Posted on by Joe in C#, Linq | 2 Comments

Before Linq to SQL I always separated out my Entities, Data Access Layer and Business Logic Layer.  With Linq to SQL it’s a little different as I feel the generated classes are kind of like the Entity and Data Access Layer combined.  Rather than using the generated entities directly it is still good practice to have a Business Logic Layer.  In this example I am using the term Repository which is an aspect of Domain-Driven Design.

Each entity will likely need it’s own repository object, as there will business logic that is specific for that entity, but there will be logic that is shared between all entities so it is worth creating a base object for this.

I have created a generic abstract class called RepositoryBase which has a constraint for EntityBase which is the base entity class I created in my Set inheritance modifiers with SQLMetalpost.  This ensures that the repositories can only be used with the objects created by Linq to SQL.

To handle my DataContext I am creating an instance of it in the constructor and keeping this instance for the life of the object.  For this reason my base repository implements IDisposable to handle disposing the DataContext.

Here is the code for my base repository:


public abstract class RepositoryBase&lt;T&gt; : IDisposable where T : EntityBase
{
    private UniversityDataContext _context;

    public RepositoryBase()
    {
        _context = new UniversityDataContext(ConfigurationManager.ConnectionStrings[&quot;UniversityConnectionString&quot;].ConnectionString);
    }

    public UniversityDataContext Context
    {
        get
        {
            return _context;
        }
    }

    public List&lt;T&gt; GetAll()
    {
        return _context.GetTable&lt;T&gt;().ToList();
    }
    public T GetByID(int id)
    {
        return _context.GetTable&lt;T&gt;().FirstOrDefault(e =&gt; e.ID.Equals(id));
    }

    public int Count()
    {
        return _context.GetTable&lt;T&gt;().Count();
    }

    public void Save(T entity)
    {
        if (entity.IsNew)
        {
            _context.GetTable&lt;T&gt;().InsertOnSubmit(entity);
        }
        else
        {
            _context.GetTable&lt;T&gt;().Attach(entity, true);
        }

        _context.SubmitChanges();
    }

    public void Delete(T entity)
    {
        if (!entity.IsNew)
        {
            _context.GetTable&lt;T&gt;().Attach(entity);
            _context.GetTable&lt;T&gt;().DeleteOnSubmit(entity);
            _context.SubmitChanges();
        }
    }

    public void Dispose()
    {
        if (_context != null)
        {
            _context.Dispose();
        }
    }
}

You can see it contains methods that are relevant for all entities.  A method to get all entities, a method to get all entities by ID which I can do due to ID being a virtual member in my EntityBase class which is overridden by each entity.  It also has generic methods for saving and deleting which will work for any of the entities.  There will be a lot more logic that could go into this base class, but for now this just shows the basics.

Using this class you can derive separate repositories for each entity. I have a public property for the Context which allows any derived classes to use the DataContext instance.  Here is my implementation for StudentRepository which adds a couple of student specific methods:


public class StudentRepository : RepositoryBase&lt;Student&gt;
{
    public List&lt;Student&gt; GetByForename(string forename)
    {
        return Context.Students.Where(s =&gt; s.Forename.Equals(forename, StringComparison.CurrentCultureIgnoreCase)).ToList();
    }

    public List&lt;Student&gt; GetBySurname(string surname)
     {
        return Context.Students.Where(s =&gt; s.Surname.Equals(surname, StringComparison.CurrentCultureIgnoreCase)).ToList();
    }
}

Using this derived class I could use any of the base methods:

StudentRepository rep = new StudentRepository();
Student s = rep.GetByID(1);
s.Forename = &quot;Joseph&quot;;
rep.Save(s);
gvStudents.DataSource = new StudentRepository().GetAll();
gvStudents.DataBind();

I could also use any of the entity specific methods:

StudentRepository rep = new StudentRepository();
List&lt;Student&gt; students = rep.GetByForename(&quot;Joseph&quot;);
foreach (Student s in students)
{
    rep.Delete(s);
}

To explicitly dispose of the object and the underlying DataContext I could do the following:

using (StudentRepository rep = new StudentRepository())
{
    List&lt;Student&gt; students = rep.GetByForename(&quot;Joseph&quot;);
    foreach (Student s in students)
    {
        rep.Delete(s);
    }
}

Move wordpress.com blog to other hosting provider

Posted on by Joe in Personal | Leave a comment

Yesterday I moved my blog from wordpress.com to my own hosting provider giving me greater control over my blog. This was quite an easy process but thought I would document the steps I took here incase it helps anyone else.

Firstly I installed wordpress on my new host. I then used the Import and Export options in Tools to import all my posts, categories, images etc into my new blog. I then opened up the SQL Admin tool provided by my host and ran some update queries to update any links and image references to use my own domain instead of the wordpress.com domain.

At this point the blog was running but was using the default theme so I downloaded the theme I was using on wordpress.com and installed it.

Now everything looked okay apart from my source code samples. I tried quite a few plugins that provide source code markup but I really wanted to find the one wordpress.com used as I liked the format it used, and I didn’t want to have to replace all my source code tags to use those of another plugin. After a bit of hunting around I found SyntaxHighlighter Evolved, which looks to be an updated version of the plugin wordpress.com uses.  After installing it all my source code example worked without having to update the tags, whoop!

Something else I liked on wordpress.com was the stats plugin they have, which uses Open Flash Chart written by my brother-in-law.  Doing a quick Google search brought up the wordpress.com Stats plugin.  It requires a wordpress.com API key but as I’m moving from wordpress.com that’s not a problem.  When activating the plugin it asks for the API key which can be found on the account page of wordpress.com.  It then asks you to confirm you want to link the new blog to the wordpress.com account.

Now my blog looks and works pretty much like my wordpress.com one, but they are two separate blogs which I don’t want.  What I really wanted to be able to do was forward all the posts on the old blog to the new blog as I didn’t want google search results going through the old one.  I found this post which has a handy tutorial on how this can be done.  It requires switching your name servers to the wordpress.com ones and adding your domain via the wordpress.com admin panel, costing you USD10.  Once that is done you can set your new domain to be the primary domain for the blog, then switch the name servers back and voila, the old blog redirects to the new one.

All in all this was quite painless, I’m now on the hunt for a decent theme!