WCF Client Closal & Disposal

Say you’re consuming a WCF service. You’ve added a service reference, and you’ve got a client proxy. It implements IDisposable. So, when it’s time to use it, you should just chuck it in a using statement and not worry about additional resource cleanup, right?

Not so fast. There can be problems with the using statement. The problem is prevalent enough to warrant an article on MSDN demonstrating the improper use of using to automatically clean up resources when using a typed client.

So what should you be using instead of using? One option, which is outlined in the aforementioned MSDN article, is to use a try/catch block. If an exception occurs while closing the client, the client’s Abort method should be called. MSDN’s guidance suggests reporting errors and calling Abort for expected exceptions and calling Abort then re-throwing unexpected exceptions. The article explains, “Typically there is no useful way to handle unexpected errors, so typically you should not catch them when calling a WCF client communication method.”

// MSDN recommendation for WCF client cleanup
try
{
    client.Close();
}
catch (CommunicationException e)
{
    ...
    client.Abort();
}
catch (TimeoutException e)
{
    ...
    client.Abort();
}
catch (Exception e)
{
    ...
    client.Abort();
    throw;
}

There’s a lot of quick & dirty advice online that suggests using a try/finally block to first Close the client if it’s not in a faulted state, then Abort it if it’s not in a closed state. This is probably fine for small, simple applications, but hiding all exceptions can lead to maintenance woes later by reducing the visibility of underlying problems.

// effective but hides errors
try
{
    if (client.State != CommunicationState.Faulted)
    {
        client.Close();
    }
}
finally
{
    if (client.State != CommunicationState.Closed)
    {
        client.Abort();
    }
}

I like the suggestion laid out in this blog article. The author suggests re-implementing IDisposable in a partial class. The problem I have with this approach is that it may be confusing to other developers. When the client is used in the application, it will be wrapped in a using. There’s no good way for a developer to know whether that class has been properly re-implemented without doing further investigation. I think it’s easier for developers to have a hard rule: don’t use using with WCF clients.

So, instead of using a partial class, I’d suggest creating a wrapper that implements IDisposable. Developers using the client don’t need to worry about closing connections or error-handling; they can just throw a using around it an move on.

Here’s what that might look like. You could implement the service contract interface to ensure all methods are exposed, or have a generic method that accepts a lambda expression.

// An IDisposable client wrapper
public class Client : IDisposable
{
    private WcfClient _client;
    
    public Client()
    {
        _client = new WcfClient();
    }
    
    public void SomeMethod()
    {
        _client.SomeMethod();
    }
    
    void IDisposable.Dispose()
    {
        Dispose(true);
    }
 
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_client == null)
            {
                return;
            }
            
            try
            {
                if (_client.State != CommunicationState.Faulted)
                {
                    _client.Close();
                }
            }
            catch (CommunicationException e)
            {
                //...
                _client.Abort();
            }
            catch (TimeoutException e)
            {
                //...
                _client.Abort();
            }
            catch (Exception e)
            {
                //...
                _client.Abort();
                throw;
            }
            finally
            {
                if (_client.State != CommunicationState.Closed)
                {
                    _client.Abort();
                }
                _client = null;
            }
        }
    }
 
    ~Client()
    {
        Dispose(false);
    }
}

Convert Latitude/Longitude Between Decimal and Degrees/Minutes/Seconds in C#

Latitude and longitude are usually represented in one of two formats: signed decimal and degrees/minutes/seconds (DMS). Signed decimal values range from -90 to 90 for latitude and -180 to 180 for longitude. DMS values, on the other hand, are broken into four parts: degrees, minutes, and seconds–obviously–plus a compass direction.

Converting between the two formats is not terribly difficult if you keep the following formula in mind:

Decimal Degrees = Degrees + minutes/60 + seconds/3600

Computers are good at math and converting things, so let’s write a converter to do the work for us! First, we need to define some types to work with. We have two different formats, so it makes sense for us to have a DecimalLocation and a DmsLocation. We can also get some re-use out of a DmsPoint type, and we’ll need an enumeration for PointType to help with displaying N/S & E/W directional indicators. I threw in some overloads for ToString to help with displaying results, too. Also note that N/S/E/W are determined based on the sign of Degrees for DMS points.

