Archives

Archives / 2011
  • Silverlight 5

    “The reports of my death have been greatly exaggerated.” – Mark Twain Today, Silverlight 5 is released and available for download!  The Release Candidate has been around for some time, and many of us were expecting the release in November.  Well, here it is, November 39th, and it’s here!  Here are some of the things that are New or Improved in Silverlight 5: Binding Improvements, including ICustomTypeProvider, Binding in Style Setters, DataContextChanged Event, and Custom Markup Extensions Support for the XNA 3D API for 3D graphics 3D Render Targets 3D surface composition settings 3D multi-sample anti-aliasing Other improvements to the … more

  • Handy EnumerableExtensions

    There’s a great site for finding extension methods, ExtensionMethod.net.  I don’t believe either of these came from there, and I’ve not (yet) submitted them there, but here are a couple of extensions on IEnumerable<T> that I’ve found useful recently. ForEach<T> The first one is simply a method that allows you to easily iterate over a sequence and perform an action on it.  This is a pretty commonly useful extension method, so much so that it’s now included in .NET 4.0 out of the box.  But if you’re using an older version of the framework, this is one you can roll yourself. public static void ForEach<T>(this IEnumerable<T> items, … more

  • View HTML Source of Email in GMail and Google Apps

    If you’re working on creating a pleasant-looking HTML email template for your site’s newsletter, you’ll want to test it out on the major email clients, including Outlook and GMail.  For instance, if you get The Code Project’s Insider Daily News in your GMail inbox, it will look something like this: Now, if you view the source for this page, you’ll get something that’s less than useful.  The whole thing looks like a giant <script> block and has no relation to the HTML that was in your email template.  Of course, the interface uses frames (iframes), and depending on your browser you can also view the frame source: Which will yield this: How useful! If you … more

  • Inner Fields and Lazy Initialization in C#

    Using lazy initialization in C#, a class’s state is set up such that each property’s get method performs a check to see if the underlying field is null.  If it is, then it calculates or populates the field before returning it.  This is a very simple and common approach, but it requires that the class follows a convention of only accessing the field via the property.  Unfortunately, there are no language features that can enforce this, so it’s possible for errors to creep in.  Here’s an example of this approach working correctly: public class Order { // other properties   private Customer _customer; public Customer … more

  • RazorEngine Performance and Template Caching

    I’ve been using RazorEngine on a project and have been impressed with its simplicity and ease-of-use.  However, the performance of the application isn’t quite where I need it to be, and I was pretty sure the issue was with how I was using RazorEngine, especially since I could anecdotally see that the processor consumption on the machine running the app was quite high, and looking at the running tasks it was clear that most of that was a result of csc.exe (C# compiler) activity. A bit of searching found this discussion thread on codeplex regarding the re-compiling of existing templates.  The issue is a known one with version 2.1, which is the current release and what I’m … more

  • Install Application as Service on Windows Server 2008

    You can use the sc.exe command to install an EXE as a service on Windows Server 2008.  There’s a good article on creating an application that can easily run as either a console app or as a service here.  From an administrator command prompt, the syntax is something like this: sc \\servername create MyService.ServiceName binpath= d:\services\Foo\Foo.exe displayname= MyService.ServiceName Note that for this particular utility, the command line options include the “=” sign in them, so you must have no space before the “=” and you must have a space after the “=”.   Also the server name must be preceded by \\ to work. Assuming it works, you should see something like this: … more

  • Using If This Then That to Automate Your Life

    I’ve just started getting into If This Then That (ifttt.com) and have set up a simple task that will update my Steve Smith Facebook Page whenever I post something here to my blog.  Getting this set up was extremely simple to do, and so far although I’ve only been using it for about an hour I’m quite impressed and enamored with ifttt.com.  Here’s how easy it is to set up something like this: 1. Register with ifttt.com This took 30 seconds. 2. Create a task If this (the trigger): Then (the action to take – create a new Link Post on my Facebook Page): End Result: This is actually the first post I’m making since adding this task, so if this post shows up on my … more

  • Working with Lazy Loading in Entity Framework Code First

    Entity Framework 4 has Lazy Loading built-in and enabled by default.  Here’s a quick bit of code to show you how to work with this feature.  To get started with this, simply create a new Console Application and in nuget (Package Manager Console), run this command: install-package EntityFramework.Sample This will install a simple blog post example.  Copy and paste the following into your Program.cs file (replace everything): using System; using System.Collections.Generic; using System.Linq; using System.Text; using EFExample.Models;   namespace EFExample { class Program { static void … more

  • 3 Tips to Improve Your Connection Strings

    Due to some database moves, I’ve recently been touching a lot of connection strings, which has me thinking about the topic.  In fact, I put together a short survey on twitter, and invited a bunch of developers and DBAs to share their thoughts, both on twitter and in the survey, on some issues relating to connection strings.  Here are three tips you should know about that, if you’re not already using, should improve your use of connection strings.   Use Windows Authentication (if you can) By far the biggest tip I can offer is that you should be using Windows Authentication.  You can find this guidance directly from Microsoft, when they discuss Choosing an … more

  • Speaking at DevReach 2011

    I’m very pleased to be speaking again at DevReach in Sofia, Bulgaria next month.  As usual, the conference has an amazing list of speakers (which I’m still somewhat amazed includes me), with Scott Hanselman making the trip out this year to give several sessions.  If you have the opportunity to attend, I highly recommend it.  There’s certainly no other conference in Eastern Europe that comes close. This year, I’ll be presenting on three topics.  The first is something new for me.  I’ll be co-presenting with Richard Campbell of DotNetRocks on Performance Tuning ASP.NET – Stories from the Trenches.  For this session, Richard and I are each going to share some of … more

  • Cleveland 2011 Software Engineering 101

    Next Friday, 7 October 2011, Microsoft in Cleveland is hosting a free one-day event focused on the basics of Software Engineering.  There are a handful of seats left before the event sells out.  You can learn more and RSVP for Software Engineering 101 here (until tickets run out).  The event is being held at the Microsoft office here: Microsoft Corporation 6050 Oak Tree Blvd Independence, OH 44131 Last year, the event sold out (well, “sold” is misleading, since it’s free), and it’s on track to do so this year as well.  Here’s some more information, from the event’s home page: This is a one-day, FREE event designed to improve your software development … more

  • Wiring up an AutoCompleteBox to a JSON Service in Silverlight

    I’m currently building an internal application for The Code Project that needs to be able to transfer the contents of some potentially very large files over the wire.  After considering various ways to get the data from point A to point B, we decided the easiest thing would be to process the text file on the client, and send batches of rows up to the server for processing.  Initially we looked at building a WPF client for this, but then switched over to Silverlight 4 since the rest of the application is web-based and we didn’t want staff to have to worry about a separate standalone application. Basically the files get translated into simple lists on the server, so the UI simply … more

  • Set JsonRequestBehavior to AllowGet

    If you’re working with ASP.NET MVC and JsonResult, you may encounter this error: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set … more

  • Bidirectional Entity Foreign Key Names in EF Code First

    Ran into a small problem today, where I had two classes referring to one another using EF 4.1 Code First.  Let’s say I had a class Item and another class ItemHistory.  ItemHistory has a property of type Item that refers to the Item class.  Item, in turn, has an ICollection<ItemHistory> Histories property:  public class Item { public int Id { get; set; } public virtual ICollection<ItemHistory> Histories { get; set; } }   public class ItemHistory { public int Id { get; set; } public virtual Item Item { get; set; } } In my DbContext OnModelCreating() I have some code like this … more

  • WinRT and the Paradox of Choice

    In my recent analysis of the Windows 8 / WinRT options for building Metro style Apps, I mentioned the many choices Microsoft is offering for building these applications.  While I agree with Microsoft’s decision to support C++, .NET, and HTML5/JS developers when building these applications, it does still represent a Paradox of Choice for many developers, myself included.  If we consider only native apps for the iPad, there are far fewer choices involved when it comes to programming language and platform (effectively there is only one choice, or as my daughter Ilyana likes to tell me “One choice is not a choice!”).  Recently, a fair number of high profile companies (such as … more

  • Analyzing Windows 8 and WinRT

    Last week at BUILD, Microsoft introduced their vision for the next generation of Windows devices with announcements and previews of Windows 8, Metro style applications, and WinRT.  The BUILD conference was the most secretive event I’ve ever known Microsoft to hold, with very few leaks prior to the keynotes that began on Tuesday, September 13th.  Now that the event has come and gone, you can watch the sessions and keynote presentations for yourself here.  In this post, I am going to offer my own analysis of the event and its announcements, with what I view as some of the strengths and weaknesses of Microsoft’s strategy, and the threats and opportunities it creates.  I’m … more

  • Moving Beyond Enums

    I just published an article on ASPAlliance on Moving Beyond Enums, describing when and how to move from enums to classes in your code when you start demanding more from your enums than they were designed to give.  Check it out and let me know what you think.  I also thought I’d post an alternate LINQ-ified version of the DisplayFriendlyNames() method I used in the article. Original, non-LINQ version: public static string DisplayFriendlyNames() { var sb = new StringBuilder(); foreach (Role role in Role.List()) { if (role.IsVisible) { sb.AppendLine(role.Name); } } … more

  • Working with SimpleMembership outside of ASP.NET

    I’m using SimpleMembership, from WebMatrix’s distribution(WebMatrix.WebData), with an ASP.NET MVC 3 application.  You can find the NuGet Package for SimpleMembership.Mvc3 here, and installing it is just a matter of running “Install-Package SimpleMembership.Mvc3” from the Package Manager Console in Visual Studio.  Unlike the built-in Membership and Role providers for ASP.NET, SimpleMembership doesn’t require huge swaths of XML to be added to your web.config file, or much in the way of database initialization using tools like aspnet_regsql.exe.  Instead, it does pretty much all of its work in code, in a static class SimpleMembershipMvc3 that gets placed in your App_Start … more

  • Validating Emails for System.Net.Mail

    If you’ve worked with the System.Net.Mail API to send out messages, you may have run into the fact that when you add an email address to a message, it will sometimes throw an exception if the email doesn’t appear to be valid: var myMessage = new MailMessage();myMessage.To.Add("ssmith@somewhere,com"); // invalid ','// do more stuff Result: FormatException - The specified string is not in the form required for an e-mail address. This is handy since it’s usually better to fail early rather than wait until you actually go to send the message to learn that the email is invalid.  However, if you’re processing more than one email, you likely have code that might look like … more

  • Display Plus Sign in Excel if Value is Positive

    Sometimes in Excel you may want to actually display a + character (or plus sign) in front of the cell value if the value is positive.  For instance, if you’re showing the change in a value, like this (note these are made up values): In this case, you can imagine that the Change columns are relative to the previous month’s report, so this gives an at-a-glance idea of the trend.  However, you probably would like the first column to show a + sign so that it’s more clear that it’s a delta value, not a raw value.  You can apply this custom formatting to do so.  First, right click on the cell(s) you want to format, and select Format Cells.  Then click Custom and type in … more

  • Installing Visual Studio Load Test Agents and Controllers

    Visual Studio includes support for distributed load testing through the use of Test Agents and Controllers.  For reference, there are a couple of MSDN Walkthroughs on Installing and Configuring Visual Studio Agents and Test and Build Controllers and Using a Test Controller and Test Agents in a Load Test.  However, they lack pretty pictures, so if a screenshot walkthrough is more your speed, read on. Before starting, you’ll need to installation media.  This might be an actual DVD, or more likely it’s an ISO image you’ve gotten from MSDN that looks something like this: Here’s what mine looks like once mounted as my F: drive: Of course the next step is to run setup.exe, … more

  • Drawing Directed Graphs with GraphViz

    I’ve been wanting to draw some simple circle-and-arrow directed graphs for a while, because of a few problem domains I’m working in.  One example pertains to articles and related educational content, which I’d like to represent as a series of modules linked by arrows that represent prerequisites.  You can see a wonderful example of such a diagram on the Khan Academy’s site in their Exercise Dashboard (shown below): Their site actually uses the Google Maps API and is dynamic.  That’s beyond my needs for the moment, although I do think it’s quite cool.  I just want to draw circles and links and have them rendered nicely without my having to redraw them all or move them … more

  • How to Find Conference and User Group Presenters

    If you’re a user group leader or event organizer and are looking for quality presenters for your event, here are some resources that should help get you started.  This is not meant to be an all-inclusive or exhaustive list, of course, and to that end I fully expect that there will be great resources left as an exercise for you, the reader, to add via the comments.  Thanks for Gerhard Weiss for giving me the initial idea to post this (some time ago, on a mailing list). Know Thyself (and your past speakers) If you’ve been running a group or event for some time, you already have relationships with many speakers and presenters.  You also probably know which ones were best rated, … more

  • Common Design Patterns Resources

    Last night I gave a presentation at the Cleveland .NET SIG on Common Design Patterns.  The turnout was great, so much so that the group ran out of pizza and chairs, so thanks to everyone for taking the time to come out!  Thankfully the A/C held up pretty well (in years’ past, it’s been an issue there), and I hope everybody enjoyed the topic and discussion.  I promised that I would post the slides and demos here, so I am, along with a few links to other resources. Download my Common Design Patterns slides and sample code.  You can also view my sample code directly on CodePlex as it’s checked into its own fork of the MVC Music Store there. Learn more about Design … more

  • Single Payee Credit Cards for Recurring Payments

    Have you ever set up a recurring payment with a vendor using a credit card?  I have.  It’s very convenient, both for the consumer and the vendor, because neither one needs to be bothered with invoicing and paying bills on a regular basis.  Everything’s great, as long as the consumer really does still want the product or service offered by the vendor, and as long as the vendor is ethical and diligent about allowing the customer to cancel their service.  It’s this last bit where things sometimes break down, and which is why a large number of people choose not to use any kind of automated billpay, whether through their bank or by sharing credit card details.  If the … more

  • Everything You Need to Get Started with SpecFlow and WatiN

    I’m adding SpecFlow to an application I’m working on so that I can add some acceptance tests that actually exercise the user interface.  I’ve only spent a couple of hours on it thus far, but I have it working with a single specification running through the tests via WatiN.  I found the following resources helpful as I was going through this exercise: Getting Started with SpecFlow and ASP.NET BDD with SpecFlow and ASP.NET MVC BDD with SpecFlow BDD with SpecFlow and Watin WatiN – Web App Testing in .NET I’m assuming that you’re just interested in getting up to speed with SpecFlow for acceptance testing and that you don’t want to waste any time on hidden gotchas or … more

  • Dayton .NET User Group Talk on Anti-Patterns and Worst Practices

    Last night I spoke at the Dayton .NET User Group on the topic of Anti-Patterns and Worst Practices.  It was a pretty good-sized group, albeit rather subdued.  You’ll find some of the inspiration for the talk in my Principles, Patterns, and Practices of Mediocre Programming post, and others in the 97 Things Every Programmer Should Know book (or online here).  The slides and demos are available for download.  Thanks to those of you who came to the meeting, and to Joe for inviting me to come down and visit. more

  • Seth Godin The Dip

    I picked up The Dip by Seth Godin a while back and thought I’d post my thoughts on it.  It’s a quick read, at only 80 pages or so.  I’m generally a fan of Seth’s books, and I enjoyed this one.  His style is entertaining to read, and the book was worth the < $10 it cost on Amazon.  The key takeaway from this book is that when you hit the hard part of any activity you’re pursuing, you determine whether it’s worth it to push through to the end goal.  He makes a good point that winners know when it makes sense to quit, and basically choose their battles.  One of the principles of software development that I try to adhere to is to fail fast, which I think is … more

  • Copy a Table with data in SQL Server

    Sometimes when you’re about to do some major surgery on your database, you want the comfort of knowing that you can always rollback if there’s a problem.  And it’s not always the case that you’ll immediately know there was a problem.  Sometimes, you just want a copy of the original data so that you can go back to it, or use it to analyze where you went wrong.  Of course, you can backup the whole database, but restoring the full system is often overkill if you’re only working on a handful of tables, not to mention the fact that backups are rather cumbersome and slow compared to standard SQL statements.  What if you just need a complete copy of the data from one table in … more

  • Regional Differences

    Last week I ran a poll (that maxed out at 400 responses on twtpoll) asking how developers recommend using regions in C# (or not).  You can see the results here:

    About 15% of the respondents chose Other and/or chose to leave a comment.  The comments are useful because they often highlight answer categories that I overlooked when I set up the poll.  In this case, there were a lot of comments, I think because there are a lot of different opinions about regions in general, some of them rather heated.

    Clearly the largest number of respondents simply never use Regions.  A number of comments went on to say things like “Regions aren’t evil I just don’t know … more

  • Using Google Realtime Search to track Trends

    You can use Google’s Realtime search feature to track trending topics on social media networks like Twitter.  To find it, just do a search as usual, then click on the More icon on the left to open up the Realtime option (or just go to http://google.com/realtime). The default view will show you the most recent items for the given term(s).  You’ll also see a timeline showing the frequency with which the term(s) have appeared over a given time period. If you’re hosting an event (like the Stir Trek developer conference in Columbus, Ohio) and have set up a hashtag for the event, this can be very useful to see how things are going on the day of the event: Now, what I haven’t … more

  • How Developers Are Using var in C#

    The var keyword was introduced in C# 3.0, and has since gained quite a bit of popularity.  There is also a fair bit of contention over how it should be used, with posts like this one (with which I happen to agree) being not uncommon.  Over the last week I posted a couple of polls on twitter that asked about specific scenarios in which one might use var, trying to address the two scenarios outlined by the author of that post. Scenario One This was meant to depict the case where the type would appear twice on one line, and so using var makes the code more succinct while no less clear. http://twtpoll.com/r/a3w7j7 75% of respondents agree that this is a scenario in which you … more

  • On the Usefulness of Xml Summary Comments with Poll Results

    Last week I hosted a quick poll on Twitter about how useful a particular XML comment was for a particular class.  The code looked like this: /// <summary>/// Repository for handling Users./// </summary>public class UserRepository : Repository<User> The poll actually got 355 votes, which is pretty impressive.  In hindsight I should have added an option relating to generating documentation, or updated the “necessary evil” option to include documentation as a valid reason for having these, since a large number of comments pointed to documentation as a motivation for this.  Or intellisense.  Personally I don’t see how the above would provide me … more

  • Entity Framework Error - Model compatibility cannot be checked...

    If you’re using Entity Framework Code First and you have everything working with, for instance, a SQL CE database, but then you want to move to a full SQL Server database, you may encounter this message if you don’t do things in the right order.  In my case, what I did was open SQL Management Studio, Create my new database, then popped into Visual Studio, Server Manager, added a connection to it.  Then I grabbed the connection string and stuffed it into my config file.  When I ran my application, I got this error message: Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added … more

  • Record Visual Studio Web Test Using Fiddler

    Fiddler is a great tool for examining and working with HTTP requests.  If you’re a web developer, it’s one of those tools that you should definitely be at least aware of.  The most recent version has some nice new features, like being able to very easily isolate which window or process it’s recording, so you don’t end up with a lot of noise from messengers and other background HTTP requests.  The feature I want to describe for this post has actually been around for a while, so even if you’re using an older version of Fiddler, you can probably take advantage of it.  That is, you can easily export a Fiddler session as a Visual Studio Web Test (or Web Performance Test). … more

  • Log Method Name Helper

    Sometimes it’s handy to see the order in which methods are firing, or how long they’re taking, without having to attach a debugger.  Typically, you might write some code like this: public void Foo() { Debug.Print("Entering Foo"); // other stuff } public void Bar() { Debug.Print("Entering Bar"); // other stuff } This of course gets tedious after a while.  There are all kinds of things wrong with this approach.  It isn’t DRY.  It includes magic strings.  You’d almost never need it if you were following TDD.  Etc.  If you really need this kind of logging detail on a … more

  • Run Batch File as Scheduled Task

    I’ve had problems running batch files as scheduled tasks.  I’m not alone – over the past couple of weeks, while I’ve been trying to get a scheduled job to work on a new server (when it worked fine on the old one), I’ve done a fair bit of searching on this topic.  I’ve found long threads on how some folks cannot run batch file as a scheduled task, with suggestions such as using full UNC paths for all of the values (for the program name and start in folder).  I found a blog post explaining how batch files need to have a command window, and thus should be run with cmd.exe, in order for their output to be sent to a file for later examination.  I found a really long thread on … more

  • The 4 Stages of Learning Design Patterns

    Design patterns are general, reusable solutions that occur in software design, which can usually be adapted to fit into a number of different situations and applications.  Recently, I recorded a screencast interview with Carl Franklin on Commonly Used Design Patterns for dnrTV, and one of the things we discussed was the stages of learning design patterns.  I noted that, at least for myself, I’d found that I tended to go through four distinct phases during my learning process when it came to these patterns.  I’ve found it valuable to enumerate these stages, because if we can recognize where we are in our learning process, it can help us to evaluate whether our decision to use a … more

  • Fixing MaxItemsInObjectGraph quota Error in WCF Service

    I have a WCF Service that occasionally yields a message like this one: Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. Today isn’t the first time I’ve run into this message – I’ve fixed this issue before – but since this is the 2nd or more time I’ve run into it, I thought I’d post a quick resolution here so I can find it again later myself, and perhaps help some others.  There’s a rather long forum thread on this subject that ultimately includes the solution, but digging it out is a bit painful as is the case with so many forum threads, so I’ll sum up here and just … more

  • Exporting Blog Content from Community Server

    I have some old blog content scattered around a few different sites, and it’s on my list for the near future to consolidate it as much as possible onto a single blog engine and domain – one blog to rule them all – at least for my own stuff.  I wasn’t sure how to get my content out of http://weblogs.asp.net/ but a quick email got me the answer, which I thought I’d share.  To export your content from weblogs.asp.net in BlogML format, just log into your dashboard and select Syndication Settings under Global Settings.  Then, click the Export button under “BlogML Export”, as shown here: That’s it.  That will open up as a big block of XML – simply save it to a file.  … more

  • Configuring a WCF Service to Run Via HTTPS

    Yesterday I wrote about how to wire up jQuery UI’s AutoComplete add-in to a WCF Service to create an autocomplete search/navigation control.  Today I deployed the resulting code to production but initially had some trouble getting things to work.  The only real difference between the two environments is that in production everything goes through HTTPS/SSL, so I figured that had to be the culprit.  A bit of searching led to this blog post describing WCF Bindings Needed for HTTPS.  I pretty much followed its advice exactly and things worked immediately.  Here’s my code: 1: <system.serviceModel> 2: <behaviors> 3: … more

  • Optimizing Data Feeds for Stir Trek

    I wrote a couple of weeks ago about using Visual Studio 2010’s Performance and Load Testing tools to analyze and correct some performance concerns with the Stir Trek Conference web site (which, by the way, is 2 weeks from today!).  I realized, though, that there are a bunch of mobile applications that are set up to use the site’s XML and JSON data feeds, and I hadn’t measured or tuned these at all.  It’s likely that more traffic on the day of the event will come via these feed URLs than through the actual web site, since I expect most attendees to be using their phones rather than full computers to access the site’s data (there being no WiFi at the theater, nor any tables on which … more

  • Creating an Autocomplete Redirect Navigation Control using jQuery UI

    On an application I’m working on, there’s was an ASP.NET DropDownList used for jumping to a particular account.  This, when enhanced with the AJAX Control Toolkit’s ListSearchExtender, provided an awesome user experience for quickly navigating to a particular account.  Just click the control, and either scroll, or better, type in the first few characters of the name of the account, and it was instantly selected.  Tab or enter from there, and you’re done. Unfortunately, as often happens, the applicability of this solution to application has changed with time.  Where once the DropDownList had one or two hundred records, now it has thousands, and unfortunately its existing … more

  • Creating a Bot for the Rock Paper Azure Contest

    The Windows Azure team is holding a contest, and The Code Project is helping to support it.  As part of this contest, you can get free Azure compute time by signing up with the code CP001 here.  The contest is simple – Rock, Paper, Scissors, with bots, and with 2 new moves: Dynamite, which beats Rock, Paper, or Scissors, and Water Balloon, which beats Dynamite.  The catch: you only have a limited supply of dynamite. Get Started Here: My bot placed 4th out of about 50 in last week’s contest (look for ardalis, the same as my twitter handle).  I’m hoping to be in the top 3 this week.  I thought I’d share some tips to help you get started. Countering an Expected … more

  • Create a Windows Service in .NET That Can Also Run as Console Application

    I’m creating a simple windows service using Visual Studio 2010 and .NET 4.  I want to be able to easily test it by simply running the resulting exe without the need to install the service.  I did some research on this topic and found three helpful articles: HybridService: Easily Switch between Console Application and Service (on CodeProject) Run Windows Service as a console program Creating a windows service in visual studio 2010 (in VB) I found that the first article was a bit more work than the second.  In the end, I pretty much combined the latter two articles’ approaches and created a simple template (in C#) that can be used as a starting point for any … more

  • Installing ASP.NET MVC 3 Tools Update

    Phil Haack has a post introducing the ASP.NET MVC 3 Tools Update that you probably should read.  This is my own experience installing the update and upgrading an existing MVC 3 project to use the new tooling.  First, you’ll want to install the MVC 3 Tools Update, using one of these options: Web Platform Installer for ASP.NET MVC 3 Tools Update Download Page for ASP.NET MVC 3 Tools Update And then you can read the Release Notes as well. I’m not going to talk about what’s new with the Tools Update, except to re-emphasize the fact that MVC 3 didn’t change at all – only the tooling has changed.  So, don’t worry about whether your application will need upgraded or will be … more

  • Real World Performance and the Stir Trek Web Site

    I recently joined the board responsible for organizing the Stir Trek conference in Columbus, Ohio.  This is a great conference I’ve spoken at the last couple of years that’s held in a movie theater on opening day of a new great movie.  The first one, two years ago, was held for the opening day of Star Trek (hence the name), and last year was Iron Man II.  This year’s movie is Thor, which looks to be pretty awesome.  Here are some badges promoting the event: You can find more here. The site opened for registration a few weeks ago and sold out very quickly.  However, there were some issues with the web site that were troubling.  The site basically died under … more

  • Introducing Pair Programming at Cinci Day Of Agile

    Last weekend I presented at the Cincinnati Day of Agile event on Introducing Pair Programming (see on slideshare).  The event was nearly sold out with about 240 people in attendance, a mix of devs and PMs.  The content and (other) speakers I thought were great – Phil and his team did a great job.  I took a few pictures during the event, which you can see below: Phil and Joel Semeniuk Brian Prince James Bender Jim Holmes   The event went very well, logistically, and the content was an interesting mix of topics.  It was interesting to me viewing agile practices through the lens of project managers, versus developers.  It was also interesting to hear … more

  • How To Fix Visual Studio File Templates

    When you create a new project in Visual Studio, it will usually include some files as part of the project.  Most of the time, these are pretty useless, but if it’s your first time working with said template, they may help you get going.  In VS2010, the Test Project, for example, has been improved over prior versions by eliminating a useless text file describing tests and a useless Manual Test file that I never once used.  It still includes a unit test file, which I think is fine, with the name that will never be correct, UnitTest1.cs (though I understand it would be a tough problem to guess a name that might be correct).  Let’s look at the default file created: I do … more

  • Visual Studio 2010 Unlimited Load Test Virtual Users

    You may have heard the recent announcement that Visual Studio 2010 Ultimate and MSDN subscribers now have access to the Visual Studio 2010 Load Test Feature Pack, which enables load testing of applications with unlimited virtual users.  Unfortunately, it’s not entirely clear at first, at least to me, how to get this to work if you’ve simply installed VS2010 Ultimate and now want to take advantage of this.  The first thing you will find in MSDN is the Visual Studio 2010 Load Test Feature Pack Deployment Guide, which is just a PDF: Of course, it’s a PDF wrapped in an EXE which only extracts but doesn’t open the resulting files.  One you’ve extracted it, there’s not a lot to … more

  • Complex Technical Demos Using Local Source Control

    Last summer at the Software Engineering 101 event put on by NimblePros in Cleveland, I saw Kevin Kuebler do a demo using git or Mercurial to iterate from phase of the project he was building to the next.  It worked amazingly well and I thought I would document how to set this up yourself, so that when you’re giving a technical presentation that involves a somewhat complex set of changes to a project, you can easily step through the updates without having to resort to a lot of on-stage typing, code snippets in multiple files, or switching between different projects/folders. For this example, I’m going to be using as a base a stock ASP.NET MVC 3 web project, but that choice was made … more

  • ASP.NET Tips and Tricks on dnrTV

    I recently did a show with Carl Franklin on ASP.NET Tips and Tricks, recorded for dnrTV.com.  In it, I go through a bunch of ASP.NET tips, from the oldies but goodies like Tracing and Caching, to some new ones like optimizing the performance of your ASP.NET MVC 3 applications.  The samples from the presentation are available for download here. more

  • What are you working on?

    If you ask a newly-hired developer this question while they are busy coding away on something, you’ll usually get an answer like “the Acme project.”  If that’s too obvious (after all, maybe that’s the only project this dev works on), then the answer might be “the new xyz feature” or “that abc bug.”  All of these are more-or-less valid responses, and depending on the scope of the response, they might be sufficiently clear to narrow down exactly how far along the dev is in getting the overall feature, story, or bug complete.  However, what if you come back in a few hours, or the next day, and ask the same question, and you get the exact same answer?  How do you know what … more

  • How to Record a Screencast with Expression Encoder 4

    I’m a huge fan of TechSmith Camtasia and use it for pretty much all of my screencasts.  However, I’m currently recording some presentations for the Code Project Agile Virtual Tech Summit that’s taking place next week, and the preferred capture program for the platform is Expression Encoder 4.  So, I figured while I’m learning how to do it, I might as well share how it works and how I find it compares with Camtasia. To get started, you should download and install Expression Encoder 4.  It’s a free product with the features needed to record your screen (and audio). Next, set your screen resolution to whatever you want to use for the recording.  Typically, to keep the file … more

  • Building a CachedRepository via Strategy Pattern

    In part one of this series, I introduced the CachedRepository pattern, and demonstrated how it can be applied through the use of simple inheritance to an existing Repository class.  This allows us to easily configure whether or not we want to use caching at the repository level through the use of an IOC Container like Structuremap.  However, using inheritance to achieve the behavior isn’t always desirable, since generally it’s better to use object composition if possible (this tends to result in more flexible designs). One benefit of the inheritance-based approach is its simplicity.  Both in terms of the code require and in terms of wiring up the interfaces and … more

  • Introducing the CachedRepository Pattern

    In this first part of a series on adding support for caching to the Repository Pattern, I’d like to show how to very simply control whether or not caching is performed on a per-repository basis through the use of an Inversion of Control Container.  In this case, I’ll be using StructureMap with ASP.NET MVC 3.  One of the primary goals of this implementation is to follow principles of object oriented design, in particular the Single Responsibility Principle and the Don’t Repeat Yourself Principle. To start, take a look at the MVC Music Store sample application.  The Jan 13 2011 release doesn’t include any usage of the Repository pattern, so the first thing we will do is add a … more

  • Improving ASP.NET MVC Application Performance at MVCConf

    Yesterday I gave a presentation to a little over 300 attendees of MVCConf on Improving ASP.NET MVC Application Performance.  There were some great responses on twitter and generally the ratings on SpeakerRate were positive, which was great because I was a bit worried going into the presentation, since I’d only committed to giving a talk at the conference a few day earlier.  I’m uploading the recording of the session to the MVCConf team now, and will add a link here when it’s available. Since the session was less than an hour, I had a couple of small things that I had wanted to touch on but didn’t have a chance, so I’ll mention those now.  I mentioned that having Caching … more

  • Starting and Stopping Services on Remote Servers using PowerShell

    This wraps up my mini-series on using PowerShell to help manage services running on multiple remote servers.  In my case, these scripts exist to make it easy for me to globally start and stop services on a number of web servers that are part of Lake Quincy Media’s AdSignia ad platform – you can read more about the message-based architecture we’re using here. I learned the basics of starting and stopping services here.  I adapted this so that I could store all of my server’s names in one PowerShell script, and call into it with another to list all of the running servers on remote servers using another PowerShell script.  I also made sure to make the ListServices.ps1 script use … more

  • List Services Running on Remote Servers

    As I wrote earlier, Lake Quincy Media’s AdSignia ad platform is utilizing services and a message-based architecture to decouple the system from the database and improve performance and reliability of the servers.  It’s proven useful to quickly work with the services across multiple nodes in the web cluster, and PowerShell is the obvious choice for automating some of these tasks.  When building up a collection of PowerShell scripts to support an application, I recommend that you store them in source control with the application itself.  It’s also worth following the Don’t Repeat Yourself principle, which you can do by using PowerShell functions to return results from one … more

  • Pass Results from One PowerShell Script To Another

    If you’re using PowerShell but want to keep your scripts DRY, you may want to factor common functions into their own scripts, and then call these scripts from multiple other scripts.   This is pretty easy to do.  For instance, if you have an array of values that you want to use as inputs for several scripts, you could create a file like this one: Colors.ps1 function Colors { return "Red", "White", "Blue" }   Now, to use this in another PowerShell script, you simply need to load it by using a . and then assign the result to a variable after a semicolon (;).  Like so: ListColors.ps1 . … more

  • Message-Based Architecture Goodness

    Recently at Lake Quincy Media we upgraded our logging system for the AdSignia ad platform so that it uses messaging rather than direct SQL database access.  This allows us to log much more detailed data, which we can then analyze, and also improves the performance of every ad request, since it eliminates a database call and replaces it with a local queue operation, which is much faster and less likely to suffer from any kind of contention.  Prior to this, the logging information was stored in the application’s only database, which also included all of the reporting tables, user data, advertiser, site, and advertisement records, etc.  The new design sets logging aside as a … more

  • MSBuild Invalid Character in Connection String with dbproj

    If you get this error: error MSB5016: The name “Intitial Catalog” contains an invalid character “ “. or something similar when trying to specify a connection string within an MSBuild task, like this one: <MSBuild Projects="src\Databases\Northwind.dbproj" Targets="Build;Deploy" Properties="TargetDatabase=Northwind;TargetConnectionString=&quot;Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;User Id=foo;password=bar;Enlist=False;&quot;" />     The issue is with the semicolons in the querystring.  If you replace them with %3B then the error goes away: … more

  • If Writing An Object That Is IDisposable, Don&rsquo;t Fail During Construction

    There’s a great pattern for ensuring that unmanaged resources are cleaned up in the .NET world.  It’s called the Disposable pattern and it applies to any resource that implements the IDisposable interface.  If you are writing an object that directly deals with unmanaged resources, such as files, database connections, network sockets, fonts, etc., then you are well advised to implement IDisposable and ensure your resources are cleaned up in your class’s Dispose() method.  Having followed this pattern, you’ll allow client code to clean up after itself by calling Dispose() as soon as they are finished with the resources your class uses, rather than waiting for the garbage … more

  • Getting Next Month in MSBuild

    I’m working on an application that needs to deploy a new database each month, in order to manage the large amount of data involved.  We’d like to automate this as much as possible, and since we already have the database schema in a Visual Studio 2010 database project, we figured the simplest thing would be to create an MSBuild task to do this, and then schedule it as part of our build server.  The format we want to use for the database name is simply “Databasename_201103” where the 201103 is next month’s year and month number (in this case, March 2011). So, to make the first part work is pretty simple.  You can pass in a parameter, TargetDatabase, to the Deploy task of a … more

  • Tip : Override ToString() in Objects

    Most of your domain objects should override ToString() for the simple reason that if you ever want to simply display the object’s state, you shouldn’t need to implement a custom formatter for it.  Furthermore, it’s well-known that the default System.Object implementation of .ToString(), which outputs the type’s name, is useless 99% of the time.  Thus, it’s generally a good idea to implement .ToString() on your classes that have some kind of state, and to have your implementation present at least the bare-bones information about this state.  If it’s a customer, maybe the .ToString() renders their customer ID and name.  If it’s an Order, maybe .ToString() renders the order … more

  • Live Essentials Evilness

    Hey, Microsoft, please stop trying to reset my home page and change my search preferences when I install the one tool from Live Essentials that I find useful, Live Writer (which is awesome, by the way).  I’m pretty sure my browser already has a preferences section wherein I can set my home page, and likewise my search engine of choice, and your presumption that by installing another tool that is related to my browser only inasmuch as it happens to use the Internet that somehow I want your advice on how I browse the Internet is annoying and insulting. Honestly, I don’t mind the “Help improve our stuff” box, but this dialog is evil because: 1. It shows up long after I’ve already … more

  • Where is Outlook 2010 Export

    In an example of extremely intuitive user experience, the latest version of Outlook has moved things around in the interests of ribbonizing everything.  This would be fine if in fact the trendy new ribbon UI was organized in a fashion that was, well, based on logic.  Sadly, at least in the case of Exporting data, this is not the case.  In previous versions of Outlook, one could navigate to File, Import/Export, and lo and behold, the Import and Export options did appear.  Not so Outlook 2010.  Clicking on the File tab, reveals this: Notice – nothing to do with Exporting.  You can click around on some of the other tabs.  Home, Send / Receive, hey, it … more

  • Entity Framework Invalid Object Name dbo.Albums

    Continuing in working with the MVC Music Store sample application, the next thing I ran into after installing the SQL database by hand, was an error on the home page saying: Invalid object name 'dbo.Albums'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Albums'. Source Error: Line 26: // the albums with the highest count Line 27: Line 28: return storeDB.Album Line 29: .OrderByDescending(a => … more

  • Database cannot be opened - version 655

    I’m working with the new MvcMusicStore sample application, and immediately I’m having trouble with the database.  When I try and open the .mdf file that’s in my App_Data, I’m presented with this error message: The database 'C:\DEV\SCRATCH\MVCMUSICSTORE-V2.0\MVCMUSICSTORE-COMPLETED\MVCMUSICSTORE\APP_DATA\MVCMUSICSTORE.MDF' cannot be opened because it is version 655. This server supports version 612 and earlier. A downgrade path is not supported. Could not open new database 'C:\DEV\SCRATCH\MVCMUSICSTORE-V2.0\MVCMUSICSTORE-COMPLETED\MVCMUSICSTORE\APP_DATA\MVCMUSICSTORE.MDF'. CREATE DATABASE is aborted. An attempt to attach an auto-named database for file … more

  • ViewBag does not exist in current context

    If you’re working with the ASP.NET MVC 3 MvcMusicStore demo and you run into the error message: The name ‘ViewBag’ does not exist in the current context It’s probably a sign that you are running on an older version of ASP.NET MVC (or a pre-release of MVC 3).  You can download the latest version of ASP.NET MVC 3 here.  This will install the Web Platform Installer (version 3) and will install ASP.NET MVC 3: Once MVC 3 (released version) is installed, recompile the MVC Music Store demo and your “ViewBag does not exist in current context” errors should disappear. Update: You may still see this error if you have an application that you built using … more

  • Creating a WHERE NOT EXISTS or WHERE NOT IN Query Using LLBLGen

    Consider a scenario where you have a many-to-many relationship, but it’s nullable.  For instance, maybe you have Articles and Categories (or Tags), and an Article can have 0 to N Categories/Tags.  Now, you want to pull in a set of Articles that are uncategorized.  Using SQL, you might write a query like this: SELECT a.ID, a.Name FROM Article a WHERE NOT EXISTS ( SELECT NULL FROM Article_Category_Xref acx WHERE acx.ArticleID = a.ID ) If you needed to do this using LLBLGen, and you didn’t know a better way, you could achieve this by first getting all of the tagged messages (easily done using an existing relationship), and … more

  • How Do I Use StructureMap with ASP.NET MVC 3

    As I write this, the best resource for official documentation on ASP.NET MVC 3 is of course MSDN.  You can also learn more about ASP.NET MVC 3 here.  However, neither of those mention how to properly set up an IOC Container (like StructureMap) with ASP.NET MVC 3.  After some searching, I was able to get things working using the RTM version of ASP.NET MVC 3.  Here’s what I had to do. Step One – Global.asax – Application_Start() First, you need to wire things up when your application starts.  You can put all of your container registration stuff right into your Global.asax, but that violates SRP.  I typically have a separate project in my solution devoted to … more

  • Sharp XV-Z9000U Projector Won&rsquo;t Power Up - Solution

    I have a fairly old projector that recently required a new bulb.  It’s a Sharp XV-Z9000U model, which has bulbs that last for something like 2000 hours, and the projector has a timer in it that starts warning you when you’re approaching this number.  Ultimately, when you’ve ignored the warnings long enough (because the existing bulb keeps on working fine), the projector starts to shut itself down.  This is either a ploy to ensure regular purchases of replacement bulbs (albeit not all that frequently), or is perhaps some kind of safety feature since maybe the bulbs explode spectacularly when they fail, so replacing them prior to that point is a good idea. In any case, I … more

  • Lessons Learned Performing Harry Potter Book Kata

    Last week at CodeMash I went through the Harry Potter Book Kata with Steve (@underwhelmed).  This is an interesting kata because it pretty much starts out very straightforward and things progress very quickly, and then you are faced with a brick wall in terms of how to proceed with the algorithm.  I recommend you give the exercise a try yourself before reading my tips, since they may be something of a spoiler for you (if you enjoy the puzzle-solving aspect of these exercises more than the repetition of known good solutions). Lesson One – Test The Small Stuff This isn’t really a spoiler, so I’ll start with it.  Steve and I tested all of the basic cases in the problem like 0 … more

  • How do I Change Where MSMQ Messages are Stored or Persisted?

    If you are using MSMQ, either directly or with the help of a package like NServiceBus, you may encounter errors if your server becomes overloaded with messages either due to high load or as a result of a failure in your message handling process.  If this happens, you may see exceptions like this one (ask me how I know this…): System.Messaging.MessageQueueException (0x80004005): Insufficient resources to perform operation. at System.Messaging.MessageQueue.SendInternal(Object obj, MessageQueueTransaction internalTransaction, MessageQueueTransactionType transactionType) at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.Send(TransportMessage m, String destination) in … more

  • Unit Test Naming Convention

    I’ve been writing tests and unit tests for quite a while, and naturally my personal preference for naming them has evolved somewhat with time.  Initially, I didn’t really know what I was doing and the default organization tended to be something like “given a class, Customer, all of the tests will go into a class called CustomerTests.”  This turned out, for me at least, to be less than ideal.  Later I learned more about BDD and specifications and I decided I could apply some of the same context and scenario information to my test organization as well.  Thus, I began striving to write my test classes such that each one described a particular scenario, and each test … more

  • Type was not registered in the serializer exception with NServiceBus

    If you encounter this error in your ASP.NET application after updating it while using NServiceBus: Server Error in '/' Application. Type DataPump.Infrastructure.Messages.MyMessage was not registered in the serializer. Check that it appears in the list of configured assemblies/types to scan. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Type DataPump.Infrastructure.Messages.MyMessage was not registered in the serializer. Check that it appears in the list of configured … more

  • Attempt was made to load an assembly from a network location

    If you see this bug while running an application that is referencing some third-party DLLs that you recently downloaded, your first thought should be “I need to Unblock the assembly I’m referencing!”  …an attempt was made to load an assembly from a network location… Windows, while trying to be helpful, will block downloaded files, causing .NET to fail when trying to load such DLLs.  The best way to fix this problem when you are downloading a package with many assemblies in it (e.g. NUnit, NServiceBus, etc.) is to Unblock the entire zip file before you unzip it.  Otherwise, every file will need to be Unblocked, which is a major inconvenience. To Unblock either the zip … more