Tuesday, May 08, 2012

Today the Visual Studio team announced some changes to the look of Visual Studio 11. You can read about it here.

When the Beta came out a little while back there was quite a lot of talk about the new look for the UI. I wrote a blog post about it as well. Many people were pretty upset about the new “metro” look to Visual Studio. I wasn’t completely in love with the new look at first myself. A flood of complaints came in as people got their first look at the new skin to a familiar tool. I think all the complaining was premature. As I stated in my blog post, once I started using Visual Studio 11 I got used to it pretty quickly. I’ve been using it a lot over the past month or so and I’ve even gotten to the point where I like it more than VS 2010. However, I do think it was missing some color. Well, people complained and Microsoft listened. I think that was pretty cool. Today the public got a peek at the changes that have been put into the release candidate. I won’t bother pasting images in, I think you should read about it on the Visual Studio blog. I really think that they achieved a nice balance, putting in some color where needed to enhance the experience.

I think it is time t move on from this topic. I’ll close with a few points:

  1. Visual Studio 11 has tons of great features. The new look is just on the surface. People should play with it for a while and see what is inside!
  2. Don’t be so quick to judge. I’ll admit, I had some doubts but I gave it a chance. I think the designers made a few mistakes but they are fixing them. For instance, the old icons were hard to read when they had borders around them. I’m glad this is fixed. I’m glad they added some color back in to, it makes certain icons stand out nicely. But when you give it some time you may find that these designers were also right about of lot of their ideas. VS11 is quite easy to use.
  3. It’s over. Stop complaining. Like many people, I don’t like the All Caps menus that are in the latest refresh. SO WHAT? Is it really that big a deal? Is this really worth switching over to Java and using Eclipse? Some people are actually talking like that should be our response. Come on people, get a grip.
Tuesday, May 08, 2012 8:52:49 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Wednesday, April 18, 2012

It seems like for forever I have been dealing with the problem of deploying software and keeping the database updates synchronized at the same time. I’m sure you’ve been there too. If you are developing software, you likely need database schema changes from time to time (or much more often). If you are running a local copy of the database for development (I like working like that), you can easily make the change on your local SQL Server instance (or some other database product). But then you need all of your teammates to update their database instances with the changes. Of course, they may have changes to the schema as well. All that, plus sooner or later you will need to deploy these changes to the test, staging or production database.

Where I have worked we used a variety of techniques to accomplish this goal but it has never been easy. Finally, Microsoft gives us Entity Framework Migrations! This makes this situation very easy to deal with!

Here are some steps to get started with Migrations. I was surprised with how easy this is to use. To be fair, I haven’t pushed this technology much past the basics but it is working quite nicely on my project so far. Also I’m using EF Code First which is really cool but in this post, I won’t be explaining all of the parts of that. I’ll mention the basic steps but if you want to learn more about the many features of EF Code First, you’ll need to look elsewhere.

Beware, I am running Visual Studio 11 Beta, .Net 4.5 Beta, Entity Framework 5 Beta. You should be able to accomplish this stuff with earlier versions too.

