mynameiscoffey

Browsing: / Home
Shortlink

Why I love distributed source control systems

By mynameiscoffey on 2011-09-14 in Uncategorized

Lets say you’re humming along one day and you realize, oh crap, one piece of hardware or network infrastructure related to my source control system goes down, what does that mean to me?

  • You’re on Git — You can still view history, merge, branch, checkout, checkin and sync with your peers for items you are working on together, only remote origin is down.
  • You’re on SVN — You cannot view history, merge, branch, checkout, checkin or sync, but you can at least still work on whatever local copies you have and they will commit without any more hassle than usual once your SVN server comes back online.
  • You’re on TFS — Go home. Visual Studio won’t let you edit files unless it can talk to TFS, and God help you if you try having 20 people work on those files directly on the file system and try to commit them later; without an accord being signed between Visual Studio and TFS it will likely be treated as an act of war.

Oh snap, server is totally dead, now what?

  • You’re on Git — No big deal, someone just copies their repo to a new location, everyone repoints their repo to it and everyone goes on merrily.
  • You’re on SVN — Hope we have a backup, otherwise, damn, we lost all of our history and we can only recover whatever someone had checked out at the time. This is going to take a while to sort out.
  • You’re on TFS — If you don’t have a backup, at least you have eachother.
Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

28.days.later – Rails-style date helpers in .Net

By mynameiscoffey on 2011-07-19 in Uncategorized

When reading some articles about what makes Ruby (and Rails) "elegant" and "beautiful" the following line of code was used to demonstrate the power and flexibility of Ruby.

7.days.ago

As you might imagine, this nugget will return a date time object from a week ago. This might look like voodoo magic at first glance but lets take a closer look at what is going on and better yet how we can produce something similar in C#.

What this would look like in C# would be:

7.Days().Ago();

Parens are optional (and often omitted) in Ruby, so these two code samples are really identical. So how can we express this in C#? Lets break it down.

It appears that there is some kind of method chaining going on, so lets look at the first method call:

7.Days()

This looks like some kind of method called Days being called on the integer 7, on its own this should denotate some kind of time span.

public static class RailsDates
{
    public static TimeSpan Days(this int i)
    {
        return new TimeSpan(days: i, hours: 0, minutes: 0, seconds: 0, milliseconds: 0);
    }

    public static TimeSpan Day(this int i)
    {
        return Days(i);
    }
}

The Day() method allows us to make a call to 1.Day() as well, since 1.Days() sounds strange.

Now that we have a TimeSpan, we need to be able to say, that many days ago, and get the appropriate DateTime object back.

public static class RailsDates
{
    // ...

    public static DateTime Ago(this TimeSpan ts)
    {
        return DateTime.Now.Subtract(ts);
    }
}

Thats it! Now we have Rails-style dates in C# and at the same time gain some insight into how Rails is handling what initially may have looked like voodoo. Full helper below for multiple time spans and the ability to say 7.Days().Ago() as well as 2.Weeks().FromNow().

public static class RubyDates
{
    public static TimeSpan Weeks(this int i)
    {
        return new TimeSpan(days: (i * 7), hours: 0, minutes: 0, seconds: 0, milliseconds: 0);
    }

    public static TimeSpan Week(this int i)
    {
        return Weeks(i);
    }

    public static TimeSpan Days(this int i)
    {
        return new TimeSpan(days: i, hours: 0, minutes: 0, seconds: 0, milliseconds: 0);
    }

    public static TimeSpan Day(this int i)
    {
        return Days(i);
    }

    public static TimeSpan Hours(this int i)
    {
        return new TimeSpan(days: 0, hours: i, minutes: 0, seconds: 0, milliseconds: 0);
    }

    public static TimeSpan Hour(this int i)
    {
        return Hours(i);
    }

    public static TimeSpan Minutes(this int i)
    {
        return new TimeSpan(days: 0, hours: 0, minutes: i, seconds: 0, milliseconds: 0);
    }

    public static TimeSpan Minute(this int i)
    {
        return Minutes(i);
    }

    public static TimeSpan Seconds(this int i)
    {
        return new TimeSpan(days: 0, hours: 0, minutes: 0, seconds: i, milliseconds: 0);
    }

