Do you know what a Tuple is? Have you ever used a Tuple in C#? Have you heard of Tuples but assumed they were some complicated language feature? Tuples are very useful and very easy to use.

A Tuple is a very easy way to create objects that have multiple properties. Sure, creating classes is pretty easy too. But sometimes you just want to pass around a few pieces of information and not create a class just for that. And yes, I know you can use a struct instead. But both of those are very permanent. Do I really need to create a new Type in my project for something so simple? Here’s an example.

Today I was writing a method that returned some XML as string. The XML was going to be combined into a larger XML document. Sort of like this:

string xml = "<OuterNode><Section1>{0}</Section1></OuterNode>";
string inner = someService.GetXml();
string.Format(xml, inner);

Pretty simple right? But then I found out that I actually needed to get 2 portions of XML and they went into two different places:

string xml = “<OuterNode><Section1>{0}</Section1><Section2>{1}</Section2></OuterNoded>”; //simplified for the example

Sure there are lots of ways to do this:

  1. I could create a second method to return the second section of XML. Sure I could. But as much as I like single responsibility, the method I am using really is the right place to return both pieces of information. You’ll have to trust me on that :)
  2. I could create a class to hold both pieces of information like the one below. But, well, I am lazy. Plus, it just feels like a lot of overhead for this.
public class XmlHolder
{
    public string FirstPart {get; set;}
    public string SecondPart{ get;set;}
}

This is a use case where a Tuple can come in handy. A Tuple is a data structure that has a specific number of arguments, each of a specific Type and in a particular order. Please don’t be mislead by the word “structure”; a Tuple is a Class, not a Struct. Here is how you create a Tuple:

var firstTuple = Tuple.Create(xmlPartOne, xmlPartTwo); //Both of those arguments are strings.

Cool huh?

To get the data out:

var foo = firstTuple.Item1;
var bar = firstTuple.Item2;

OK, cool. But not super cool. “Item1”, “Item2”??? To me that seems sort of cheesy. But keep in mind, this is not a Dynamic Type object so you can’t name the properties. So I guess “Item1”, etc, will be ok.

Using the Create() method is cool. But what exactly does it create? Here is another way to write it that gives us some more insight:

Tuple<string, string> firstTuple = Tuple.Create(xmlPartOne, xmlPartTwo);

or

Tuple<string, string> firstTuple = new Tuple<string, string>(xmlPartOne, xmlPartTwo);

Now you can see what is really going on… Generics! I love Generics.

Do you have more than two items? That’s no problem:

var foo = Tuple.Create(string1, string2, string3, string4, string5); // assume these arguments are all strings please.

Got items of different types? Easy:

var foo = Tuple.Create(someString, someInt, someDecimal, somePersonObject, someThingElse);

That last one is the same as this:

Tuple<string, int, decimal, Person, SomeThingElse> firstTuple = Tuple.Create(someString, someInt, someDecimal, somePersonObject, someThingElse);

Easy right? And of course, thanks to Generics it is strongly typed.

These guys are really easy to use. Plus unlike an anonymous object, you can pass them around. Here I have a method that takes a Tuple as an argument.

public void DoSomething(Tuple<int, string, DateTime> input)
{
    int age = input.Item1;
    string name = input.Item2;
    DateTime hireDate = input.Item3;
}

The problem with the example above is that the developer who calls the method cant really tell what arguments the method really wants. It would probably be better to do this:

public void DoSomething(int age, string Name, DateTime hireDate)

So, Tuples are classes that should be used with some caution. Not because they are “bad” but they may not be the best kind of object to pass around because, while strongly typed, the properties aren’t “strongly named”. Certainly not a great choice for a public API. I think they should really be used sparingly. Certainly great for prototyping. And good for real applications too. But as a team lead, I wouldn’t want to see my team start using Tuples in place of regular classes all over the place!

Some more information:

Tuples were introduced in .Net 4.0.

Tuples are immutable. You can’t change the value once it is defined.

Items in the Tuple can be value or reference types.

Tuples are classes, not structs so they are on the heap, not the stack. That means they are garbage collected.

