Subscribe: Patrick Steele's .NET Blog
Added By: Feedage Forager Feedage Grade B rated
Language: English
android  code  data  it’s  i’m  mercurial  new  public  return  set public  set  simple  source  string  visual studio 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Patrick Steele's .NET Blog

Patrick Steele's .NET Blog

Implements ICodeWithDotNet


Why you need to learn async in .NET

Fri, 13 Apr 2012 21:52:06 GMT

I had an opportunity to teach a quick class yesterday about what’s new in .NET 4.0.  One of the topics was the TPL (Task Parallel Library) and how it can make async programming easier.  I also stressed that this is the direction Microsoft is going with for C# 5.0 and learning the TPL will greatly benefit their understanding of the new async stuff.  We had a little time left over and I was able to show some code that uses the Async CTP to accomplish some stuff, but it wasn’t a simple demo that you could jump in to and understand so I thought I’d thrown one together and put it in a blog post. The entire solution file with all of the sample projects is located here. A Simple Example Let’s start with a super-simple example (WindowsApplication01 in the solution). I’ve got a form that displays a label and a button.  When the user clicks the button, I want to start displaying the current time for 15 seconds and then stop. What I’d like to write is this: lblTime.ForeColor = Color.Red; for (var x = 0; x < 15; x++) { lblTime.Text = DateTime.Now.ToString("HH:mm:ss"); Thread.Sleep(1000); } lblTime.ForeColor = SystemColors.ControlText; (Note that I also changed the label’s color while counting – not quite an ILM-level effect, but it adds something to the demo!) As I’m sure most of my readers are aware, you can’t write WinForms code this way.  WinForms apps, by default, only have one thread running and it’s main job is to process messages from the windows message pump (for a more thorough explanation, see my Visual Studio Magazine article on multithreading in WinForms).  If you put a Thread.Sleep in the middle of that code, your UI will be locked up and unresponsive for those 15 seconds.  Not a good UX and something that needs to be fixed.  Sure, I could throw an “Application.DoEvents()” in there, but that’s hacky. The Windows Timer Then I think, “I can solve that.  I’ll use the Windows Timer to handle the timing in the background and simply notify me when the time has changed”.  Let’s see how I could accomplish this with a Windows timer (WindowsApplication02 in the solution): public partial class Form1 : Form { private readonly Timer clockTimer; private int counter;   public Form1() { InitializeComponent(); clockTimer = new Timer {Interval = 1000}; clockTimer.Tick += UpdateLabel; }   private void UpdateLabel(object sender, EventArgs e) { lblTime.Text = DateTime.Now.ToString("HH:mm:ss"); counter++; if (counter == 15) { clockTimer.Enabled = false; lblTime.ForeColor = SystemColors.ControlText; } }   private void cmdStart_Click(object sender, EventArgs e) { lblTime.ForeColor = Color.Red; counter = 0; clockTimer.Start(); } } Holy cow – things got pretty complicated here.  I use the timer to fire off a Tick event every second.  Inside there, I can update the label.  Granted, I can’t use a simple for/loop and have to maintain a global counter for the number of iterations.  And my “end” code (when the loop is finished) is now buried inside the bottom of the Tick event (inside an “if” statement).  I do, however, get a responsive application that doesn’t hang or stop repainting while the 15 seconds are ticking away. But doesn’t .NET have something that makes background processing easier? The BackgroundWorker Next I try .NET’s BackgroundWorker component – it’s specifically designed to do processing in a background thread (leaving the UI thread free to process the windows message pump) and allows updates to be performed on the main UI thread (WindowsApplication03 in the soluti[...]

Using hg bisect to hunt down bugs

Wed, 25 Jan 2012 03:32:18 GMT

