Change the Default Text of Controls in Word Templates

One of my pet peeves is when people create and distribute MS Word forms that don’t use controls for the fields. It’s a very easy thing to do, and everybody will be happier to use your form. What makes that form even nicer, though? Changing the default text of your field controls to be friendly and more indicative of what information is being requested.

This is a relatively simple task, accomplished in just 4 very easy steps:

  1. On the Developer tab in the ribbon, enable Design Mode by clicking the toggle button
  2. Select all the text between the prompt tags; be sure to select the text while in design mode, otherwise you may change the font/color of your text to something other than the prompt default
  3. Type the desired prompt text
  4. Disable Design Mode by clicking the toggle button

Use this tip to instantly improve that quality of any Word document form. Share it with your co-workers; they’ll be impressed!

Credit: this is the post where I picked up this little nugget of information.

Advertisements

10 Habits of Remarkably Uncharismatic People

this is what i'm talking about

I just finished reading an article at Inc.com: 10 Habits of Remarkably Charismatic People. I like reading these types of articles because they help me find new ways to be a little better, or they give me a little pat on the back when they suggests habits or behaviors I already do. Like most articles of this nature, the list wasn’t exactly earth-shattering. Here’s the abbreviated version:

  1. Listen more than you talk.
  2. Listen to everybody.
  3. Put distractions away.
  4. Give before you receive, and expect to receive nothing.
  5. Don’t act self-important.
  6. Realize that others are more important.
  7. Shine the spotlight on others.
  8. Choose your words. (Choose to be positive.)
  9. Don’t discuss the failings of others.
  10. Readily admit your failings.

What I like about this list is not that it illuminates a path to +1 charisma but that it reminds us to be good people. The article could have easily been titled “10 Tips For Being a Good Human” or “10 Ways to Make People Not Hate You At the Grocery Store.” (Seriously–apply these at the grocery store, people.) But you know what’s more fun? 10 Habits of Remarkably Uncharismatic People:

  1. Talk all the time. If it’s worth saying, you’re probably talking about it.
  2. Only listen to people from whom you have something to gain. Otherwise, what’s the point?
  3. Text and email come first. People in your presence won’t mistakenly assume you’re ignoring them.
  4. Give only when you receive, else you might receive nothing. That would be totally unfair.
  5. Act self-important. Walk the walk, baby.
  6. Realize that others are just jealous. Don’t let them steal what’s rightfully yours.
  7. Shine the spotlight on your own achievements. You’re amazing! Make sure everybody knows it.
  8. Complain. If nobody knows you’re unhappy, you’ll have to keep doing it.
  9. Readily admit the failings of others. You’ll look better by comparison.
  10. Don’t discuss your failings. (Maybe nobody noticed.)

Back to the point, the 5-second version of the article goes something like this: be a {humble, respectful, positive, gracious, transparent, good} person, and people will like you more. When you put it like that, it’s a pretty obvious message. Nonetheless, it would go a long way if everybody were to embrace this list and focus on being a little more charismatic in their everyday lives. More specifically, at the grocery store. And at restaurants.

Files as Embedded Resources in Unit Tests

One of the most common unit test mistakes that I see is using relative file paths to actual files. The problem with this is that tests run automatically as part of a build might not have the same file structure that your relative paths assume. A better solution is to use the DeploymentItem attribute in your tests to ensure the necessary resources are copied to the relevant unit test directory, but I prefer a different solution: compiling the files as embedded resources.

A file is added to the project as an embedded resource simply by changing its Build Action in Properties. Once it’s an embedded resource, it can be accessed from your unit tests like this:

private string GetFileContents(string sampleFile)
{
    var asm = Assembly.GetExecutingAssembly();
    var resource = string.Format("MyProject.Tests.SampleFiles.{0}", sampleFile);
    using (var stream = asm.GetManifestResourceStream(resource))
    {
        if (stream != null)
        {
            var reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }
    }
    return string.Empty;
}

Note that the resource name is the Solution Explorer path to the file. So the above example is from a test project named “MyProject.Tests” in a folder named “SampleFiles.” This function accepts a file name and will return the contents of the specified file from that directory as a string.

This technique can be used in conjunction with mocks to simulate a multitude of scenarios like reading a file, retrieving data from a web service, or querying a database.

Here’s a quick example that demonstrates how this could be used to simulate retrieval of data from a web service:

public interface IDataAccess
{
	string GetXmlDataFromWebService();
}

public class MyClass
{
	private readonly IDataAccess _dataAccess;
	
	public MyClass(IDataAccess dataAccess)
	{
		_dataAccess = dataAccess;
	}
	
	public void Execute()
	{
		var xml = _dataAccess.GetXmlDataFromWebService();
		// do more...
	}
}

[TestMethod]
public void Execute_ProcessesXml()
{
	// Arrange
	var mockDataAccess = MockRepository.GenerateMock<IDataAccess>();
	var target = new MyClass(mockDataAccess);
	
	var xml = GetFileContents("TestData.xml");
	mockDataAccess.Expect(x => x.GetXmlDataFromWebService())
		.Return(xml);
	
	// Act
	target.Execute();
	
	// Assert
	mockDataAccess.VerifyAllExpectations();
	// more assertions...
}