class DecimalLocation
{
    public decimal Latitude { get; set; }
    public decimal Longitude { get; set; }

    public override string ToString()
    {
        return string.Format("{0:f5}, {1:f5}",
            Latitude, Longitude);
    }
}

class DmsLocation
{
    public DmsPoint Latitude { get; set; }
    public DmsPoint Longitude { get; set; }

    public override string ToString()
    {
        return string.Format("{0}, {1}",
            Latitude, Longitude);
    }
}

class DmsPoint
{
    public int Degrees { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }
    public PointType Type { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1} {2} {3}",
            Math.Abs(Degrees),
            Minutes,
            Seconds,
            Type == PointType.Lat
                ? Degrees < 0 ? "S" : "N"
                : Degrees < 0 ? "W" : "E");
    }
}

enum PointType
{
    Lat,
    Lon
}

Now that we’ve got our data types out of the way, we can work on the conversion. Our conversion formula shows how to calculate decimal degrees from DMS, so let’s do that first. It’s really straightforward–we just plug the formula into a function and call it for both latitude and longitude.

DecimalLocation Convert(DmsLocation dmsLocation)
{
    if (dmsLocation == null)
    {
        return null;
    }

    return new DecimalLocation
        {
            Latitude = CalculateDecimal(dmsLocation.Latitude),
            Longitude = CalculateDecimal(dmsLocation.Longitude)
        };
}

decimal CalculateDecimal(DmsPoint point)
{
    if (point == null)
    {
        return default(decimal);
    }
    return point.Degrees + (decimal)point.Minutes/60 + (decimal)point.Seconds/3600;
}

Going the other direction is a little more complicated. Ultimately, we’re just working backwards. Peel off the degrees, then calculate minutes, and seconds are left.

DmsLocation Convert(DecimalLocation decimalLocation)
{
    if (decimalLocation == null)
    {
        return null;
    }

    return new DmsLocation
        {
            Latitude = new DmsPoint
                {
                    Degrees = ExtractDegrees(decimalLocation.Latitude),
                    Minutes = ExtractMinutes(decimalLocation.Latitude),
                    Seconds = ExtractSeconds(decimalLocation.Latitude),
                    Type = PointType.Lat
                },
            Longitude = new DmsPoint
                {
                    Degrees = ExtractDegrees(decimalLocation.Longitude),
                    Minutes = ExtractMinutes(decimalLocation.Longitude),
                    Seconds = ExtractSeconds(decimalLocation.Longitude),
                    Type = PointType.Lon
                }
        };
}

int ExtractDegrees(decimal value)
{
    return (int)value;
}

int ExtractMinutes(decimal value)
{
    value = Math.Abs(value);
    return (int)((value - ExtractDegrees(value)) * 60);
}

int ExtractSeconds(decimal value)
{
    value = Math.Abs(value);
    decimal minutes = (value - ExtractDegrees(value)) * 60;
    return (int)Math.Round((minutes - ExtractMinutes(value)) * 60);
}

That’s it–we’ve got some lightweight methods to go between the two formats. Let’s whip up a quick test to verify the conversions:

void Main()
{
    DecimalLocation decimalLocation;
    DmsLocation dmsLocation;

    decimalLocation = new DecimalLocation
        {
            Latitude = 38.898611m,
            Longitude = -77.037778m
        };
    dmsLocation = Convert(decimalLocation);
    Console.WriteLine("{0} -> {1}", decimalLocation, dmsLocation);

    dmsLocation = new DmsLocation
        {
            Latitude = new DmsPoint
                {
                    Degrees = 38,
                    Minutes = 53,
                    Seconds = 55,
                    Type = PointType.Lat
                },
            Longitude = new DmsPoint
                {
                    Degrees = -77,
                    Minutes = 2,
                    Seconds = 16,
                    Type = PointType.Lon
                }
        };
    decimalLocation = Convert(dmsLocation);
    Console.WriteLine("{0} -> {1}", dmsLocation, decimalLocation);
}

// output:
//    38.89861, -77.03778 -> 38 53 55 N, 77 2 16 W
//    38 53 55 N, 77 2 16 W -> 38.89861, -76.96222