The “bisect” command in Mercurial (git has it too) is a great way to quickly find which version of your code introduced a bug.  This post will show you how to use the bisect command along with handling a small “gotcha” I encountered while using it. I recently had to hunt down a bug in a very old version of an application.  While the application had gone through numerous releases after the bug had been introduced, nobody had noticed.  And as luck would have it, this particular bug was also in a section of code without unit tests – I’d have to load up the code in Visual Studio and run the app to verify the bug.  Since I tag each revision in Mercurial that is used to produce a release, I knew which revision the users first noticed the bug – and I knew the previous release didn’t have the bug.  The problem was that between the bad release and the good release was about 26 commits.  I used Mercurial’s bisect command to make locating the bug quicker. The first thing to do when doing a bisect is to ensure your working directory has no uncommitted changes.  The bisect command will perform an hg update automatically as it helps you zero in on the bug so it’s important you don’t have any uncommitted code. Next, I went to my working directory and initialized the bisect operation by running: hg bisect –r Now, I had to tell bisect which version was bad (where I knew the bug exists) and which version was good (where I know the bug does not exist).  In this case, revision 581 was good and revision 606 was bad: hg bisect –g 581 hg bisect –b 606 Mercurial responded: Testing changeset 593:e3c0018aef4d (25 changesets remaining, ~4 tests) 37 files updated, 0 files merged, 23 files removed, 0 files unresolved Mercurial had immediately updated my working directory to revision 593. This revision is about halfway between the good revision and the bad revision.  Here’s a graphical view of what I told Mercurial: I opened Visual Studio to load the project up and test the application.  I only have Visual Studio 2010 installed and this was a Visual Studio 2008 solution (see, I told you it was old).  I let Visual Studio perform the conversion.  I then ran the app and found that the bug exists in this version.  At this point, I needed to tell Mercurial that this version was bad.  At the command prompt I entered: hg bisect –b Mercurial’s response was an error: Testing changeset 587:d6e96f87a104 (12 changesets remaining, ~3 tests) abort: outstanding uncommitted changes Since 593 was now the first bad revision, Mercurial tried to update to a version between 593 and 581 but couldn’t because there were uncommitted changes.  Remember how I said this an old VS2008 solution?  Since I upgraded it to VS2010, the solution was changed and Mercurial stopped the automatic update that the bisect command wanted to do. For this situation, I didn’t care about the change to my working directory.  So I had to revert all of the changes before I could continue with the bisect: hg revert –a hg bisect –b Now the bisect worked and put me at revision 587, which is just about right in between the last known good version and the last known bad version: Testing this version in VS2010 (again, the VS2008 solution was updated to 2010), I found the bug didn’t exist.  So I went back to my command prompt, reverted my changes and marked this version as good: hg revert –a hg bisect –g   I was getting closer!  I’m now at revision 590 and the bug still existed.  I revert and mark it as bad: hg revert –a hg bisect –b   After this, Mercurial updated my working directory to revision 588.  I tested it and found the bug.  I did my revert and marked it bad: hg revert –a hg bisect –b Mercurial now reports 588 as the first revision where the bug appeared (since 587 was already marked good). T[...]

2012 Begins

Thu, 19 Jan 2012 22:42:03 GMT

It has become tradition for the past few years that my first blog post of the new year is to thank Microsoft for being recognized as an MVP.  This year is no different.  Once again, I’m honored to be recognized by Microsoft for my contributions to the community.  After visiting Redmond for the past 4 years, I’m going to be skipping the Summit this year.  I’ve got a client project that I really want to focus on and don’t want to push it out another week.

For 2012, I’ll continue to produce C# Corner articles for Visual Studio Magazine.  A big thanks to Eric Vogel who took over the web-only side of the C# Corner.  Between work, the print version of C# Corner and various family commitments, I could not continue producing the additional web-only articles.  I talked it over with my editor, Michael Desmond and he was totally understanding and found Eric to help me out.  Thanks Eric!

My interest in Android has not abated.  I’m still writing apps here and there for the platform.  I recently started looking in to the “android-binding” project (data binding for MVVM/MVP style apps) as well as “roboguice” (dependency injection for Android).  Both look like some really neat projects that will make developing Android apps easier.

After coming back from CodeMash 2012, I’m excited at the opportunity to implement some of what I learned.  If you have the opportunity to go to CodeMash, I urge you to attend!  Just be fast – this year, CodeMash sold out 1200 tickets in only 20 minutes!  Once you’ve attended one, you’ll know why!

Using WPF Converters to Affect Multiple Properties

Thu, 28 Jul 2011 19:01:49 GMT