Step By Step Guide to Getting Started with Entity Framework Code First Migrations (in C#)

  1. Create a new application. I’m working with a simple C# Console App.
  2. Install Entity Framework. You can do this via the Nuget Package Manager UI or the Package Manager Console. Again, I am using beta so I’ll need to use the console with this command: PM> install-package EntityFramework –includePreRelease
  3. I did get an error when I did that. I don’t recall getting that error in the past but to resolve the error, I used the Add Reference Dialog and added a reference to System.ComponentModel.DataAnnotations. Then I re-tried the console command and it worked just fine.
  4. After installing EntityFramework, my app.config looks like this:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
    EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> </configuration>

    Thanks NuGet!

  5. Next we’ll need to create an entity that needs to be in our database. In my application, I need a simple object to represent movies.
        public class Movie
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Year { get; set; }
            public string Studio { get; set; }
        }

    You will note that I did NOT annotate this class with any attributes at all.

  6. Next we’ll need to create our DbContext. It too is pretty simple.
        public class MovieContext : DbContext
        {
            public DbSet<Movie> Movies { get; set; }
        }
  7. Ok for this simple sample, my initial data schema is done. Since this is Code First however, my database doesn’t actually exist yet. Let’s have Entity Framework create it for us. To do so, we need to run our application. Before running it, just add this code to the Main method of your console app. If your application doesn’t “use” the DbContext, it won’t be generated.
        MovieContext context = new MovieContext();
        foreach(var movie in context.Movies)
        {
                    
        }
    Now just run the app. If you’ve got SqlServer Express installed, you will now have a new database in there that looks like this:image
    Yes, the Id was automatically turned into a primary key. Sweet, huh? Code First Rocks!
  8. Now we have a database and a schema but we haven’t used migrations yet! Let’s get started with that. Back in the NuGet Package Manager Console, type this: PM> enable-Migrations 
  9. When you enable migrations, it will create a Migrations folder in your project with two files.
    • 201204190017084_InitialCreate.cs (your name will vary). This file contains the code to create your database schema from scratch. In this case, there is only one table. This will be important because after we do our next migration, we may need to roll back to our initial design.
    • Configuration.cs which is used for… you guessed it, configuration of Migrations. One important setting is AutomaticMigrationsEnabled. With that set to true, EF will always migrate your database when you run your application and it detects that your context is out of sync with your db.
    • Check out these files and you will see how simple this stuff is. Each migration contains an Up() method and a Down() method. This enables you to migrate your database up and down to any version!
          public partial class InitialCreate : DbMigration
          {
              public override void Up()
              {
                  CreateTable(
                      "Movies",
                      c => new
                          {
                              Id = c.Int(nullable: false, identity: true),
                              Title = c.String(),
                              Year = c.String(),
                              Studio = c.String(),
                          })
                      .PrimaryKey(t => t.Id);
                  
              }
              
              public override void Down()
              {
                  DropTable("Movies");
              }
          }
  10. Now we need to make a change: Add something to the Movie class, something like this: public string Genre { get; set; }
  11. Now if we run our application (remember that we do NOT have Automatic Migrations Enabled). We’ll get an error:image
    In this case, that is perfect and just what we expected.
  12. Back to the Package Manager Console: PM> add-migration Genre That command will create a new Migration file for us with just what we need:
        public partial class Genre : DbMigration
        {
            public override void Up()
            {
                AddColumn("Movies", "Genre", c => c.String());
            }
            
            public override void Down()
            {
                DropColumn("Movies", "Genre");
            }
        }
  13. Next, this command in Package Manager Console: PM> update-database You’ll get some messages confirming the action. When I check my database I’ll see that the new column was added just as I needed. I can now run my application successfully again. Too bad my application doesn’t do anything.

Eventually, you will have multiple migrations in your project. If you need to revert back to an old version of code, you can also revert back to an old version of the schema by specifying which a target. In this example, I want to target the migration named “InitialCreate”: update-database –TargetMigration InitialCreate

To create scripts instead of actually updating your database, you can use a command similar to this: update-database -Script -TargetMigration Genre These scripts can be saved and used as part of your deployment process.

Those are the basics of Entity Framework Migrations. I think you will find it is pretty easy to use. For more information, I suggest you follow the ADO.Net Team Blog.

Download my sample solution: MigrationsDemo.zip

Wednesday, April 18, 2012 10:00:15 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Sunday, April 15, 2012

I’m a few weeks into a side project that I blogged about in a previous post. I’m having a lot of fun (I’m such a geek) using a bunch of new stuff. Since Visual Studio 11 is at the center of all the work on the project, I thought I’d share my first impressions on it. Of course, I’m using a Beta version of it. Really this post is about my second thoughts since they are much more meaningful. Spoiler alert: First impressions aren’t always the most important.

My first thoughts

My first thoughts were pretty typical and can be summarized with one bullet:

  • Colorless

That is pretty much what most people think when they see it for the first time. People tend to ignore all of the improvements and new features and focus on the lack of color. At first I found this lack of color to be somewhat distracting which is odd because it is meant to have the opposite effect. I’ll be honest, I wasn’t thrilled with the new look but I was quick to point out to some of my peers that we should give it some time and get used to it.

My Second Thoughts

Guess what? I got used to it… quickly. After using Visual Studio 11 for a couple of hours, I quickly got used to the lack of color. It isn’t really that big a deal and I think the VS team was on the right track by moving Visual Studio overall to the background and making the code editor the focal point. Having said that, I still think some color would be helpful. My last point on the overall lack of color is that it isn’t 100% consistent. Some windows within VS11 still have color. And some plugins use color too. That makes things a bit odd. I’m including a screenshot below. That’s all for the color.