The converted values are off slightly, presumably due to some loss of precision, but the values produced are in the same general vicinity. (See here, here, and here.)

Full example:

void Main()
{
    DecimalLocation decimalLocation;
    DmsLocation dmsLocation;

    decimalLocation = new DecimalLocation
        {
            Latitude = 38.898611m,
            Longitude = -77.037778m
        };
    dmsLocation = Convert(decimalLocation);
    Console.WriteLine("{0} -> {1}", decimalLocation, dmsLocation);

    dmsLocation = new DmsLocation
        {
            Latitude = new DmsPoint
                {
                    Degrees = 38,
                    Minutes = 53,
                    Seconds = 55,
                    Type = PointType.Lat
                },
            Longitude = new DmsPoint
                {
                    Degrees = -77,
                    Minutes = 2,
                    Seconds = 16,
                    Type = PointType.Lon
                }
        };
    decimalLocation = Convert(dmsLocation);
    Console.WriteLine("{0} -> {1}", dmsLocation, decimalLocation);
}

class DecimalLocation
{
    public decimal Latitude { get; set; }
    public decimal Longitude { get; set; }

    public override string ToString()
    {
        return string.Format("{0:f5}, {1:f5}",
            Latitude, Longitude);
    }
}

class DmsLocation
{
    public DmsPoint Latitude { get; set; }
    public DmsPoint Longitude { get; set; }

    public override string ToString()
    {
        return string.Format("{0}, {1}",
            Latitude, Longitude);
    }
}

class DmsPoint
{
    public int Degrees { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }
    public PointType Type { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1} {2} {3}",
            Math.Abs(Degrees),
            Minutes,
            Seconds,
            Type == PointType.Lat
                ? Degrees < 0 ? "S" : "N"
                : Degrees < 0 ? "W" : "E");
    }
}

enum PointType
{
    Lat,
    Lon
}

DecimalLocation Convert(DmsLocation dmsLocation)
{
    if (dmsLocation == null)
    {
        return null;
    }

    return new DecimalLocation
        {
            Latitude = CalculateDecimal(dmsLocation.Latitude),
            Longitude = CalculateDecimal(dmsLocation.Longitude)
        };
}

DmsLocation Convert(DecimalLocation decimalLocation)
{
    if (decimalLocation == null)
    {
        return null;
    }

    return new DmsLocation
        {
            Latitude = new DmsPoint
                {
                    Degrees = ExtractDegrees(decimalLocation.Latitude),
                    Minutes = ExtractMinutes(decimalLocation.Latitude),
                    Seconds = ExtractSeconds(decimalLocation.Latitude),
                    Type = PointType.Lat
                },
            Longitude = new DmsPoint
                {
                    Degrees = ExtractDegrees(decimalLocation.Longitude),
                    Minutes = ExtractMinutes(decimalLocation.Longitude),
                    Seconds = ExtractSeconds(decimalLocation.Longitude),
                    Type = PointType.Lon
                }
        };
}

decimal CalculateDecimal(DmsPoint point)
{
    if (point == null)
    {
        return default(decimal);
    }
    return point.Degrees + (decimal)point.Minutes/60 + (decimal)point.Seconds/3600;
}

int ExtractDegrees(decimal value)
{
    return (int)value;
}

int ExtractMinutes(decimal value)
{
    value = Math.Abs(value);
    return (int)((value - ExtractDegrees(value)) * 60);
}

int ExtractSeconds(decimal value)
{
    value = Math.Abs(value);
    decimal minutes = (value - ExtractDegrees(value)) * 60;
    return (int)Math.Round((minutes - ExtractMinutes(value)) * 60);
}

Delete Another User’s Workspace in TFS

I’ve run into this problem several times. A build blows up for some reason and creates an orphaned workspace. Other builds then fail with the message The path […] is already mapped in workspace […].

tfsbuild_alreadymapped

The way that I’ve dealt with this in the past is to simply delete the workspace, which you can do easily enough by using the tf workspace command.

tf workspace /delete someworkspace;somedomain\someuser

When you run the command, you’ll be warned that deleted workspaces cannot be recovered and prompted to confirm.

tfsbuild_reallydeleteworksp

Type “Yes” and the deed is done. Run another build, and you should be good!

 