I’m working on my first WPF application.  I’ve done a ton of reading on WPF and it’s helped me in my understandings of how WPF works.  So far, I’m really liking the data binding flexibility WPF gives you.  That, along with a very testable MVVM-based architecture, has made the experience a fun one! Yesterday, I came across a situation where I needed a single item from my view model (an enum value) to affect two properties on a  WPF element (the Foreground and Background colors of a DataGridCell).  I’m familiar with value converters, but they only convert to a single value.  I did some research on MultiValueConverters, but, as seasoned WPF developer Anne Marsan pointed out, they take multiple inputs but still only produce a single output.  How to proceed? NOTE: I’ve provided sample code in a BitBucket project here.  Each “attempt” that I detail below is tagged in the repository so you can easily see the implementations of each approach by switching your working directory to a certain tag. First Attempt (Tag: Attempt1) My first attempt was brute force and worked, but was messy – I simply created two value converters: both would take my enum, but one would return the background color and one would return the foreground color. [ValueConversion(typeof(CompareResult), typeof(String))] class ForeColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var result = (CompareResult)value; var ci = ColorInformation.FromResult(result); return ci.ForeColor; }   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } }   [ValueConversion(typeof(CompareResult), typeof(String))] public class BackColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var result = (CompareResult)value; var ci = ColorInformation.FromResult(result); return ci.BackColor; }   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } This was too much code duplication and I didn’t like it.  But, I kept it around it as my fallback measure if I couldn’t find a more elegant solution. Second Attempt (Tag: Attempt2) Why mess with converters?  Why not just expose the ForeColor and BackColor as properties on my view model.  Simple data binding would make this effortless. But I didn’t like this idea – it sounds too much like I’m mixing my UI and my view model.  The view model (in my opinion) should just represent the data to be displayed.  It’s up to the view to decide how this data should be displayed. Third Attempt (No Tag) Before I had talked with Anne Marsan about the MultiValueConverters, I thought about creating a multivalue converter that would take both the framework element I want to affect as well a[...]

Published My First Android Application!

Sat, 18 Jun 2011 21:36:14 GMT

While I’ve been playing around with Android development for a few months and I’ve started half-a-dozen various apps, I finally completed one and submitted it to the Android Market.  It’s a simple SQLite database app that contains the 2011 ferry schedule for the Star Line Mackinac Island Ferry.

Starline publishes a PDF with their complete schedule and it’s sitting in one of my Dropbox folders.  But viewing the schedule meant I had to open Dropbox, navigate to the folder then click on the PDF to download it. Then wait for the PDF to appear and navigate to the schedule and pinch/zoom to find the date range I’m looking for.

With my application, you simply pick your dock and then click on handy “Today” or “Tomorrow” buttons which will automatically calculate which date range you fall in.  Then you’ll get a listing of departure times both from the mainland and from the island.  You’re also free to pick any of the published date ranges to see times for the entire regular season.

If you’re planning a trip to Mackinac Island and plan to take the Star Line ferry, it’s a nice way to keep the schedule with you at all times.

Taking Android Emulator Screenshots WITHOUT Eclipse.

Sat, 18 Jun 2011 21:11:57 GMT

I’m working on an Android app and before publishing it to the Android Market, I needed some screenshots.  I assumed the emulator supported screenshots, but when I did a search for “android emulator screenshot”, most of the hits talked about how to do it from Eclipse.  I’m using IntelliJ IDEA Community Edition.  However, based on the descriptions, I understood what was going on.

The Eclipse plugin is talking to the emulator directly.  If you want to do that outside of Eclipse, you can do it using ddms – the Dalvik Debug Monitor.  Go to your Android SDK directory and look in the “tools” directory.  Run the “ddms.bat” file.  This will launch the Dalvik Debug Monitor.


From here, getting screenshots is easy.  Select the emulator that is currently running (in my case, “emulator-5556”).  Now start the screenshot application by either going to the “Device” menu and selecting “Screen capture…” or simply pressing CTRL+S.


Go back to the emulator, do whatever it is you need to do and when you’re ready for a screenshot, go back to the Device Screen Capture window and click “Copy” to save the screenshot to the clipboard or “Save” to open up a file browser where you can pick the location to save your image.  If you need more images, go back to the emulator, go to your next view/screen/whatever and then return to the Device Screen Capture window and click “Refresh” to update the image.