You can use Create() for Tuples with 1 item to 8:

  • Create(T1); // called a singleton
  • Create(T1, T2); // called a pair
  • Create(T1, T2, T3); //called a triple
  • Create(T1, T2, T3, T4); // called a quadruple
  • Create(T1, T2, T3, T4, T5); // called a quintuple
  • Create(T1, T2, T3, T4, T5, T6); // called a sextuple
  • Create(T1, T2, T3, T4, T5, T6, T7); // called a septuple
  • Create(T1, T2, T3, T4, T5, T6, T7, T8); // called an octuple
  • Plus you can pass another Tuple in as the 8th argument to make even larger Tuples!

Check them out, I hope you will enjoy using Tuples in your code.

Now that the holidays are over it is time to get back to business. The Philly Application Lifecycle Management group has 2 great meetings scheduled.

The first is Thursday evening, Jan 22. Come hear Nik Molnar talk about tracking web performance.

The second meeting is next month on Thursday Feb. 19. For that meeting, Jess Chadwick talks about Getting the most out of NuGet.

We are really lucky to have these great speakers coming to our group. I’ve attended talks presented by both of these guys and I can assure you they will be good!

For more information about the group, please head over to Meetup.com:

 

Here are some additional details on the meetings.

Tracking Real World Web Performance

Study upon study confirms that web performance has a direct correlation to revenue, operating costs, and search engine ranking. With this in mind, we all want our applications to be faster but how do we know what bottlenecks to focus on?

Join Nik Molnar, co-founder of the open source debugging and diagnostics tool Glimpse, to learn how to leverage free and open source tools to capture your application’s live performance data, understand what the metrics mean and focus on the ones you should really care about.

This session will cover how to use free services to act as a simple lab for synthetic performance testing and how to get Real User Metrics (RUM) from the very last mile via the instrumentation API’s built into browsers. Nik will also demonstrate techniques to automate the performance feedback loop so you can ensure to always treat “fast as a feature”.

This session is suitable for any stakeholder who cares about performance. It is classified as 200 level.

 

Getting the Most out of NuGet

NuGet is far more than just a UI that makes it easy to incorporate open source projects into your applications. At the core of NuGet lies a platform that any team or organization can leverage to easily and collaboratively share assemblies, content, and even development tools… all within the comfort of your company’s LAN.

In this session we’ll go beyond the public package repository and take a look at the NuGet platform in depth to see how easy it is to create custom NuGet packages and host them in a private repository. We’ll also explore some of the other powerful things that NuGet enables you to do such as easily sharing tools and even scripting Visual Studio.

Jess Chadwick is a software developer and technologist with over fifteen years of development experience ranging from embedded devices in start-ups to enterprise-scale web farms at Fortune 500s. He is an ASPInsider and a magazine, book, and online course author, including O’Reilly’s Programming ASP.NET MVC 4 and several courses on Lynda.com. Jess is actively involved in the development community, regularly speaking at user groups and conferences as well as leading the NJDOTNET Central New Jersey .NET user group.

One lesson I have learned over the years is not to take any unnecessary risks during production deployments. I hope that by sharing this wisdom I can help others, but I have the sad feeling that this one of those lessons that people need to learn the hard way. Unfortunately it is too tempting to “just go for it” sometimes. If it works, consider yourself lucky. When it fails (and sooner or later it will) you will regret your cowboy ways. I hope you will read on, there are some great ways to mitigate the risk of deployments.

Most of the problems that occur during deployments are caused by simple human error. Nothing serious, just plain old forgetfulness! In my experience, deployment issues usually arise because someone just forgets to do something. The thing that gets forgotten could be anything from a database script that gets missed, a forgotten view, an overlooked setting, or a .config file omission. And I don’t mean that this happens because someone is a bad developer. It’s just human nature. We are not perfect and can’t possibly remember everything.

There is no foolproof solution for perfect deployments. However, by following these tips you can greatly increase your likelihood of success. Of course, any of these practices will help but for best results, combine them all.

Deploy as often as possible