Get Cute with Predecessors in Microsoft Project

I’ve known about Microsoft Project for a long time, but I’ve never really done anything with it until recently. There are several Project aficionados around the office. I’ve taken a peek here and there at their projects, but I just didn’t see the value. I don’t think I was ready for it. My team recently adopted Project as its primary planning tool, though, and so I’ve been using it more frequently. Little by little, I’m learning and becoming more comfortable with it, and I’m liking it more each day. I’m not a zealot yet, but I may very well be on my way.

The coolest feature I’ve learned about is the Predecessors field for tasks. If you’ve seen project at all, you’ve probably seen this. It allows you to say, “Task A must be finished before Task B, and Task B must be finished before Task C.” That makes sense, but it’s not all that impressive. What’s cool about it, and much less obvious, is that you can specify the dependency type for a predecessor. You can also specify lead time and lag time. These two features allow you to plan for more complex–and realistic–scenarios: “Task A must be finished before Task B, and Task C should start two weeks after Task B is completed.”

Dependency Type Description
FS (Finish-to-Start) Start the day after the predecessor finishes
FF (Finish-to-Finish) Finish the day the predecessor finishes
SS (Start-to-Start) Start the day the predecessor starts
SF (Start-to-Finish) Finish the day the predecessor starts

That’s all good and well, but how is any of this useful? Well, by using these different dependency types, you can pick the task or milestone that’s most important to your project and build a plan around it. Then, if the date of that all-important item changes, the rest of your plan can adjust automatically.

My team is responsible for creating small, custom projects for our customers. We have a backlog of work, and we want to schedule our development work based on a projected deployment date. We enter the deployment task first and build the plan backward from that. In order to deploy, development needs to be done two weeks before. In order for development to begin, we need a completed design. To create a design, a requirements document must be signed by the customer. And so on.

In Project, that plan might look like this. Note that the dates in italics are calculated from the predecessors.

ID Task Duration Date Predecessor
1 Requirements 1 wk 5/6/13 2SF-1 wk
2 Design 1 wk 5/20/13 3SF-1 wks
3 Develop 4 wk 6/3/2013 4SF-2 wks
4 Deploy 1 wk 7/15/2013

To create this plan, I picked my targeted deployment date. The development task’s predecessor says, “The deployment task’s start date should be my finish date with 2 additional weeks of lead time.” Similarly, the design task should start so that it will be finished 1 week before the development task is scheduled to start, and the requirements task should be done 1 week before the design task begins.

Now let’s throw a curveball at the plan. Say that something comes up, and the customer needs an upgrade before I can do my deployment. I can insert a new task, and make it the deployment task’s predecessor. Everything else adjusts automatically.

ID Task Duration Date Predecessor
1 Requirements 1 wk 5/27/13 3SF-1 wk
2 Design 1 wk 6/10/13 4SF-1 wks
3 Develop 4 wk 6/24/2013 5SF-2 wks
4 Customer upgrade 0 days 8/5/13
5 Deploy 1 wk 8/5/2013  4

That’s so awesome! I just shifted the entire project plan to reflect a new milestone that nobody ever saw coming.

Fill-In Field Prompts in Word 2013

I was creating a Word document template for my team to use, and I wanted to include a reference number in the header to make it appear on each page. I initially created a field for the user to click and enter the value. The problem with using a simple entry field and sticking it in the header is that it’s grayed-out and easily forgotten.

So, instead of using a textbox field, I decided to prompt the user for the value by using a fill-in field. It’s an easy thing to do, and users of the template will never forget to enter the value. (Of course, they might choose to ignore the prompt, but that’s a different problem!)

To create a fill-in field in Word 2013, do the following:

  1. Put your cursor in the document where you want the field to appear
  2. In the INSERT bar in the ribbon, choose Quick Parts > Field…

    Word2013_FIllIn_QuickParts

  3. In the Field dialog, choose Fill-In as the field name, enter the prompt text, and click OK

    Word2013_FIllIn_FieldPrompt

  4. Be sure to save your document as a Word Template

    Word2013_FIllIn_SaveAs

That’s all there is to it. When you create a new document from the template, you’ll be prompted, and the value will be filled in.
Word2013_FIllIn_ValuePrompt