Unit Tests: Why I Love ‘Em

Image borrowed from here

Unit tests are one of my favorite things to write as a developer. I simply love them. It’s like a little game I get to play with myself to ensure I’ve covered all possible scenarios and verify that my code is absolutely bulletproof. If I’m doing maintenance work on a project without tests, you better believe it won’t be without tests by the time I’m finished. And when I review another developer’s code and find issues that I know would’ve been caught by even the simplest of unit tests, I feel sad.

There’s been a lot of buzz about unit tests for several years now, but it’s still a challenge getting everybody to buy in. Where’s the real benefit with these tests? Isn’t it going to take me a lot longer if I have to write tests for everything? Aren’t I just making more work for myself when I make the changes that I’ll inevitably be making? No, no, NO!

The benefits of unit tests and test-driven development are so great and so many that whether or not to do it shouldn’t even be a discussion. That said, I realize there’s a path to enlightenment that takes time to travel, and I want to help you get there. So let’s explore some of these endless benefits that I’m speak of…

SOLID Design

Code that is difficult to test is often a result of poor design. If you follow the SOLID design principles, you will find that your code generally lends itself well to unit tests. Writing tests first can help identify a bad design before it’s too late. SOLID principles make testing easier. So, by embracing unit tests and test-driven development, your coding practices will naturally evolve to follow these principles.

  • Single responsibility principle – Testing and verifying an object with a single, clear, defined purpose will be easier than testing a class with multiple, vague responsibilities. Know your class’s purpose, and you’ll have a better idea what tests to write. It’s important to apply this principle to methods, as well. A method that does one thing is easy to test. A method that does 100 things, not so much.
  • Open/closed principle – Making classes extensible will make them flexible in unit test scenarios. One of my favorite techniques is using partial mocks with RhinoMocks, which rely heavily on this principle.
  • Liskov substitution principle – Embracing this principle will help you keep base classes and interfaces simple. This will make consumers of your objects easier to test because less time can be spent repeating unnecessary mocking. Don’t make an IMyDataProvider that has implementation-specific public methods (e.g., CreateDatabaseConnection(), ExecuteStoredProcedure(), etc.). Instead, create a method that does what’s needed, like GetData(). The result is that a MockMyDataProvider can be provided, and you need only mock the GetData method every time instead of each implementation-specific method. Still write tests for those implementation-specific methods, but write them in the tests for your data provider implementation!
  • Interface segregation principle – Interfaces are, in my opinion, the single most important aspect of unit testing layer interactions. Mock objects built from interfaces are absolutely essential for testing most non-trivial scenarios.
  • Dependency inversion principle – Creating mocks, stubs, and fakes is meaningless without a way to inject them into the object being tested. Use constructor injection, property injection, or a dependency injection framework like Unity to provide your object with mocks to remove outside dependencies and test specific functionality.

Fewer Surprises

There is nothing more frustrating than spending hours upon hours troubleshooting an issue only to arrive at a piece of code that has clearly never been run. Write tests, and check your code coverage. If there are lines of code that haven’t been covered, you can evaluate them to determine whether or not additional tests should be written. Play the what-else-could-possibly-go-wrong-here game with yourself. Enforce your own assumptions with exceptions, and test those. If you expect an argument to be not-null, write a test that expects an ArgumentNullException to be thrown; that will be significantly easier to troubleshoot than a null reference exception.

Improved Maintainability

If you’ve spent any significant time maintaining the work of others, you know this is a big one. It’s unsettling to find yourself in the middle of someone else’s 1000-line function with a block of commented code that looks like it does exactly what’s been reported to not be happening. Clearly, removing it was an intentional move, but what will you be breaking by uncommenting it? If a test is written (MammothMethod_ShouldNotCallDatabaseDirectly()), and you uncomment the code that calls the database directly causing that test to fail, you’ll have received two yellow flags warning you that maybe this is a bad approach. Without the test, a developer shrugs, uncomments the code, feels good about it, and re-introduces a bug that was likely fixed previously by another developer. (Didn’t we fix that two releases ago?) Writing tests for your fixes ensures that you aren’t on the other end of that scenario where somebody undoes your fixes. (If they still undo your fix and break or refactor your test in the process, be sure to yell at them.)

Unit tests are also helpful in terms of code management when complex branching strategies are employed. Let’s say you have 20 developers working in different branches. When the branches are brought back together, how can you confirm that changes were not lost? With unit tests in place, you simply need to run the tests. Since that should be happening automatically with each build anyway, all you need to do is verify that the test are there. This really beats the alternative of reviewing code to see if a particular change is included. Plus you feel good as a code-mover knowing that the code is verifying itself with each move.

Well-Tested, High Quality Solutions