    public static TimeSpan Second(this int i)
    {
        return Seconds(i);
    }

    public static TimeSpan Milliseconds(this int i)
    {
        return new TimeSpan(days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: i);
    }

    public static TimeSpan Millisecond(this int i)
    {
        return Milliseconds(i);
    }

    public static DateTime Ago(this TimeSpan ts)
    {
        return DateTime.Now.Subtract(ts);
    }

    public static DateTime FromNow(this TimeSpan ts)
    {
        return DateTime.Now.Add(ts);
    }
}
Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Resolving a phantom namespace issue in a Windows WPF Application

By mynameiscoffey on 2011-06-03 in .Net Development

Recently a friend of mine was asking for help with an issue where he was getting a namespace error when trying to compile his WPF application.

The type or namespace name ‘Utilities’ could not be found (are you missing a using directive or an assembly reference?)

I’ve seen this many times before, we all have, and figured he probably was just looking at the problem too long and it was just a simple case of not setting up a reference somewhere.

I got the solution and took a look, basically a WPF application with a couple libraries under the same solution. One of them was acting like it wasn’t set up as a reference, however it clearly was there! After screwing with it for much longer than I care to admit, I decided to try things that didn’t make sense, since the situation wasn’t making any sense. I decided to try switching the framework over from .NET 4 to .NET 4 Client Profile, since that is what the WPF application runs under. It broke a little further since there was one class inside the Utility project referencing System.Web that wasn’t being used in this project, so I excluded it and hit build.

Much to my surprise, it worked!

It didn’t make much sense, I’ve built WPF projects before without having to explicitly specify Client Profile on the external libraries… so I changed the project back to .Net 4 (no Client Profile) and it still compiled!

It seems like if there is anything in the project that would prevent it from being compiled under the Client Profile, it will not be referenceable within the WPF application. While this makes perfect sense, since the WPF app needs to be able to run under the Client Profile, the error message presented doesn’t really help a whole lot.

So in summary, if you have an application running under Client Profile that can’t reference a project properly, it is because it cannot work under Client Profile. Changing your referenced project to Client Profile will help you find the problematic code.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

TryParse with default values

By mynameiscoffey on 2011-04-02 in .Net Development

Often I find myself writing parsing logic to convert a string to some kind of number, such as something coming in from a source I can’t control. Generally I end up with a block of code such as:

int someValue;
if(! Int32.TryParse(someString, out someValue))
{
    // some default value
    someValue = 42;
}

This bugs me because most of the time all I care about is if the value is parsable, and if not, just to assign some default value. Here is a quick helper that allows you to shorten the above to the following:

int someValue = TryParseWithDefault.ToInt32(someString, 42);

Just include the following:

public static class TryParseWithDefault
{
    public static Int16 ToInt16(string valueToParse, Int16 defaultValue)
    {
        Int16 returnValue;
        if (!Int16.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static Int32 ToInt32(string valueToParse, Int32 defaultValue)
    {
        Int32 returnValue;
        if (!Int32.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static Int64 ToInt64(string valueToParse, Int64 defaultValue)
    {
        Int64 returnValue;
        if (!Int64.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static UInt16 ToUInt16(string valueToParse, UInt16 defaultValue)
    {
        UInt16 returnValue;
        if (!UInt16.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static UInt32 ToUInt32(string valueToParse, UInt32 defaultValue)
    {
        UInt32 returnValue;
        if (!UInt32.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static UInt64 ToUInt64(string valueToParse, UInt64 defaultValue)
    {
        UInt64 returnValue;
        if (!UInt64.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static Single ToSingle(string valueToParse, Single defaultValue)
    {
        Single returnValue;
        if (!Single.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static Double ToDouble(string valueToParse, Double defaultValue)
    {
        Double returnValue;
        if (!Double.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static Decimal ToDecimal(string valueToParse, Decimal defaultValue)
    {
        Decimal returnValue;
        if (!Decimal.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static Byte ToByte(string valueToParse, Byte defaultValue)
    {
        Byte returnValue;
        if (!Byte.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }

    public static SByte ToSByte(string valueToParse, SByte defaultValue)
    {
        SByte returnValue;
        if (!SByte.TryParse(valueToParse, out returnValue))
            returnValue = defaultValue;
        return returnValue;
    }
}
Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

SEO-Friendly URLs in Ruby on Rails

By mynameiscoffey on 2011-02-27 in Ruby on Rails Development

Recently I wrote about implementing SEO Friendly URLs in ASP.Net MVC and thought I’d take a stab at porting it over to Ruby on Rails.

For this example we’ll be using the same scenario, we have a movie reviews site where we want our movies to have a more descriptive URL such as:

http://example.com/movie/1/star-trek

There are already a ton of tutorials out there for handling this in Rails but everything I looked at formatted it like this:

http://example.com/movie/1-star-trek

While this might not seem like that big of a difference, only one character, it brings with it some problems to keep in mind. First, you have the problem of looking up data: you either have to parse that string apart to find the ID so you can look up records, or you have to look your records up based on some ruby function that combines the ID and SEO-friendly portion, meaning you aren’t getting efficient queries as you have to bring your entire table back to do the lookup in memory. The second issue I have with the above is unless you are doing the first option for looking up records, you run into issues when you need to change the SEO-friendly portion of that URL, it breaks any existing links and search engine ranking your page has, unless you now maintain a history of all URLs that have existed ever and look up in that table when you can’t find a record. You also lose the discoverability and hackability of the URL, where I may know I need ID 42 but I don’t know the SEO-friendly portion. For these reasons I’m going to show an alternative approach similar to my ASP.Net MVC example.

Like in our ASP.Net MVC example, we want to make it so that hitting incorrect URLs (where the ID is correct but the SEO-friendly movie title is not) ww issue a 301 to the correct location to preserve legacy links and search engine ranking when we change, say, “Star Trek” to “Star Trek: The Motion Picture”, and allow our URLs to be discoverable and hackable since changing the ID also automatically fixes the SEO-friendly name for our user.

http://example.com/movie/1/star-trek-the-motion-picture

First we will start off by adding the following method to our Movie model:

def seo_name
  self.name.gsub(/'/m, "").parameterize
end

Rails’ built in parameterize method handles this conversion for us, however it isn’t perfect, so I added the removal of apostrophies before running it to prevent problems where something like “Ocean’s Eleven” would become “ocean-s-eleven” with only Rails’ built in parameterize method, and I would prefer “oceans-eleven” by default.

Next we need to get a route to handle this new URL design:

#config/routes.rb
match 'movie/:id(/:seo_name)' => 'movie#show', :as => :named_movie

Now that we have a special route to use, we can make our controller automatically redirect to the correct SEO-friendly URL if it is not supplied or supplied incorrectly. Now since we may have already existing functionality in place, such as xml or json functionality we want to preserve, we only want our logic to affect html rendering only.

def show
  @movie = Movie.find(params[:id])

  respond_to do |format|
    format.html {
      unless params[:seo_name] == @movie.seo_name
        head :moved_permanently, :location => named_movie_url(:id => @movie.id, :seo_name => @movie.seo_name)
      else
        render
      end
    }
    format.xml  { render :x ml => @movie }
  end
end

Excellent! Now our controller is automatically correcting requests to use the SEO-friendly URL! To reference this route with link_to so you don’t throw a 301 every time someone clicks something on your site, you can use:

<%= link_to @movie.name, named_movie_url(:id => @movie.id, :seo_name => @movie.seo_name) %>

Thats it! Now we have SEO-friendly URLs that don’t require us to parse apart a string to find the ID or use an inefficient look-up method in our data access!

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

SEO-Friendly URLs in ASP.Net MVC

By mynameiscoffey on 2010-12-19 in .Net Development, Uncategorized

SEO Friendly URLs are something that are becoming quite commonplace these days, but making these SEO Friendly URLs might not be obvious at first.

I’d like to walk you through a solution I used.

For this example imagine we have a movie review site, where our visitors might want to view various movies and things you have to say about them. Typically a URL for a movie might look like this:

http://mysite.com/movies/details/1

Personally I’m a fan of cleaner, more RESTful routes such as this:

http://mysite.com/movies/1

Either way, these aren’t very descriptive to our users or search engines. What would be great would be able to see something like this:

http://mysite.com/movies/1/star-wars

What would be best, would be if we could make it so we can hit movies/1 and it could automatically redirect us to whatever the correct SEO-friendly version is, that way if we later decide to change the title of our movie from Star Wars to say, Star Wars: A New Hope, we could have all our old links work and maintain our search ranking:

http://mysite.com/movies/1/star-wars-a-new-hope

First we will start off with something to determine the correct SEO-friendly version of each movie title:

public static string SeoName(string name)
{
    return Regex.Replace(name.ToLower().Replace(@"'", String.Empty), @"[^\w]+", "-");
}

This will put the name to lower case, and replace non-alphanumeric characters with dashes. It is smart enough to take multiple non-alphanumeric characters in a row and reduce them to a single dash (for example, the colon space above between Star Wars and A New Hope should be one dash, not two). The replace for single quote is to prevent problems where something like Weekend at Bernie’s becomes weekend-at-bernie-s but instead properly weekend-at-bernies.

Next we need to get our routes prepared for our new proposed URL design:

// Global.asax.cs
routes.MapRoute(
    "NamedMovie",
    "Movie/{id}/{seoName}",
    new { controller = "Movie", action = "Details", seoName = "" },
    new { id = @"^\d+$" }
);

Next up we’re going to alter our Details action to have the additional seoName parameter and add some logic to verify the request is coming in against the proper SEO-friendly version, and if not, issue a 301 (moved permanently) redirect to the correctly formatted URL.

public ActionResult Details(int id, string seoName)
{
    Movie movie = (from m in _entities.Movies
                         where m.Id == id
                         select m).FirstOrDefault();

    // Redirect to proper name
    if (seoName != SeoName(movie.Name))
        return RedirectToActionPermanent("Details", new { id = id, seoName = SeoName(movie.Name) });

    return View(movie);
}

That’s it!! Now our movie review application will correctly append the SEO-Friendly title if not provided or provided incorrectly and gives us the flexibility to change this value in the future without worrying about alienating existing links or search engine ranking. Also since we still maintain the ID in the route, we can use our existing data access logic and it also makes the URLs more hackable, for people who know which ID they want on your application, they can just change that and it will automatically put them in the right place.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Fixing Visual Studio’s Ctrl-Tab behavior

By mynameiscoffey on 2010-10-26 in .Net Development

One feature of Visual Studio that has always bothered me is how it handles Ctrl-Tab.  On pretty much every other application I have ever used, Ctrl-Tab (and its inverse, Shift-Ctrl-Tab) has had the function of moving between tabs in sequential order as they appear on-screen.  Visual studio, however, presents this little nugget when paging:

Visual Studio Window Switcher

The window switching menu that Visual Studio includes uses an Active File History rather than the open tabs themselves for ordering, so whatever file you are actively editing is at the top, the most recently looked at is next, and so on.  This might make sense to somebody, and some might find it useful, but to me it is annoying because the order of the files on the Active Files list does not match what I see when I look at the top of the screen.

I looked around and found lots of hacky macros to try to restore this functionality, however (at least in Visual Studio 2010), Microsoft has provided a much simpler solution.

In Visual Studio 2010, go to Tools > Options.  Select Environment > Keyboard in the options menu (If Keyboard doesn’t show up, make sure you have Show all settings checked).   Filter commands for NextTab (make sure you don’t hit Enter once you type in your search criteria, it still controls the OK button on the page).  The action we are looking for is Window.NextTab, which is the behavior we get in most applications.  I bind this to Ctrl-Tab, and Window.PreviousTab to Ctrl-Shift-Tab.

Options Menu for Next Tab

The only thing that doesn’t seem to work perfectly at this point, is when I am inside an aspx or cshtml file the binding doesn’t work.  If anyone knows a solution to this problem please let me know in the comments!!

Share this on: Mixx Delicious Digg Facebook Twitter

About Me

Josh Coffey is a professional software developer working and playing in Austin.

Google Ads

Copyright © 2013 mynameiscoffey.

Powered by WordPress and News.