image

Some features to note (this is by no means a comprehensive list, just some highlights):

So far, I think VS11 is an awesome development environment. I’ve been doing MVC development within VS11 and the HTML, CSS, and JavaScript support is really nice. VS11 is now providing a lot of help for developers working in these areas. I’ll also point out that I am using ReSharper (v7 EAP for VS11). I love ReSharper! Between VS11 and ReSharper, the web development experience is awesome. I’ll be honest, I don’t always know which tool is providing the various features!

When developing web apps, we typically want to run/debug/test them in a variety of browsers. It seems like Microsoft has figured out the IE is not the only browser in town. So now we can use the Debug Target toolbar button. Just click the typical “play” button or hit F5 to debug in which ever browser is selected: image Or you can use the drop down to chose a different target or change the default:

image

I like the fact that the great features of the Solution Navigator (previously part of the Productivity Power Tools) were combined into the Solution Explorer. Of course, the Add Reference dialog is a huge improvement from the past, that was also a feature from the Power Tools.

I’m also a huge fan in the reduction of items in the toolbars. I think the VS team really nailed that part of the design as well. They took out all but the most commonly used buttons from the toolbar – but only in the default configuration. If there is a button or toolbar you like, just add it back in. That part is easy! More importantly, we should all get used to the Quick Launch feature. With that, we can just type the name of any command we want. No more hunting around in the menus for seldom used actions!

Another great feature is the Preview Tab. I’m surprised more people aren’t talking about this one. This is pretty cool but I don’t think you can get the full value of it until you experience it yourself. Think about all those times you are debugging and you end up stepping into file after file after file. All those files get opened up in the tab well. Eventually you get to the file you want in the debug process. But when you are done you have a ton of open files. Not everyone is like me, but I hate open files. I want my tab well to be as empty as possible. Preview Tab to the rescue! With VS11, all of those files that you step through don’t open up as normal files, they open in the Preview Tab. But Preview Tab only has one file at a time. So each new file you step into replaces the old one and your environment stays clutter free. And Preview Tab is pretty smart too. If you make a change to the file it moves it into the normal tab well. You can also click a button in the tab to “promote” the file to be a normally opened file. In this image you can see the Preview Tab on the right, circled in blue.

image


While it isn’t really new, I want to mention that the extensibility features of VS11 (and 2010 too) are really powerful and work so well and somewhat seamlessly. The Extension Manager is really cool and with it I’m always adding tools to Visual Studio. There are loads of great things to install. With VS2010 I hadn’t gotten to experience Nuget but with the work I’m doing now in VS11 I am all over it. Nuget (or is it NuGet, or nuget?) is providing all kinds of good stuff for my solution. Between VS11, the extensions and nuget packages, I really feel empowered to create great solutions.

There are lots of other great features, these are just the ones that came to mind as I was writing. Download the Beta and check it out for yourself!

Sunday, April 15, 2012 7:45:21 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Thursday, April 12, 2012

A lot of new stuff has been coming out from Microsoft lately. Couple that with all the cool open source projects available for use and a developer can quickly get left behind from all the new technology. I try to stay pretty current but there is some new stuff that I’ve been wanting to use. I also wanted to brush up on some old skills and even use some of the technologies I am experienced with in new ways. I decided it was time to start a little project for myself. I’m often asked by developers about how they can gain experience with new technology (or even old tech that is new to them). My advice is that they should just write an application that uses the technology. As a hiring manager, I’ll give serious consideration to that kind of experience, provided it isn’t “hello world”. When I write an application like this, I treat it like a real world production project. And if you are creating a web application you can have it hosted and then it IS a real product. That should count as experience to a smart hiring manager. So when you write these applications, try to follow all of the best practices, use good standards, etc.

In my case, I am writing an application that I hope will actually get some use. I’m hoping to get some great blogging material out of this as well. I already have, but now I need to find time to write about it. Anyway, figure out what you want to build and then create a list of the things you want to learn. As you write the application, you can just keep adding other technologies, frameworks or patterns in along the way.