At the end of the day, what you’re really trying to produce is a quality solution. You want your deliverables to work correctly when your assumptions are met and handle unexpected scenarios gracefully. You want to tell your users how your application will handle any situation they can come up with. You want your users to feel great about you, whether it’s your company, your product, or you specifically. Unit tests can help you do all this. What happens if the web service isn’t available? There’s a unit test to verify an email is sent. How can I audit queries to the database? There’s a unit test to verify logging. What if an expected record is missing? There’s a test for that, too. If you can think of it, make sure you’ve tested it. Write the tests as you go, and you’ll be sure not to affect features implemented earlier. At the end of development, your code will have a collection of tests self-verifying every feature and enforcing all assumptions.

Did it take more code? Yes.
Did it take more time? Arguably.
Will the final product have higher quality, require less maintenance, and result in a net decrease in total development effort over time? Definitely.

Format Date/Time as UTC with Timezone Offset

Here’s a quick snippet from MSDN that demonstrates how to format a date/time to UTC format with a timezone offset. (ISO 8601 compliant!)

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);
DateTimeOffset dateOffset = new DateTimeOffset(date1,
    TimeZoneInfo.Local.GetUtcOffset(date1));
Console.Write(dateOffset.ToString("o"));

This will produce the following output:

2008-04-10T06:30:00.0000000-04:00

Everything you ever wanted to know and more about date and time formatting can be found here.

Print Recordset Details from IDataReader

Occasionally when working with recordsets returned by a stored procedure in an IDataReader, it can be helpful to print information about the columns returned. I like to do this when making a DTO class that mirrors a recordset to ensure that my class’s properties are typed consistently with the recordset. Printing the column details can be accomplished easily with the following code:

IDataReader reader = GetDataReader();
for (int i = 0; i < reader.FieldCount; i++)
{
    Console.WriteLine("Name:{0}, Type:{1}",
        reader.GetName(i),
        reader.GetDataTypeName(i));
}

Adobe CreatePDF Subscriptions: Why?

I was reading a PDF this morning and noticed a new button in the latest version of Adobe Reader: “Convert file to PDF using Adobe CreatePDF online.”

“Oooh,” I thought to myself, “Has Adobe finally provided us with a free and convenient way to create PDF documents??”

I promptly directed my browser to Google and searched “Adobe CreatePDF” and clicked the first result. At the top of Adobe’s landing page, there’s a button to “Create a PDF now” that takes you to… their subscription page? Really?

I guess this isn’t surprising, but it is disappointing. The list of features provided include converting Word DOCX files and Excel XLSX files. Of course, both Word and Excel come with this capability built-in via the Save As command, so these features merely provide me with a less convenient way to convert my Office documents to PDFs.

Maybe this would be good for a non-Officer user who needs to view Word and Excel documents, though? Not in my opinion. OpenOffice.org opens these file types and lets me do the same conversion via its Export function. This is actually how I used to create PDFs before Microsoft included the capability into Office. Google Drive (formerly Google Docs) also lets you download copies of files as PDFs.

If you are going to charge for this — which, clearly, you are — why not make it more affordable? $89.99 annually seems pretty steep, especially if you compare it to products like Adobe’s own ExportPDF which allows you to go the other direction, converting PDFs to Word or Excel for just $19.99 annually. I wouldn’t be interested in paying a one-time fee of $89.99 for this, and, frankly, ExportPDF seems like the more valuable of these two products!

So who is this product’s target demographic? I simply can’t come up with a reasonable answer. To me, this represents Adobe preying on users that either don’t realize this functionality already exists in the latest versions of Office or aren’t resourceful enough to use free alternatives like OpenOffice.org and Google Drive. If this had been a free offering, I’d be writing a different article praising Adobe for making this available. Users needing to create professional-grade PDFs are still going to purchase licenses for Acrobat, so why not just make this available for the non-professionals to keep PDF adoption and accessibility rates high? Maybe I’m failing to pick up on the key features or benefits, but I simply don’t get it. Am I missing something here?!

Yield Keyword Explained

The yield keyword is a neat, but infrequently used, language feature of c#. Essentially, it allows you to “queue-up” results to be returned by a method as an enumerable collection.

Consider this simple example that produces a collection of integers from 0 to 9:

static IEnumerable<int> GetValues()
{
    var result = new List<int>();
    for (var i = 0; i < 10; i++)
    {
        result.Add(i);
    }
    return result;
}

By using yield, we can skip the step of creating a List<int> variable to store our results. This function will produce the same result:

static IEnumerable<int> GetValuesYieldEdition()
{
    for (var i = 0; i < 10; i++)
    {
        yield return i;
    }
}

Create a Word Cloud with Wordle

A word cloud is a cool way to present data, and they can be created really easily with free tools like Wordle. Word clouds are typically generated by analyzing text for the frequency of words and phrases. More frequent words are displayed in a larger font making it easy to identify themes.

If you already have text for the word cloud, that’s great — just copy/paste it into the tool and click generate. You can “engineer” a word cloud by simply repeating words and phrases. To adjust the appearance of the generated word cloud, most tools have some sort of style randomizer. I typically randomize until I find something I like.

The above example was generated by using the following text. Note that “~” can be used to chain words together into phrases.

word~cloud
word~cloud
word~cloud
amazing
amazing
amazing
amazing
whoa
whoa
cool
so~easy