Good stuff!

Life-Changing Shortcuts: Windows Key + Arrow

Multiple screens are a must-have these days. I have just two, and I’m constantly throwing windows back and forth. Windows 7 introduced some nice docking features that make this easy and efficient. I can drag a maximized window by the title bar, and it will un-maximize. If I then “push” it to the top of my other screen, it will re-maximize.

Windows 7 also lets you drag windows to the sides of your screen to half-maximize it; the window will use the entire vertical space but only half of the horizontal space, as if it were docked to the side of the screen to which it was dragged. Great. I love it.

But there’s a problem. There are no edges between my screens. Ugh… I guess I’ll just resize the window to make it half-screen sized, and then manually position it along the crack like a caveman. I mean, there’s no better way to do this, right?

That’s what I might’ve said if this were 2012. I know some things now that I didn’t know then. That’s right, I’m talking about the Windows key + arrow shortcut. Use this amazing shortcut to reposition windows by jumping through the different docking options. Here’s the summary:

Shortcut Description
Windows + ↑ Maximize a normal or left/right-docked window
Windows + ← Left-dock a window; cycle through side-dock positions
Windows + → Right-dock a window; cycle through side-dock positions
Windows + ↓ Un-maximize or un-dock a window; minimize a normal window

Toggling maximize and minimize are no big deal, and neither are dock-left and dock-right. What is useful, however, is that dock-left and dock-right respect the boundary between displays. OMG–life changed! This is easily my favorite new shortcut of 2013. So, you probably won’t use this shortcut to maximize or minimize windows, but remember it for the next time you’re trying to look at four things all at the same time. I bet you’ll fall in love.

Pretty Forms with CSS & jQuery

Let’s say you’re making a web form. You want it to look nice, so you’d like the input controls to line up and be consistently sized. You know that you shouldn’t be using tables for formatting, but how else can you avoid creating an ugly mess of labels smushed-up against their controls?

UglyForm

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script type="text/javascript"></script>
    <style type="text/css"></style>
</head>
<body>
    <div>
        <label for="name">Name:</label><input type="text" name="name"/><br/>
        <label for="email">Email:</label><input type="text" name="email"/><br/>
        <label for="password">Password:</label><input type="password" name="password"/><br/>
        <label for="confirmPassword">Confirm:</label><input type="password" name="confirmPassword"/><br/>
        <label for="newsletter">Email me about stuff!</label><input type="checkbox" name="newsletter"/>
    </div>
</body>
</html>

I found a cool trick to fix the spacing of labels and controls using jQuery. The idea is simple: loop through all labels and set their widths equal to the widest. The logic to do this is a typical CS-101 find-the-max loop, but there’s also a not-so-obvious second step. In order for the widened labels to display, they must be floated to the left.

LessUglyForm

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
    <script type="text/javascript">
         $(function() {
             var max = 0;
             $("label").each(function () {
                 if ($(this).width() > max)
                     max = $(this).width();
            });
            $("label").width(max + 5);
        });
    </script>
    <style type="text/css">
        label {
            float: left;
        }
    </style>
</head>
<body>
    <div>
        <label for="name">Name:</label><input type="text" name="name"/><br/>
        <label for="email">Email:</label><input type="text" name="email"/><br/>
        <label for="password">Password:</label><input type="password" name="password"/><br/>
        <label for="confirmPassword">Confirm:</label><input type="password" name="confirmPassword"/><br/>
        <label for="newsletter">Email me about stuff!</label><input type="checkbox" name="newsletter"/>
    </div>
</body>
</html>

Fixing the label spacing helps, but it’s still pretty ugly. You don’t want the textboxes rubbing shoulders like that, and why are the password boxes slightly shorter than the textboxes? We can fix both of those items with some simple CSS.

OkayForm

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
    <script type="text/javascript">
        $(function() {
            var max = 0;
            $("label").each(function () {
                if ($(this).width() > max)
                    max = $(this).width();
            });
            $("label").width(max + 5);
        });
    </script>
    <style type="text/css">
        label {
            float: left;
        }
        input {
            margin: 2px;
        }
        [type=text], [type=password] {
            width: 150px;
        }
    </style>