Here is my list of things I’m using or will be using in my new pet project. Obviously the beta stuff is brand new. And I’ve already got experience with MVC 2 (pre-Razor), jQuery, HTML, CSS, etc. However, this stuff gets better and better all the time and I like to stay on top of it. Working a few hours here and there for the past 2 weeks, I’ve already included all of the items in blue in my project.

  • Visual Studio 11 (beta)
  • Entity Framework 5 (beta)
  • Entity Framework Code First
  • Entity Framework Migrations
  • ASP.Net MVC 4
  • Razor
  • HTML 5
  • jQuery
  • jQuery UI
  • Git
  • Open Authentication
  • CSS3 & Media Queries
  • HTML/CSS Grid Systems
  • NuGet
  • SEO Toolkit (Microsoft)
  • C# 4.5 (including Async)
  • SignalR
  • Azure
  • ASP.Net Web API
  • BootStrap (from Twitter)
  • Facebook Integration
  • Of course, Dependency Injection, Unit Testing, and all of the other stuff I put into any app I am deploying.

I’m writing this as a web application and creating a mobile version at the same time. In addition, I plan to extend this to additional platforms. So my list continues:

  • Mobile Web
  • WP7
  • Metro (Windows 8)
Thursday, April 12, 2012 2:21:00 AM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback

Philly.Net recently had a very successful event called CSharpenUp. We spent the day talking about some advanced topics for C# developers. We had 4 speakers and 80+ attendees. The feedback was very positive, everyone learned a lot and had fun too. If we can set it up, we’ll do the same event in the fall for those that missed it.

I’m still gathering code samples from the other presenters. But for now, here is mine:

Code samples and slides for my LINQ session: Intro to LINQ

Code samples and slides for my Unit Testing session: Unit Testing Made Easy

Also, FYI we did try to record the sessions using Camtasia. Unfortunately, the mic we used wasn’t that great. I’m trying to salvage mine but I may just re-record them.

 |  |  |  |  |  | 
Thursday, April 12, 2012 1:38:00 AM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Wednesday, April 11, 2012

When I write code, one of my big concerns is how will I test it. I’ve learned that when I see a static method, it is going to make things more complicated than I would like. However, resolving that isn’t usually too difficult. Converting a string value into an Enum is a perfect example. Of course, parsing the string may succeed or fail and I need to know how my code will behave in either case, hence the reason for the unit tests.

In order to make unit testing a bit easier, I wrote a simple class to help out. Basically, this class “wraps” Enum.TryParse() and of course, implements and interface. I’m also using some simple generics to make the casting a little prettier. Since I used an interface, I can now using MOQ, RhinoMocks, or any other framework to mock my dependency and control how it behaves.

You may note that I didn’t call the methods Parse. Instead, I used the name Adapt. That is just a naming convention of my current project so it made sense to be consistent. Feel free to rename this as you wish :)

Here is the interface:

public interface IStringToEnumAdapter
{
     T Adapt<T>(string value) where T: struct;
     bool TryAdapt<T>(string value, out T? result) where T : struct;
}

You’ll probably notice that my generic constraint is struct. That is because you can’t use Enum as a generic constraint. So struct is the best I’ve got to work with. And considering we are doing parsing here, if you pass any other stuct in, it is going to fail on the parse anyway. So I think it is pretty safe.

Here is the implementation:

public class StringToEnumAdapter : IStringToEnumAdapter
{
    public T Adapt<T>(string value) where T : struct
    {
        T result;
        
        bool success = Enum.TryParse(value, true, out result);
 
        if (success)
            return result;
 
        throw new InvalidEnumArgumentException(string.Format("{0} could not be converted to {1}", value, typeof(T).Name));
    }
 
    public bool TryAdapt<T>(string value, out T? result) where T : struct
    {
        T parsedValue;
        bool success = Enum.TryParse(value, true, out parsedValue);
 
        result = success ? parsedValue : (T?)null;
 
        return success;
    }
}

Guess what? It isn’t all that complicated right? If you are getting into testing, you’ll soon find out that simple steps like this make life a lot easier.

Click here to download the class and unit tests for it too.

 |  |  |  | 
Wednesday, April 11, 2012 9:02:58 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Tuesday, February 14, 2012

Tomorrow night I’m doing a demo at Philly.Net on AOP. It’s a pretty cool technology that allows you to deal with cross cutting concerns in a pretty easy way. Write your code once (code for exception handling, logging, security, etc.) in an Aspect. Then you can easily reuse that same aspect throughout your application by simply decorating methods with an attribute.

