Blog Setup

Posted by Jack Altiere on April 12th, 2010

I have been trying different combinations of tools / plugins for my blog, and now that I’m finally happy with the setup I have I thought I’d share how I’m doing things.

First, I host my own instance of WordPress to handle the site.  There are several different blog engines available, but WordPress is the only one that I have any real experience with.  It meets all of my requirements for a blog engine.

  1. There are a lot of free templates available.  This is important to me, because I’d like to have a decent looking site and I’m by not a good graphic artist.
  2. It’s easy to update.  WordPress used to be a pain to upgrade, but now it is very easy.  You can upgrade to a new version with the click of a link from the administrative interface.
  3. There are plenty of nice third party plugins and widgets available.  I want to focus on writing content, not playing around with my website.
  4. It’s written in PHP, so it’s easy to get in there and modify stuff if I absolutely have to.

Next, I publish all of my content with Windows Live Writer.  This tool is simple, and it integrates well with WordPress.  It does have one quirk that I had to get around however.  I want to be able to edit content from more than 1 computer, and I don’t want to have to carry around a USB drive to accomplish this.  To solve the first part of the problem, I’m using Live Mesh.  With this, you can set up folders that are shared across as many PC’s as you want to.  You get 5 GB of space for free, and it’s a snap to install.  I installed Mesh on the computers I would potentially be writing content with, and then I created a Mesh folder called My Weblog Posts.  In this folder I have a Drafts folder and a Recent Posts folder.  This is important, because it addresses the pain point I have with Live Writer.

In Live Writer, you can’t specify where you want your drafts to be saved.  By default drafts get saved to Documents / My Weblog Posts / Drafts.  What I did was delete this directory after installing Live Writer.  Then I created a symbolic link to the directory I set up in Mesh, which ends up sitting on my Desktop with instructions found here.  I’ve done this on both Windows  7 and Vista machines.  Make sure you run cmd.exe as an Administrator so you have sufficient privileges to create the link.  So when I’m done, my Documents directory has a link to my Mesh folder structure to save Drafts, as seen by the icon next to the folder below.

symlink

I give credit to Justin Etheridge for this idea, this came out of a conversation we had at the Mix 10 conference last month.  I don’t remember exactly how he does it, but our conversation inspired my new setup.

Another thing that I have changed around a lot is my code syntax highlighter.  I finally settled on using a product called (strangely enough) SyntaxHighlighter.  If you are reading my blog on an aggregator such as Google Reader you are missing out, but this is what the code looks like on my actual site:

syntax

This tool does a fantastic job, and it supports a lot of different languages.  To make this even easier to use, I found a WordPress plugin called SyntaxHighlighter Evolved that automatically puts the required Javascript calls in my theme so I don’t have to edit my template by hand.  I also use a Live Writer plugin called PreCode that allows me to copy and paste stuff directly into Live Writer and be formatted with the correct “pre” tags for the language I’m pasting.  It fixed indentation with the click of a button, which is helpful since I often don’t include the namespace information, etc. when posting fragments.  It also allows you to choose what the target language is from a drop down list.  This has made pasting code snippets a breeze, I wish I would have stumbled across this sooner.

For image editing, I use Paint.Net.  If you aren’t already using this tool I highly recommend it.  It’s everything that Paint SHOULD be.

Lastly, I use Google Analytics to look at how traffic to my site is looking.  They added a new feature called Intelligence that allows you to set up custom daily, weekly, and monthly alerts.  This allows you to get email if certain criteria happen.  For example, you can set up daily alerts to let you know that you got 50 new visitors, or that you got 500 visits, or that someone reached your site by using the keyword jquery in a search 10 times.  It really is a cool feature, and they have a few pre-canned alerts you can use to get you started.

That’s my setup.  I’m able to edit drafts on any of my PC’s and I finally have a syntax highlighting product that I’m happy with.  One thing I should point out, my method of sharing drafts should only be used for drafts.  I think that this would break down if you tried to edit posts that are already published from a different PC because of how Live Writer generates an ID for each post.

JQuery delegates

Posted by Jack Altiere on April 8th, 2010

I’ve had a few projects where I needed to update information on a site at a regular interval, and it’s always a better user experience if you do it asynchronously.    I always like to come up with a functional example, so I’m going to write a quick MVC page that displays all the images in a directory.  The catch is that I want add any pictures to the page that are added to this directory without having to refresh the page.   Another thing I’d like to do is use the data capabilities in JQuery to store additional information about each image.

First I wanted to create a class to hold the additional data so that I can make a strongly typed view with it.  This is what I came up with:

[Serializable]
public class UploadedImage
{
    public int Id { get; set; }
    public string ImageName { get; set; }
    public string ImagePath { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
}


After creating my class, I created my strongly typed view to accept a List<UploadedImage>.  The next step was to add the controller method to display the view.  In this method, I wanted to load the initial list of images present in the directory and pass them to the view.

public ActionResult Timer()
{
    var photos = new List<UploadedImage>();
    var dir = new DirectoryInfo(ConfigurationParser.GetAppSettingString("PhotoDirectory"));
    var counter = 1;
    foreach (var file in dir.GetFiles())
    {
        var img = Image.FromFile(file.FullName);
        var photo = new UploadedImage
                        {
                            Id = counter,
                            ImageName = file.Name,
                            ImagePath = string.Format("../../Content/Images/Photos/{0}", file.Name),
                            Height = img.Height,
                            Width = img.Width
                        };
        photos.Add(photo);
        counter ++;
    }

    ViewData.Model = photos;
    return View();
}


This is pretty self explanatory, I just loaded the photos from the directory, gathered some information about them, and assigned each an arbitrary ID.  The last step was to put them all in a list and pass them to the view.

Since the focus of this exercise is JQuery, the bulk of our work is going to take place in the view.  I’m not doing anything complicated to display the images.  All I”m doing is using an unordered list to display all of the thumbnails, and creating a div that I will use to display additional information about the image in a pop-up when it is clicked.

<h2>JQuery Delegate Example</h2>

    <ul class="thumbnails">
        <% foreach (var item in Model) { %>
        <li><a href="#"><img id="img<%= item.Id %>" src="<%=Html.Encode(item.ImagePath) %>" alt="" /></a></li>
        <% } %>
    </ul>

    <div id="popupContact">
    <a id="popupContactClose">x</a>
    <span id="imgName"></span>
    <p id="contactArea">  

    </p>
</div>
<div id="backgroundPopup"></div>  


That leaves us with the client code.  The first obstacle we have to overcome is that we need a way to monitor the photo directory to figure out when new images are added.  I ended up using a JQuery plugin I found called doTimeout that works really well.  This sets up the framework for the polling operation, to close the loop I created a web service to pass back the list of images in the directory.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<UploadedImage> LoadImages()
{
    var photos = new List<UploadedImage>();
    var dir = new DirectoryInfo(ConfigurationParser.GetAppSettingString("PhotoDirectory"));
    foreach (var file in dir.GetFiles())
    {
        var img = Image.FromFile(file.FullName);
        var photo = new UploadedImage
        {
            ImageName = file.Name,
            ImagePath = string.Format("../../Content/Images/Photos/{0}", file.Name),
            Height = img.Height,
            Width = img.Width
        };
        photos.Add(photo);
    }

    return photos;
}


This method is in my .asmx web service.  The important thing to point out is that I specified that the response was going to be in JSON.  I can just return my List<UploadedImage> type, and it will be automatically be put into JSON where my client code can access it.

Before I worry about setting up the timer, I want to be able to attach data from the controller to my JSON objects.  My reasoning for this is because I don’t want to have to use unnecessary web service calls to retrieve this information if I already have it.  The reason I want to collect this data is that I want to display it in the pop up when someone clicks on an image.  To do this, I am going to use the jQuery.data() method.  When I wrote this code, it felt a little clunky, so if anyone has an idea for a better way to accomplish this leave me a comment.

var images = new Array();

$(document).ready(function() {
    // This is messy, I wonder if there is a better way to do this?
    <% foreach (var item in Model) { %>
        images[images.length] = "<%= item.ImageName %>";
        $("#img<%= item.Id %>").data('info', {
                Id: <%= item.Id %>,
                Name: "<%= item.ImageName %>",
                Width: <%= item.Width %>,
                Height: <%= item.Height %>
        });
    <% } %>
});


In addition to setting my data information, I’m populating an array that I had set up to keep track of what images are already displayed.  It’s easy to go off down a rabbit hole when you are coming up with an example, so rather than do it the right way and only bringing back images that were uploaded since the last time I checked, I’m just pulling  them all back for simplicity’s sake and adding ones that aren’t there yet.  The other thing I added that isn’t shown here is some code to display my pop up.  

The next thing to do is to set up the loop and poll the directory for new images, and then display any images that were added.

// Load the photos every 10 seconds.
$.doTimeout('tmrPhotoSearch', 10000, function() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "../DataService.asmx/LoadImages",
        data: "{}",
        dataType: "json",
        success: function(result) {
            ProcessImages(result.d);
        }
    });
    return true;
});