The best way to make sure nothing gets missed is to deploy often. Time is your enemy, the longer you wait, the more likely you are to forget something. During the development process we do so many things to make our applications work properly in our development environment. Sometimes we use a lot of trial and error too. As time goes on we can’t possibly remember all of the steps we have taken along the way. Following an agile process with short sprints is a great way to achieve short deployment cycles. Agile or not, try to deploy when features are complete and at major milestones. You don’t need to actually deploy to production. Use the same deployment process for all your environments. If you can’t deploy to production (there are lots of reasons for this), create a staging environment and treat it like production.

Take notes

Even if you deploy often, don’t rely simply on your memory. Take a lot of notes along the way during development and during your deployments to other environments such as test, staging, etc. Develop a good system so that your notes are there when you need them, not buried and forgotten in a notebook somewhere. I like OneNote for stuff like this.

Have a solid plan

Don’t wing it. Have a good, standard plan and stick to it. The more you follow the plan, the more likely you are to succeed.

Use a good code base

Of course, you only deploy code that you know works correctly, right? Once you know it works, don’t leave anything to chance. One of the best ways to do this is to deploy the same code to all your environments. Avoid going back to your source repository and recompiling. So many things can go wrong once you do. After you deploy to your test environment and everything has been verified, you should use the exact same files (.dlls, script files, whatever) and deploy them to prod (or your other environments). Of course you will be probably need to make configuration changes, that is often unavoidable.

Watch your timing

Find a time that works good for you and your team. Different businesses will have varying constraints on when they can do production deployments so you will of course need to work within those parameters. But I definitely have my preferences for when I would choose to deploy. I like to deploy first thing in the morning when I am fresh and thinking clearly. If something goes wrong, I have a lot of time to fix it. Also, I’ll have access to other people/resources for help if needed. If I deploy at the end of the day and something goes wrong I’ll be stuck working at night to fix it. That is bad because a) I’ll be getting tired and might not think clearly, b) I won’t have people around to help and c) I won’t get to have dinner with my kids. I also like to deploy midweek. Monday mornings are bad because over the weekend I have forgotten things already! Monday is a great day to put final preparations on a big deployment. Fridays are bad too. Because if things go wrong, I could be stuck trying to fix things over the weekend!

Automate your process

I don’t trust myself or my memory much. The best way I can protect myself from me is to automate my deployments. Once things are scripted, automated and tested, I have greatly increased my chances for success. Most of the other tips I have listed are fairly easy to implement, but putting together an automated deployment can be a big project all in itself! Depending upon your project, automated deployments can be quite complicated and there is a lot to learn in this department. There are lots of great build and automation tools out there to help such as MSBuild, NAnt, TeamCity, Hudson, CruiseControl, etc. I’ve used a bunch of different tools over the years and now I am using Team Foundation Server 2012. I’ve found it to be the easiest and fastest of all to set up for my web project deployments.

Practice your deployments

Practice makes perfect, right? Unfortunately with deployments, just when you get your process working smoothly there will be some big change that will require you to modify the process anyway. But practice will definitely increase your chance for success. I even practice my automated deployments, that is the reason to have a staging/faux-prod environment. And practicing really comes in handy when it comes to database changes. It’s great to have a staging environment set up just for the purpose of practicing deployments. To practice, get your staging environment set up to match your production environment including .dlls, html and script files, databases and other resources. Then run through your deployment process on staging. Once complete, test your application to make sure everything works. If something went wrong in the deployment, don’t patch it. The best thing to do is roll back the entire staging system, tweak your process and run it again. You do this as many times as needed until you get everything right. Then you are ready to repeat your steps in your production environment. Of course, the more you automate, the less likely errors will be. But don’t assume that just because you have an automated system you don’t need to practice too.

Start soon

Lastly, do not wait to implement this process. Many developers wait, thinking that they’ve got a long development cycle and won’t be deploying to prod for a long time, maybe months down the road. When I start a new project I begin working on the build/deployment automation right away. I also make sure there are tasks created for this process. Making this an official deliverable buys me time for this work which can definitely be time consuming. And if you don’t get this work done early, you might not get to it at all. When a project is almost complete and the delivery date approaches, you will never find time to get your process in place. You will then be stuck with an error prone deployment that not only keeps you worried but will likely cause you to work on weekends fixing deployment issues.

 