If you attended my demo, you may want the source code… here it is.

If you are just curious, here is some sample code:

A simple Trace Aspect:

using System;
using System.Diagnostics;
using PostSharp.Aspects;

namespace AOPSample
{
    [Serializable]
    public sealed class TraceAttribute : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            Trace.WriteLine(string.Format("Entering {0}.{1}",
                args.Method.DeclaringType.Name, args.Method.Name));
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            Trace.WriteLine(string.Format("Leaving {0}.{1}",
                args.Method.DeclaringType.Name, args.Method.Name));
        }

    }
}

I want to write to the Trace log everytime DoSomething() gets called, so I decorate it with the Trace attribute!:
using System;

namespace AOPSample
{
    public class ServiceThatNeedsTracing
    {
        [Trace]
        public void DoSomething()
        {
            //it doesn't matter what is here.
        }
    }
}
When I run my application and call the DoSomething() method, I’ll get this in the Trace Window:
Entering ServiceThatNeedsTracing.DoSomething
Leaving ServiceThatNeedsTracing.DoSomething
Isn’t that easy?
 |  | 
Tuesday, February 14, 2012 10:06:55 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Wednesday, January 04, 2012

Linq is awesome and always makes tasks easier!  Here is a great tip that you might not know about.

Today I needed to compare two generic lists… SequenceEqual() to the rescue.  To show how it works, here is some sample code:

[Test]
public void SuccessfullyMatchesTwoListsOfInts()
{
    List<int> ints1 = new List<int>();
    ints1.Add(1);
    ints1.Add(2);
    ints1.Add(3);

    List<int> ints2 = new List<int>();
    ints2.Add(1);
    ints2.Add(2);
    ints2.Add(3);

    Assert.That(ints1.SequenceEqual(ints2), Is.True);
}

SequenceEqual loops through the 2 lists and compares each item to make sure they match.  Just for kicks I put it through the paces.  Here are some other unit tests that I wrote.  This helps show what you can do:

using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace SequenceEqual
{
    [TestFixture]
    public class SequenceEqualTests
    {
        [Test]
        public void SuccessfullyMatchesTwoListsOfInts()
        {
            List<int> ints1 = new List<int>();
            ints1.Add(1);
            ints1.Add(2);
            ints1.Add(3);

            List<int> ints2 = new List<int>();
            ints2.Add(1);
            ints2.Add(2);
            ints2.Add(3);

            Assert.That(ints1.SequenceEqual(ints2), Is.True);
        }

        [Test]
        public void SuccessfullyFailsTwoListsOfInts()
        {
            // these two don't match!
            List<int> ints1 = new List<int>();
            ints1.Add(1);
            ints1.Add(2);
            ints1.Add(3);

            List<int> ints2 = new List<int>();
            ints2.Add(1);
            ints2.Add(4);
            ints2.Add(3);

            Assert.That(ints1.SequenceEqual(ints2), Is.False);
        }

        [Test]
        public void SuccessfullyFailsTwoListsOfIntsOutOfOrder()
        {
            // these two don't match. They have the same contents but the order is changed.
            List<int> ints1 = new List<int>();
            ints1.Add(3);
            ints1.Add(2);
            ints1.Add(1);

            List<int> ints2 = new List<int>();
            ints2.Add(1);
            ints2.Add(2);
            ints2.Add(3);

            Assert.That(ints1.SequenceEqual(ints2), Is.False);
        }

        [Test]
        public void SuccessfullyFailsTwoListsOfStrings()
        {
            // these two lists of strings don't match
            List<string> strings1 = new List<string>();
            strings1.Add("one");
            strings1.Add("two");
            strings1.Add("three");

            List<string> strings2 = new List<string>();
            strings2.Add("one");
            strings2.Add("lasjdflkajsdf");
            strings2.Add("three");

            Assert.That(strings1.SequenceEqual(strings2), Is.False);
        }

        [Test]
        public void SuccessfullyMatchesTwoListsOfStrings()
        {
            // two matching lists of strings.
            List<string> strings1 = new List<string>();
            strings1.Add("one");
            strings1.Add("two");
            strings1.Add("three");

            List<string> strings2 = new List<string>();
            strings2.Add("one");
            strings2.Add("two");
            strings2.Add("three");

            Assert.That(strings1.SequenceEqual(strings2), Is.True);
        }

        [Test]
        public void SuccessfullyMatchesTwoListsOfObjects()
        {
            // works for objects too.
            List<TestObject> objects1 = new List<TestObject>();
            objects1.Add(new TestObject { Property1 = "1" });
            objects1.Add(new TestObject { Property1 = "2" });
            objects1.Add(new TestObject { Property1 = "3" });

            Assert.That(objects1.SequenceEqual(objects1), Is.True);
        }

        [Test]
        public void SuccessfullyFailsTwoListsOfObjects()
        {
            // these two lists of objects may "look" the same, but they aren't
            // the same object (reference equals!)
            List<TestObject> objects1 = new List<TestObject>();
            objects1.Add(new TestObject { Property1 = "1" });
            objects1.Add(new TestObject { Property1 = "2" });
            objects1.Add(new TestObject { Property1 = "3" });

            List<TestObject> objects2 = new List<TestObject>();
            objects2.Add(new TestObject { Property1 = "1" });
            objects2.Add(new TestObject { Property1 = "2" });
            objects2.Add(new TestObject { Property1 = "3" });

            Assert.That(objects1.SequenceEqual(objects2), Is.False);
        }

        [Test]
        public void SuccessfullyMatchesTwoListsOfObjectsWithCustomComparer()
        {
            // here I use a custom comparer to see if the 
            // two lists of objects have the same content.
            List<TestObject> objects1 = new List<TestObject>();
            objects1.Add(new TestObject { Property1 = "1" });
            objects1.Add(new TestObject { Property1 = "2" });
            objects1.Add(new TestObject { Property1 = "3" });

            List<TestObject> objects2 = new List<TestObject>();
            objects2.Add(new TestObject { Property1 = "1" });
            objects2.Add(new TestObject { Property1 = "2" });
            objects2.Add(new TestObject { Property1 = "3" });

            Assert.That(objects1.SequenceEqual(objects2, new TestObjectComparer()), Is.True);
        }

        [Test]
        public void SuccessfullyFailsTwoListsOfObjectsWithCustomComparer()
        {
            // making sure the custome comparer fails when they don't match
            List<TestObject> objects1 = new List<TestObject>();
            objects1.Add(new TestObject { Property1 = "1" });
            objects1.Add(new TestObject { Property1 = "2" });
            objects1.Add(new TestObject { Property1 = "3" });

            List<TestObject> objects2 = new List<TestObject>();
            objects2.Add(new TestObject { Property1 = "1" });
            objects2.Add(new TestObject { Property1 = "asdfsadf" });
            objects2.Add(new TestObject { Property1 = "3" });

            Assert.That(objects1.SequenceEqual(objects2, new TestObjectComparer()), Is.False);
        }
    }

    public class TestObject
    {
        public string Property1 { get; set; }
    }

    public class TestObjectComparer : IEqualityComparer<TestObject>
    {
        public bool Equals(TestObject x, TestObject y)
        {
            return (x.Property1 == y.Property1);
        }

        public int GetHashCode(TestObject obj)
        {
            return obj.GetHashCode();
        }
    }
}

Today I needed to compare to generic lists. I guessed that Linq would provide a way to do this and sure enough it did: SequenceEqual() to the rescue. To show how it work

 |  | 
Wednesday, January 04, 2012 10:23:16 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, December 09, 2011

I’m using TeamCity, MSBuild, and SVN together to do some pretty cool stuff around continuous integration and automated builds.  It’s been working well, untouched, for well over a year!  But all of a sudden my deployment process failed. Checking the logs with TeamCity, I found this:

[11:18:06]:   Error validating server certificate for 'https://[xxx].com:443':
[11:18:06]:    - The certificate is not issued by a trusted authority. Use the
[11:18:06]:      fingerprint to validate the certificate manually!
[11:18:06]:   Certificate information:
[11:18:06]:    - Hostname: [xxx]
[11:18:06]:    - Valid: from Mon, 29 Mar 2010 17:44:04 GMT until Thu, 26 Mar 2020 17:44:04 GMT
[11:18:06]:    - Issuer: [xxx]
[11:18:06]:    - Fingerprint: [xxx]
[11:18:06]:   (R)eject, accept (t)emporarily or accept (p)ermanently? svn: OPTIONS of 'https://[xxx]': Server certificate verification failed: issuer is not trusted (https://[xxx].com)

The best part about this was that, for a change, this error message was very clear.  Although I don’t know why the certificate failed.  Did it change or expire?  Did one of the network guys make a change to something?  I didn’t really care.  I just wanted to get my build working again.

Here is the line of MSBuild Script that caused the issue: (I’m using the SVN stuff from MSBuild Community Tasks)

<SvnClient Command="ls $(SvnRepository)/tags/$(BuildNumber) Username="$(SvnUserName)" password="$(SvnPassword)" ContinueOnError="true">
  <Output TaskParameter="ExitCode" PropertyName="Value"/>
</SvnClient>

Since the Command of SvnClient accepts any SVN command (in other words, anything that I can type at a command prompt), I searched the SVN Documentation.  It wasn’t hard to find that I just needed to update to this:

<SvnClient Command="ls $(SvnRepository)/tags/$(BuildNumber) --non-interactive --trust-server-cert" Username="$(SvnUserName)" password="$(SvnPassword)" ContinueOnError="true">
  <Output TaskParameter="ExitCode" PropertyName="Value"/>
</SvnClient>

This worked great but my build still failed.  That is because I have other SVN actions in my script and they don’t seem to know that I accepted the certificate. However, my other tasks are not using the very generic and flexible SvnClient Command, they are using tasks such as SvnCopy or SvnCommit, etc.  For instance:

<SvnCopy SourcePath="$(SvnRepository)/$(SvnProjectLocation)/"
    DestinationPath="$(SvnRepository)/tags/$(BuildNumber)"
    Message="Auto-tagging Revision: $(BuildNumber)"
    Username="$(SvnUserName)" password="$(SvnPassword)" />

So how could I tell SVN to accept the certificate.  I checked the MSBuild Community Tasks documentation, took a guess and got lucky on the first try…sweet.  I added this:

    <SvnCopy SourcePath="$(SvnRepository)/$(SvnProjectLocation)/"
        DestinationPath="$(SvnRepository)/tags/$(BuildNumber)"
        Message="Auto-tagging Revision: $(BuildNumber)"
        Username="$(SvnUserName)" password="$(SvnPassword)"
        Arguments="--non-interactive --trust-server-cert" />

I added the Arguments to all of my other SVN Tasks in my script and it worked perfectly!

Friday, December 09, 2011 9:23:56 AM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, April 01, 2011

Last night I had the pleasure of presenting “Unit Testing Made Easy” at NoDeNUG (Northern Delaware .Net User Group).  I’ll be doing the same demo at Philly.Net Code Camp next week.  The NoDeNUG crowd was great and asked good questions.  That made the demo fun for me and I think it went very well.  I hope it goes over great at Code Camp too. 

I’m attaching a zip file containing my slides and Visual Studio Solution.  The demo should work fine on it’s own, the references to NUnit, MOQ, and StructureMap are all included.  But if you don’t have VS2010 with Premium or Ultimate and Feature Pack 2, the CodedUI (testing for Silverlight UIs) won’t work.  I hope it will build and run ok though.  If not, let me know and I’ll upload the solution without references to the Coded UI stuff.  Also, the demo uses a Silverlight application for the front end.  If you don’t have the Silverlight tools set up, you can either add them to Visual Studio, or simply exclude the Silverlight projects.  You’ll still be able to run the services and the unit tests, even if you can’t see how the UI looks.

If you’ve just come across this and haven’t heard my presentation you have two options:

1. Come to Philly.Net Code Camp next week (April 9) and hear the presentation then!

2. Just open the enclosed solution and have a look!  I’ve got sample code in there to demonstrate using Dependency Injection to make services easier to unit test, sample unit tests, and sample tests using mocking of dependencies.  I’m coding my tests with NUnit, using StructureMap for my IOC, and MOQ as my mocking framework.

Here is the code:  UnitTestingMadeEasy.zip

Again, if you have any problems with the solution, let me know and I’ll upload a copy without the Coded UI, or even without the Silverlight part.

 |  |  |  |  |  |  |  | 
Friday, April 01, 2011 7:51:28 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [1]  |  Trackback