</head>
<body>
    <div>
        <label for="name">Name:</label><input type="text" name="name"/><br/>
        <label for="email">Email:</label><input type="text" name="email"/><br/>
        <label for="password">Password:</label><input type="password" name="password"/><br/>
        <label for="confirmPassword">Confirm:</label><input type="password" name="confirmPassword"/><br/>
        <label for="newsletter">Email me about stuff!</label><input type="checkbox" name="newsletter"/>
    </div>
</body>
</html>

Okay, now we’re starting to look like a respectable form! We can make our form a little nicer by adding a fieldset control to house our controls, and we can add a label to controls through the fieldset’s legend. In order to facilitate auto-sizing of the fieldset–it’s 100% width by default–I moved the labels and inputs into a list, and that required another jQuery loop and some CSS. As final step, add more CSS to further improve aesthetics. For this example, I added a custom web font and made the fieldset legend bold and red.

PrettyForm

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
    <script type="text/javascript">
        $(function() {
            var max = 0;
            $("label").each(function () {
                if ($(this).width() > max)
                    max = $(this).width();
            });
            $("label").width(max + 5);
            max = 0;
            $("fieldset").each(function() {
                $(this).find("li").each(function () {
                    var w = $(this).find("label").width() + $(this).find("input").width();
                    if (w > max)
                        max = w;
                });
                $(this).width(max + 10);
            });
         });
    </script>
    <link href='http://fonts.googleapis.com/css?family=Unkempt' rel='stylesheet' type='text/css'>
    <style type="text/css">
        body {
            font-family: 'Unkempt', sans-serif;
        }
        fieldset {
            margin: 10px;
            padding: 10px;
        }
            fieldset legend {
                font-weight: bold;
                color: maroon;
            }

            fieldset ul {
                margin: 0;
                padding: 0;
            }

            fieldset li {
                list-style: none;
                padding-bottom: 10px;
            }
        label {
            float: left;
        }
        input {
            margin: 2px;
        }
        [type=text], [type=password] {
            width: 150px;
        }
    </style>
</head>
<body>
    <fieldset>
        <legend>User Info</legend>
            <ul>
                <li><label for="name">Name:</label><input type="text" name="name"/></li>
                <li><label for="email">Email:</label><input type="text" name="email"/></li>
                <li><label for="password">Password:</label><input type="password" name="password"/></li>
                <li><label for="confirmPassword">Confirm:</label><input type="password" name="confirmPassword"/></li>
                <li><label for="newsletter">Email me about stuff!</label><input type="checkbox" name="newsletter"/></li>
            </ul>
    </fieldset>
</body>
</html>

Create Permanent Custom Styles in Outlook

One of my peeves in Outlook is the formatting of code snippets that I send in email. Nine times out of ten, I’m copying and pasting from Visual Studio. That works pretty well; you get keyword highlights and all that fun stuff. Life is good–unless you happen to have a dark background. I like the dark theme for Visual Studio 2012, but I can’t stand that pasted text comes with a black highlight! It’s not that I mind the black background, but the highlighted text looks like a disaster.

DarkBackgroundCodePasteIntoOutlook

At this point, you’ve got three options: go back to a light-background theme in Visual Studio, deal with it, or adjust the formatting in Outlook. It looks too ugly for me to ignore, so option #2 is out. Until know, I’ve been exercising option #1, living in a default-themed world. I decided to go in a different direction today, though. I created a style that I can use to quickly format my pasted code. (An easy solution that I considered using for a while was to use LINQPad as a formatting buffer. I’d copy/paste code from Visual Studio to LINQPad and then re-copy/paste from LINQPad to Outlook. It works.)

The key to making this as painless as possible is getting the style configured correctly. Here are the steps I used to create my new style in Outlook 2013:

  • Choose “Create a Style” from the Styles gallery (FORMAT TEXT > Styles)
  • Change paragraph spacing options
    • After: 0 pt
    • Line Spacing: Single
  • Modify borders and shading
    • Border Setting: Box
    • Border Color: White
    • Border > Options > From text (all sides): 12 pt
    • Shading Fill: Custom Color (RGB: 30, 30, 30)