A solid deployment process takes a lot of planning and work. Of course, if you have ever been on the wrong side of a bad deployment you know that all the planning is worth the extra effort! Good luck.

 

Lately I’ve been speaking at local user groups about many of the exciting new features in Visual Studio 2012. Since there is so much to know and learn about VS 2012, I decided to create a collection of blog posts with many of the tips. This collection of posts will include features that are new to VS 2012 as well as some existing features as well. To view all of the VS 2012 tips posted so far, click here.

Visual Studio 2012 has got a lot of great features. Some of them are really innovative and interesting. I don’t think of the Add Reference Dialog improvements as anything but “why in the world did this work so poorly before?”. I’m guessing the Visual Studio team had some reason but let’s face it, the old Add Reference Dialog just plain sucked. One of the biggest problems with it was that it was very slow to load. I’m happy to report that the new Dialog loads really fast! Try it out, I am sure you will be please with the results.

Access it as you did before, right click a project and then click “add reference”:

image

Like I said, it loads up really fast. As you can see, in the middle section is the complete list of assemblies from the .net framework. Note that the items with checkmarks have already been added to my project. Just as you’d expect, you can add references to installed.net assemblies, other projects in your solution and COM Libraries. And of course, you can browse your system for other .dlls.

When you use this the first few times I expect your get bit by the same snag that I did (and still do sometimes). See the screenshot below… Notice that I clicked on Microsoft.Build to add the reference. You can see it highlighted in blue. If I click the OK button I’ll be disappointed with the results as my reference will not be added. What is needed is either to double click the item in the list or click the checkbox itself. Either way you’ll see the checkbox is then checked. Now you can hit OK. By the way, unchecking an item in the list will remove it from your project.

image

 

I hope you find this tip helpful. To see more VS 2012 Tips, just click here.

Lately I’ve been speaking at local user groups about many of the exciting new features in Visual Studio 2012. Since there is so much to know and learn about VS 2012, I decided to create a collection of blog posts with many of the tips. This collection of posts will include features that are new to VS 2012 as well as some existing features as well. To view all of the VS 2012 tips posted so far, click here.

I think (I hope) it is a well-known fact that Visual Studio will automatically complete your event handlers for you. The problem is, I’ve never liked the way it did this and I always went in and cleaned them up. Not any more!

What am I talking about? Here’s a sample. In this case, I have a class Foo that has an event SomethingHappened.

    public class Foo
    {
        public event EventHandler SomethingHappened;

        public void OnSomethingHappened(EventArgs e)
        {
            EventHandler handler = SomethingHappened;
            if (handler != null) handler(this, e);
        }
    }

In another class, I have an instance of Foo named foo. To wire up that event, all I need to do is type:

foo.SomethingHappened += [TAB][TAB]    (I hope you know that I mean hit the “tab” key twice Smile)

When you do that in Visual Studio 2010 (and prior), you will get the following results:

public class SomeService
{
    private Foo foo = new Foo();
    public SomeService()
    {
        foo.SomethingHappened +=new EventHandler(foo_SomethingHappened);
    }

    void foo_SomethingHappened(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
}

What happened here? Visual studio added a method (foo_SomethingHappened) and attached it to my handler for me. Thanks!

But this gets even better when you use Visual Studio 2012! Doing the same thing will get you this:

    public class SomeService
    {
        private Foo foo = new Foo();
        public SomeService()
        {
            foo.SomethingHappened += foo_SomethingHappened;
        }

        void foo_SomethingHappened(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }

 

OK, it isn’t thatdifferent. But the “new EventHandler” text is not there. It isn’t needed, of course so it rightfully isn’t there. I try to remove as much extra text from my code to make it more readable and I’m glad the Visual Studio team is thinking along the same lines. Actually, a lot of the time I clean this up even more by removing the object name from the event handler, in this case “foo_”. It might be needed sometimes, for clarity or, of course, if you need to specify which object the event is for. But in this case, I think it is just overly verbose. I prefer this:

    public class SomeService
    {
        private Foo foo = new Foo();
        public SomeService()
        {
            foo.SomethingHappened += SomethingHappened;
        }

        void SomethingHappened(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }

I hope you find this tip helpful. To see more VS 2012 Tips, just click here.