HOWTO: Change which “.testsettings” file Visual Stuido 2010 uses

Thu, 16 Jun 2011 15:57:50 GMT

I’m blogging this mainly for historical reasons.  I just spent over 30 minutes trying to figure this out.  Well, the first 10 or 15 minutes was getting code coverage enabled in Visual Studio 2010.  There’s plenty of coverage on that topic since it’s not as intuitive as it could be.  I’ll let Google handle that one.

Visual Studio 2010 allows you to create multiple “testsettings” files in your solution.  This allows you to set up customized configurations to control deployment, code coverage and a ton of other settings.  My solution has two settings (I think these are the defaults): “Local.testsettings” and “TraceAndTestImpact.testsettings”.  I configured Code Coverage in my “local” test settings.  I then ran my unit tests and went to check out the code coverage.

Visual Studio told me there was no code coverage data available – and prodded me to check the test results for errors.  I looked at the test results and didn’t see any errors but I did notice one thing.  The “Results Summary” for my test run displayed:

Test settings: TraceAndTestImpact

Ah ha!  So it’s not using my Local settings.  All I need to do is tell the unit tests to run with the “local”  testsettings file and I’ll be all set.  But how do I do that?  A few Google searches didn’t reveal much.  I finally (out of desperation), checked the ol’ drop down menus.  Under “Test” there is an option called “Select Active Test Settings”.  Under there, you can pick which settings file to use.



WPF: Simple “Busy” Overlay

Wed, 01 Jun 2011 02:29:28 GMT