To ensure the style sticks around for future emails, do the following:

  1. Change Styles > Style Set > Save as a New Style Set…
  2. Change Styles > Style Set > Set as Default
  3. Restart Outlook for the new default style set to take effect

When I paste code from my dark themed Visual Studio, it still looks ugly. I can make it prettier by simply selecting the text and applying my new style. As a final beautification, I select the text and remove the black highlight from the text. (The removal of highlighting wouldn’t be necessary if I were content to use a black background, but I think 30/30/30 gray looks nicer, and so I will remove the highlight.)

DarkBackgroundCodePasteIntoOutlook_Better

It’s definitely a few extra clicks anytime I’m sending code, but the end product looks good!

Posting Data to an ASP.NET Page Method with Knockout

PostingDataToPageMethodWithKnockoutSample

Last time in my Knockout series of posts, I explored how to retrieve and bind data from an ASP.NET page method. That’s only half the battle, though. How can you take data captured and do interesting things with it? I’ve got an idea! How about passing it to an ASP.NET page method!

I’m going to use my example from last time with a few modifications. I added some entry controls to capture the user’s status, and I modified the GetStatus page method to return the user’s last status. The last status values will be displayed as read-only and will only be visible when a value exists. Here’s the ASPX and code-behind. Note that ASPX contains a button bound to a method in the view model that’s not yet implemented, and the code-behind has a UpdateStatus method.

default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="adamprescott.net.Knockout.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.min.js"></script>
    <script src="Scripts/knockout-2.2.1.js"></script>
    <script type="text/javascript">
        $(function () {
            var viewModel = {
                wasHappy: ko.observable(),
                lastStatusText: ko.observable(),
                isCurrentlyHappy: ko.observable(),
                currentStatusText: ko.observable(),
                updateStatus: updateStatus,
            };
            ko.applyBindings(viewModel);
            getLastStatus();

            function updateStatus() {
                // todo: post data to page method
            }

            function getLastStatus() {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetStatus",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var data = result.d;
                        if (data == null) {
                            $("#lastTime").hide();
                            return;
                        }
                        $("#lastTime").show();
                        viewModel.wasHappy(data.HappyFlag);
                        viewModel.lastStatusText(data.Text);
                    }
                });
            }
        });
    </script>
</head>
<body>
    <div>
        <strong>How are you feeling?</strong><br/>
        Are you happy? <input data-bind="checked: isCurrentlyHappy" type="checkbox"/><br/>
        Tell me about it: <input data-bind="value: currentStatusText"/><br/>
        <button data-bind="click: updateStatus">Update Status</button>
    </div>
    <div id="lastTime">
        <strong>How you felt last time:</strong><br/>
        Were you happy? <input data-bind="checked: wasHappy" type="checkbox" disabled="true"/><br/>
        What you told me about it: <span data-bind="text: lastStatusText"></span>
    </div>
</body>
</html>

default.aspx.cs:

using System;
using System.Web.Services;

namespace adamprescott.net.Knockout
{
    public class Status
    {
        public bool HappyFlag { get; set; }
        public string Text { get; set; }
    }

    public partial class Default : System.Web.UI.Page
    {
        private static Status lastStatus = null;

        [WebMethod]
        public static Status GetStatus()
        {
            return lastStatus;
        }

        [WebMethod]
        public static void UpdateStatus(Status status)
        {
            lastStatus = status;
        }
    }
}

When the button is pressed, we need to collect values and put them into an object to be passed to our page method. That’s easy–just grab values from the view model:

var data = {};
data.HappyFlag = viewModel.isCurrentlyHappy();
data.Text = viewModel.currentStatusText();

Now that we’ve got our values, we just need to pass them to our page method. Once again, it’s jQuery to the rescue!