function ProcessImages(result)
{
    var max = 0;
    var data;
    $(".thumbnails a img").each(function() {
        data = $(this).data('info');
        if (data) {
            if (data.Id > max)
                max = data.Id
        }
    });
    max++;

    var item = '';
    var id = 0;
    $.each(result, function(key, value) { 

        if (jQuery.inArray(value.ImageName, images) == -1) {
            item = "<li><a href='#'><img id='img" + max + "' src='" + value.ImagePath + "' alt='' /></a></li>";
            $(".thumbnails").append(item);

            images[images.length] = value.ImageName;

            id = "#img" + max;
            $(id).data('info', {
                    Id: max,
                    Name: value.ImageName,
                    Width: value.Width,
                    Height: value.Height
            }); 

            max++;
        }
    });
}  

One thing about the web service call I should point out, be sure to include an empty data parameter if you don’t have any parameters.  If you don’t, the content-length header won’t be generated and you could run into problems.  Notice that my service is looking for a JSON result back, and on success it’s calling my ProcessImages method, passing in the web service response.   The first part of my processing method is hokey, it’s just figuring out what the max ID is that already exists and adding 1 to it.  I would definitely not do it this way for a real app, and I would certainly have more error handling built in.  With JQuery, I’m able to loop through the results directly with the .each method since my JSON has already been translated.  All I do is check each image, and add any that are not already present dynamically to the DOM at the end of the list with the append method.  I also update my array to put the new image in there so it’s not added more than 1 time, and I add all the meta data using the .data method like before.

The last bit of logic is to set up my event for displaying the pop up when an image is clicked.  I added this to my $(document).ready function to attach the click event.  I’m also retrieving the information from the JQuery cache about the clicked image and showing it in the popup.

$(".thumbnails a img").click(function() {
    var data = $(this).data('info');
    var html = "<b>" + data.Name + "</b><br/><br/>"
             + "<i>ID: " + data.Id + "</i><br/>"
             + "<i>Height: " + data.Height + "</i><br/>"
             + "<i>Width: " + data.Width + "</i><br/>";
    $("#imgName").html(html);
    loadPopup();
});

After putting a few sample images in my photo folder and running this, you can see that it grabs the 3 images that are there and shows them.

3photos

We can also see that clicking on one of these images successfully brings up our popup window with the attributes we put in the JQuery cache.

popup

The next thing to do is make sure that the timer is running.  The best way to do that in my opinion is with Firebug.  Firebug is a tremendous tool, and a great way to learn JQuery quickly. Using the “Net” tab, I can watch my asynchronous requests being sent off to the web service.

firebug

Now I’m going to keep the page up and drop an image into the directory.   You can see below that the image was added successfully to the page, but we have a problem.

4photos

When we click the new image, our pop up doesn’t work.  Although it took a little while to get here, this is actually the point of my example.  The problem is with our click event on the images.  When the event was wired up, the 4th image didn’t exist yet, so it obviously wasn’t selected by the JQuery selector statement, therefore no event gets attached to it. 

The solution to this problem is the JQuery delegate method.  Basically what this is doing is attaching the event to a parent DOM element, so any future elements that fit the selector that you add automatically get the event attached.  To get this to work, all we have to do is change our click event to look like this:

$(".thumbnails").delegate("a img", "click", function() {
    var data = $(this).data('info');
    var html = "<b>" + data.Name + "</b><br/><br/>"
             + "<i>ID: " + data.Id + "</i><br/>"
             + "<i>Height: " + data.Height + "</i><br/>"
             + "<i>Width: " + data.Width + "</i><br/>";
    $("#imgName").html(html);
    loadPopup();
});


After this change, I removed the 4th image from the directory and ran the page again. This time when I added the 4th image and clicked it, the popup appeared like we expected it to.

popup4

There are a few things I’d like to point out before wrapping up.  First, the delegate method is only available in JQuery 1.4.2 and later.  I think the version of JQuery that came with my MVC install was 1.4.1, so keep this in mind if you have a problem.  In fact, probably the best way to get JQuery is through a content delivery network. (I use the minified version specified here) The other thing that I’d like to point out is that the same capability is available in the JQuery .live method.  This method was introduced in version 1.3 of JQuery.  The difference is that the delegate method allows you to bind to a specific DOM element, where the live method binds to the root of the DOM tree.  This makes the delegate method faster, since it doesn’t have to bubble up as far.

kick it on DotNetKicks.com


Copyright © 2007 Jack Altiere. All rights reserved.