I’m working on a WPF project that does some background processing which could take more than a few seconds.  Instead of a busy cursor, I want to give the user a simple “Please wait…” message via an overlay that appears on top of the form.  I found the solution in this stackoverflow question.  However, the solution presented there was an overview.  In this post I’ll show a complete example along with a downloadable sample project so you can play with it for yourself. Disclaimer First, a disclaimer: I’m currently working on my very first WPF application.  There may be an easier way to do this, but in building this solution from the stackoverflow question, it seemed pretty simple to me (hence the title).  Also, this form was using a Grid for layout.  I would think the general approach I use should work for other layouts, but I’ve only ever used this technique in a grid. This sample project is done using the MVVM pattern.  If you’re not familiar with this pattern, don’t worry.  This example is pretty straightforward so you should be able to get the general idea.  Also, if you’re using the MVVM pattern with your WPF (or Silverlight) apps, you should strongly consider using Simon Cropp’s Notify Property Weaver.  This little tool allows you to write regular auto-properties in your view models and it will “weave” the required IL into the generated property getters and setters to handle the INotifyPropertyChanged interface.  Highly recommended!  Initial Window Let’s start with a very simple window: This form collects a couple of pieces of information and has a link button to start the process.  The entire view model to run this form is show here (see Google and/or the source code if you need more information on the DelegateCommand): public class BusyViewModel : INotifyPropertyChanged { private ICommand doSomethingCommand;   public event PropertyChangedEventHandler PropertyChanged;   public string Item1 { get; set; } public string Item2 { get; set; } public List Results { get; set; }   public ICommand DoSomething { get { return doSomethingCommand ?? (doSomethingCommand = new DelegateCommand(LongRunningTask)); } }   private void LongRunningTask() { var results = Enumerable.Range(0, 12).Select(x => { Thread.Sleep(250); return "Result " + x; }).ToList(); this.Results = results; } }   If you clone my repository to your local machine and update your working directory to RevID 0 (the initial commit) you can run the app and see how clicking on the “DoSomething” link initiates the ICommand which runs a simple LINQ query to build up the sample results.  I stuck a Thread.Sleep in there to simulate load.  As a result, the window is unresponsive for about 3 seconds.  Let’s add a simple overlay to let the user know the application is busy. Improved UI First off, we want our view model to expose an “IsBusy” flag to indicate that it is busy doing something.  This is as easy as adding a property: public bool IsBusy { get; set; } And then we’ll put our long-running process into a background Task which will set the IsBusy flag when it starts and reset it when complete: private void LongRunningTask() { var task = new Task(ComputeResults); task.Start(); }   private void ComputeResults() { this.IsBu[...]

Clarification on Updating DefaultLocation in an MSI

Mon, 04 Apr 2011 17:36:10 GMT

Back in February, I did a blog post on how to change the default location for an Application installed via an MSI.  Thanks to a comment from Joe Marcelino, it wasn’t clear where to find the “DefaultLocation” field to change that.  Here’s a quick how-to on finding the field.

1. Right-click on your Setup project in Solution Explorer and select “View” and then “File System”:


2. In the window that opens up, under “File System on Target Machine”, select “Application Folder”:


3. Now, look at the “Properties” window and you’ll see the DefaultLocation property:


Now you can use any of the settings defined in MSDN to change where the application is installed.

Technorati Tags: ,

Android: Encapsulating Shared Preferences

Wed, 30 Mar 2011 02:01:02 GMT

The Android OS gives you a convenient way to save and load simple data (i.e. string, float, int, boolean and long) in the form of SharedPreferences.  The data is stored in a dictionary format that utilizes a key/value pair.  The “name” of the preferences is also supplied by your code.  In a lot of the samples you’ll find online, the name of the shared preferences and all of the keys are stored as constants at the top of the Activity class (or worse, the key names are copy/pasted throughout the code!).  I don’t like polluting my Activity classes with stuff like that so I’ve been encapsulating my preferences in their own class. Here’s a simple preferences class that exposes a couple of pieces of data – Full name and Age: package com.example;   import android.content.Context; import android.content.SharedPreferences;   public class AppPrefs { private final static String ACCOUNT_PREFS_NAME = "prefs"; private final static String FULLNAME_KEYNAME = "FULLNAME_KEY"; private final static String AGE_KEYNAME = "AGE_KEY";   private final Context context; private String fullName; private int age;   public AppPrefs(Context ctx) { this.context = ctx; SharedPreferences prefs = context.getSharedPreferences(ACCOUNT_PREFS_NAME, Context.MODE_PRIVATE); fullName = prefs.getString(FULLNAME_KEYNAME, "unknown"); age = prefs.getInt(AGE_KEYNAME, 18); }   public String getFullName() { return fullName; }   public void setFullName(String name) { fullName = name; }   public int getAge() { return age; }   public void setAge(int number) { age = number; }   public void Save() { SharedPreferences prefs = context.getSharedPreferences(ACCOUNT_PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit(); edit.putString(FULLNAME_KEYNAME, fullName); edit.putInt(AGE_KEYNAME, age); edit.commit(); } } You can see it’s a very simple class, but it hides all the key names within the class.  The main consumer of this class doesn’t need to know the name of the keys or even how the data is stored.  By simply using the get/set methods and the Save() method, the Activity can concentrate on what it was designed to do.  Imagine if we need to change where we’re storing the data?  Maybe we’re moving from SharedPreferences to a SQLite database?  In that case, we simply change the preferences class and the Activity won’t need any modifications. I haven’t done a lot of Android programming yet, but so far, this technique has been working out well.  I’ve created a sample application based on IntelliJ IDEA 10 using this technique on my bitbucket account. Technorati Tags: Android,IntelliJ[...]

.hgignore file for IntelliJ IDEA Development

Tue, 29 Mar 2011 18:18:54 GMT

Every time I start a new project in Visual Studio, I almost always put it under Mercurial source control – even a small demo project.  If the project becomes serious enough, I’ll create a private repository in Bitbucket and maintain it there.  After I initialize my Mercurial repository, the first thing I do is grab Nino’s .hgignore file for Visual Studio.  It’s a great time-saver.

I’ve been playing around with Android development a bit lately using JetBrains IntelliJ IDEA 10.  Like my Visual Studio projects, I also create a local Mercurial repository for my Android code.  But since I’m new to Android development, there were a bunch of files (other than the source code I was writing!) and I didn’t know if these should be stored in my source code control system or not.

Luckily, JetBrains has a KB article on the subject: How to manage IDEA projects under Version Control Systems.  Using this info, I’ve created a stock .hgignore file I use for all of my Android projects.  Here’s the contents:


I hope this useful for you.  If you know of any changes I could make, let me know!

Technorati Tags: ,,

Automapper: Handling NULL members

Fri, 18 Mar 2011 16:53:21 GMT

A question about null members came up on the Automapper mailing list.  While the problem wasn’t with Automapper, investigating the issue led to an interesting feature in Automapper. Normally, Automapper ignores null members.  After all, what is there really to do?  Imagine these source classes: public class Source { public int Data { get; set; } public Address Address { get; set; } }   public class Destination { public string Data { get; set; } public Address Address { get; set; } }   public class Address { public string AddressType { get; set; } public string Location { get; set; } } And imagine a simple mapping example with these classes: Mapper.CreateMap();   var source = new Source { Data = 22, Address = new Address { AddressType = "Home", Location = "Michigan", }, };   var dest = Mapper.Map(source); The variable ‘dest’ would have a complete mapping of the Data member and the Address member. But what if the source had no address? Mapper.CreateMap();   var source = new Source { Data = 22, };   var dest = Mapper.Map(source); In that case, Automapper would just leave the Destination.Address member null as well.  But what if we always wanted an Address defined – even if it’s just got some default data?  Use the “NullSubstitute” option: Mapper.CreateMap() .ForMember(d => d.Address, o => o.NullSubstitute(new Address { AddressType = "Unknown", Location = "Unknown", }));   var source = new Source { Data = 22, };   var dest = Mapper.Map(source); Now, the ‘dest’ variable will have an Address defined with a type and location of “Unknown”.  Very handy! Technorati Tags: .NET,Automapper,NULL[...]

Moving a local Mercurial Repository to Bitbucket

Thu, 24 Feb 2011 16:15:10 GMT

I recently got a new laptop.  Part of the migration process was to move a few local Mercurial repositories into Bitbucket.  Since these are just “playing around” repositories, they’ll be private, but the beauty of Bitbucket is that you get unlimited private repositories.  This allows me to keep all of my little pet projects “up in the cloud” and it’s one less thing to migrate the next time I get a new machine. The process couldn’t be simpler: 1. Log in to your Bitbucket account. 2. Under “Repositories”, select “Create New Repository”. 3. Enter the details for your repository.  Make sure you check the “Private” checkbox if you want this private. Once your new repository is created, grab the URL (either the HTTPS one or the SSH one – depending on what you’re using) and copy it to the clipboard.  Now go to your local mercurial repository and enter: hg push [repositoryURL] Where [repositoryURL] will be the URL of your new repository (that’s why you copied it to the clipboard!). The one last thing you’ll want to do is change the default path to your repository to be the Bitbucket repository.  So the next time you need to push changes up to Bitbucket, it will know where to go.  To do this, edit the “hgrc” file located in the .hg directory of your repository.  If there’s not a “[paths]” section, add one and then add a “default” key with the URL of your new repository (again, the clipboard comes in handy!): [paths] default = https://... Done! Technorati Tags: Mercurial,Bitbucket[...]

Changing the Default Install Location of an MSI

Thu, 24 Feb 2011 02:25:13 GMT

A few months ago, I had to tweak an MSI installer.  It was installing into a specific directory (named the same as the application) underneath Program Files.  Since the location of Program Files can change from machine to machine, the MSI has a special token you can use for Program Files (as well as for the application name).  So the current value for “DefaultLocation” of the Application Folder was:


During installation, these tokens would be replaced by the actual location based on the current machine.

I needed to change this to a specific folder underneath the users My Documents directory.  I poked around the help file and I could not find where these special tokens (like “[ProgramFilesFolder]”) were defined.  Obviously, there must be some specific set of values that are available and I’m sure My Documents is one of them.

I finally found them documented so I’m posting the link here.  Hopefully, it will help someone else out.  Not sure where I found this link…

System Folder Properties

For me, it was as easy as changing the DefaultLocation to:


Technorati Tags: ,

UPDATE: Finding the DefaultLocation property.

Setting up Windows Live Writer for

Fri, 18 Feb 2011 15:28:13 GMT

Once again, I’m on a new laptop and have forgotten how to set up Windows Live Writer to post to my account.  Thanks to Bil Simser, I’m up and running now.

I’ve found that a number of applications these days allow you to “export” your settings (FileZilla, Firefox plugins, bookmarks, etc…).  I think more companies should be doing this.  It makes migrating to a new machine a whole lot easier!

Using Lambdas for return values in Rhino.Mocks

Thu, 03 Feb 2011 02:45:31 GMT

In a recent StackOverflow question, someone showed some sample code they’d like to be able to use.  The particular syntax they used isn’t supported by Rhino.Mocks, but it was an interesting idea that I thought could be easily implemented with an extension method. Background When stubbing a method return value, Rhino.Mocks supports the following syntax: dependency.Stub(s => s.GetSomething()).Return(new Order()); The method signature is generic and therefore you get compile-time type checking that the object you’re returning matches the return value defined by the “GetSomething” method. You could also have Rhino.Mocks execute arbitrary code using the “Do” method: dependency.Stub(s => s.GetSomething()).Do((Func) (() => new Order())); This requires the cast though.  It works, but isn’t as clean as the original poster wanted.  They showed a simple example of something they’d like to see: dependency.Stub(s => s.GetSomething()).Return(() => new Order()); Very clean, simple and no casting required.  While Rhino.Mocks doesn’t support this syntax, it’s easy to add it via an extension method. The Rhino.Mocks “Stub” method returns an IMethodOptions.  We just need to accept a Func and use that as the return value.  At first, this would seem straightforward: public static IMethodOptions Return(this IMethodOptions opts, Func factory) { opts.Return(factory()); return opts; } And this would work and would provide the syntax the user was looking for.  But the problem with this is that you loose the late-bound semantics of a lambda.  The Func is executed immediately and stored as the return value.  At the point you’re setting up your mocks and stubs (the “Arrange” part of “Arrange, Act, Assert”), you may not want the lambda executing – you probably want it delayed until the method is actually executed and Rhino.Mocks plugs in your return value. So let’s make a few small tweaks: public static IMethodOptions Return(this IMethodOptions opts, Func factory) { opts.Return(default(T)); // required for Rhino.Mocks on non-void methods opts.WhenCalled(mi => mi.ReturnValue = factory()); return opts; } As you can see, we still need to set up some kind of return value or Rhino.Mocks will complain as soon as it intercepts a call to our stubbed method.  We use the “WhenCalled” method to set the return value equal to the execution of our lambda.  This gives us the delayed execution we’re looking for and a nice syntax for lambda-based return values in Rhino.Mocks. Technorati Tags: .NET,Rhino.Mocks,Mocking,Extension Methods[...]

Xml Serialization and the [Obsolete] Attribute

Tue, 01 Feb 2011 02:44:42 GMT

I learned something new today: Starting with .NET 3.5, the XmlSerializer no longer serializes properties that are marked with the Obsolete attribute.  I can’t say that I really agree with this.  Marking something Obsolete is supposed to be something for a developer to deal with in source code.  Once an object is serialized to XML, it becomes data.  I think using the Obsolete attribute as both a compiler flag as well as controlling XML serialization is a bad idea. In this post, I’ll show you how I ran into this and how I got around it. The Setup Let’s start with some make-believe code to demonstrate the issue.  We have a simple data class for storing some information.  We use XML serialization to read and write the data: public class MyData { public int Age { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List Hobbies { get; set; }   public MyData() { this.Hobbies = new List(); } } Now a few simple lines of code to serialize it to XML: static void Main(string[] args) { var data = new MyData {    FirstName = "Zachary", LastName = "Smith", Age = 50, Hobbies = {"Mischief", "Sabotage"}, }; var serializer = new XmlSerializer(typeof (MyData)); serializer.Serialize(Console.Out, data); Console.ReadKey(); } And this is what we see on the console: 50 Zachary Smith Mischief Sabotage   The Change So we decided to track the hobbies as a list of strings.  As always, things change and we have more information we need to store per-hobby.  We create a custom “Hobby” object, add a List to our MyData class and we obsolete the old “Hobbies” list to let developers know they shouldn’t use it going forward: public class Hobby { public string Name { get; set; } public int Frequency { get; set; } public int TimesCaught { get; set; }   public override string ToString() { return this.Name; } } public class MyData { public int Age { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [Obsolete("Use HobbyData collection instead.")] public List Hobbies { get; set; } public List HobbyData { get; set; }   public MyData() { this.Hobbies = new List(); this.HobbyData = new List(); } } Here’s the kicker: This serialization is done in another application.  The consumers of the XML will be older clients (clients that expect only a “Hobbies” collection) as well as newer clients (th[...]

Welcome 2011

Mon, 31 Jan 2011 21:50:35 GMT

About this time last year, I wrote a blog post about how January of 2010 was almost over and I hadn’t done a single blog post.  Ugh…  History repeats itself. 2010 in Review If I look back at 2010, it was a great year in terms of technology and development: Visited Redmond to attend the MVP Summit in February.  Had a great time with the MS product teams and got to connect with some really smart people. Continued my work on Visual Studio Magazine’s “C# Corner” column.  About mid-year, the column changed from an every-other-month print column to an every-other-month print column along with bi-monthly web-only articles.  Needless to say, this kept me even busier and away from my blog. Participated in another GiveCamp!  Thanks to the wonderful leadership of Michael Eaton and all of his minions, GiveCamp 2010 was another great success.  Planning for GiveCamp 2011 will be starting soon… I switched to DVCS full time.  After years of being a loyal SVN user, I got bit by the DVCS bug.  I played around with both Mercurial and Git and finally settled on Mercurial.  It’s seamless integration with Windows Explorer along with it’s wealth of plugins made me fall in love.  I can’t imagine going back and using a centralized version control system. Continued to work with the awesome group of talent at SRT Solutions.  Very proud that SRT won it’s third consecutive FastTrack award! Jumped off the BlackBerry train and enjoying the smooth ride of Android.  It was time to replace the old BlackBerry Storm so I did some research and settled on the Motorola DroidX.  I couldn’t be happier.  Android is a slick OS and the DroidX is a sweet piece of hardware.  Been dabbling in some Android development with both Eclipse and IntelliJ IDEA (I like IntelliJ IDEA a lot better!).   2011 Plans On January 1st I was pleasantly surprised to get an email from the Microsoft MVP program letting me know that I had received the MVP award again for my community work in 2010.  I’m honored and humbled to be recognized by Microsoft as well as my peers! I’ll continue to do some Android development.  I’m currently working on a simple app to get me feet wet.  It may even makes it’s way into the Android Market. I’ve got a project that could really benefit from WPF so I’ll be diving into WPF this year.  I’ve played around with WPF a bit in the past – simple demos and learning exercises – but this will give me a chance to build an entire application in WPF.  I’m looking forward to the increased freedom that a WPF UI should give me. I plan on blogging a lot more in 2011! Technorati Tags: Android,MVP,Mercurial,WPF,SRT,GiveCamp[...]

Guaranteed order in a foreach loop

Thu, 18 Nov 2010 18:46:55 GMT

I was always under the impression that the order items are returned via a foreach loop is not guaranteed.  For the most part, that is correct.  However, it’s not 100%.

I was working on some code today and there was a regular for loop that Resharper offered to convert to a foreach loop.  The for loop was moving through an array one item at a time (starting at zero).  Since I (incorrectly) assumed the order for a foreach loop was not guaranteed, I was surprised by Resharper’s suggestion.

So I decided to check the C# spec and see what it had to say.  Sure enough, I was wrong!  Check out section 8.8.4 on the foreach statement.  There’s this following tidbit:

The order in which foreach traverses the elements of an array is as follows: For single-dimensional arrays, elements are traversed in increasing index order, starting with index 0 and ending with index Length – 1. For multi-dimensional arrays, elements are traversed such that the indices of the rightmost dimension are increased first, then the next left dimension, and so on to the left.

So Resharper was right.  I changed the code and its much cleaner and easier to read!

EDAMLibrary : Evernote Library for C#

Sat, 07 Aug 2010 02:05:07 GMT

I recently pushed a library onto bitbucket.  It’s used for integrating with the popular note-taking, cloud-syncing, capture application Evernote.  I started using Evernote in February of this year and I’m addicted to it now.  I scan and tag tons of information and have it easily available at all times.  My data is sync’d to the cloud and accessible via a Windows client, the web and various mobile platforms (Blackberry, iPhone, Android).

While Evernote provides an API for accessing the data, it has a few organization issues that need to be overcome before you can use it.  To make it easier for those just wanting to play around with Evernote, I combined everything provided by Evernote into a single library.

And remember, if you want to develop something that integrates with Evernote, you’ll have to request an API key.  It’s a pretty simple process that just takes a few minutes.

Technorati Tags: ,,,