$.ajax({
    type: "POST",
    url: "Default.aspx/UpdateStatus",
    data: JSON.stringify({ 'status': data }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function () {
        // todo: anything?
    }
});

Bam! We just passed data to the page method in the code-behind. Tutorial accomplished. However, I need to go a little further. Now that I just updated the status, I want my UI to update its view to show the latest status. So, when my call to UpdateStatus finishes successfully, I just need to make another call to GetStatus. Super easy!

Here’s the final ASPX.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="adamprescott.net.Knockout.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.min.js"></script>
    <script src="Scripts/knockout-2.2.1.js"></script>
    <script type="text/javascript">
        $(function () {
            var viewModel = {
                wasHappy: ko.observable(),
                lastStatusText: ko.observable(),
                isCurrentlyHappy: ko.observable(),
                currentStatusText: ko.observable(),
                updateStatus: updateStatus, 
            };
            ko.applyBindings(viewModel);
            getLastStatus();

            function updateStatus() {
                // todo: post data to page method
                return;
                var data = {};
                data.HappyFlag = viewModel.isCurrentlyHappy();
                data.Text = viewModel.currentStatusText();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/UpdateStatus",
                    data: JSON.stringify({ 'status': data }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () {
                        getLastStatus();
                    }
                });
            }

            function getLastStatus() {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetStatus",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var data = result.d;
                        if (data == null) {
                            $("#lastTime").hide();
                            return;
                        }
                        $("#lastTime").show();
                        viewModel.wasHappy(data.HappyFlag);
                        viewModel.lastStatusText(data.Text);
                    }
                });
            }
        });
    </script>
</head>
<body>
    <div>
        <strong>How are you feeling?</strong><br/>
        Are you happy? <input data-bind="checked: isCurrentlyHappy" type="checkbox"/><br/>
        Tell me about it: <input data-bind="value: currentStatusText"/><br/>
        <button data-bind="click: updateStatus">Update Status</button>
    </div>
    <div id="lastTime">
        <strong>How you felt last time:</strong><br/>
        Were you happy? <input data-bind="checked: wasHappy" type="checkbox" disabled="true"/><br/>
        What you told me about it: <span data-bind="text: lastStatusText"></span>
    </div>
</body>
</html>

“Faux” Multiple Inheritance with Extension Methods

Here was my scenario: I had a project with a bunch of classes that used a common logger. I wanted each of the classes to “tag” logged messages with their type to improve traceability. I created a simple wrapper for my logging methods, like so:

public class Animal
{
    public ILogger Logger { get; set; }

    private void Foo()
    {
        // logs "[Animal] Called from Foo!"
        LogInformation("Called from Foo!");
    }

    private void LogError(string message, params object[] args)
    {
        Log(x => x.LogError(message, args));
    }

    private void LogInformation(string message, params object[] args)
    {
        Log(x => x.LogInformation(message, args));
    }

    private void Log(Action<string> logAction, string message, params object[] args)
    {
        if (Logger == null)
        {
            return;
        }
        var msg = string.Format("[{0}] {1}",
                this.GetType().Name,
                string.Format(message, args));
        logAction(msg);
    }
}

When I log messages from this class, they look like “[Animal] some message,” and I can easily see where they came from. Great, but I wanted this functionality in a few more places and I didn’t want to copy/paste the same code into each class that needed it. (DRY, you know?)

So, instead, I created a new interface and created some extension methods for it.

public interface ILogging
{
    ILogger Logger { get; }
}

public static class LoggingExtensions
{
    public static void LogError(this ILogging instance, string message, params object[] args)
    {
        Log(instance, x => instance.Logger.LogError(x), message, args);
    }
    
    public static void LogInformation(this ILogging instance, string message, params object[] args)
    {
        Log(instance, x => instance.Logger.LogInformation(x), message, args);
    }
    
    private static void Log(this ILogging instance, Action<string> logAction, string message, params object[] args)
    {
        if (instance.Logger == null)
        {
            return;
        }
        var msg = string.Format("[{0}] {1}",
                instance.GetType().Name,
                string.Format(message, args));
        logAction(msg);
    }
}

This isn’t quite as pretty as the original, but it’s a snap to re-use. Here’s a look at the example from above, refactored to implement the new interface and use its extension methods:

public class Animal : ILogging
{
    public ILogger Logger { get; set; }

    private void Foo()
    {
        // logs "[Animal] Called from Foo!"
        this.LogInformation("Called from Foo!");
    }
}

What’s really neat about this is that I get “inheritance behavior” without having to actually derive from a base class. This is valuable since you can only inherit from a single class in C#. You are allowed to implement many interfaces, though, so this technique gives you a “faux multiple inheritance” behavior without inheriting from any classes. Cool!