.NET 4 Baby Steps - Part I: TimeSpan
Welcome to part one of a new series of blog posts which will cover what is new in .NET 4. To be different I am not looking at the big features, like WF 4 or the super cool parallel stuff. This series will cover the smaller features, like new methods on existing classes or whole new classes which have been added. As with all series I do, you can see the rest of the post in the series on the series index.
We’ll start off with TimeSpan, which has been around since .NET 1.0 and represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. So what is new in TimeSpan for .NET 4?
Parse & TryParse
Parse & TryParse are methods which have been around since the beginning and let you input a string in a specific format [-][d’.’]hh’:’mm’:’ss[‘.’fffffff]. and get a TimeSpan object back. For example:
TimeSpan oneFranctionSecond = TimeSpan.Parse("0.00:00:00.1"); TimeSpan oneHour = TimeSpan.Parse("1:00"); TimeSpan oneThousandDaysPast = TimeSpan.Parse("-1000.00:00"); Console.WriteLine(oneFranctionSecond); Console.WriteLine(oneHour); Console.WriteLine(oneThousandDaysPast);
What is new in parsing? The ability to add in culture information through IFormatProvider. Why is this important? Because not everyone formats numbers the same. For example:
CultureInfo us = CultureInfo.GetCultureInfo("en-us"); // America CultureInfo rm = CultureInfo.GetCultureInfo("rm"); // No idea, but it has my initials ;) CultureInfo za = CultureInfo.GetCultureInfo("en-za"); // South Africa string usResult = string.Format(us, "{0:N}", 100000); string rmResult = string.Format(rm, "{0:N}", 100000); string zaResult = string.Format(za, "{0:N}", 100000); Console.WriteLine("America:\t {0}", usResult); Console.WriteLine("RM:\t\t {0}", rmResult); Console.WriteLine("South Africa:\t {0}", zaResult);Produces:

See how all three locations have different formats, and this is important because the old methods couldn’t cope with these differences in numbers - they could only accept a single specific format.
Now we can do the following:
CultureInfo us = CultureInfo.GetCultureInfo("en-us"); // America CultureInfo ru = CultureInfo.GetCultureInfo("ru-RU"); // Russia TimeSpan oneFranctionSecondUS = TimeSpan.Parse("6:12:14:45.3448", us); TimeSpan oneFranctionSecondRU = TimeSpan.Parse("6:12:14:45,3448", ru); Console.WriteLine(oneFranctionSecondUS); Console.WriteLine(oneFranctionSecondRU);
Note the comma in the Russian formatting, if you tried this in .NET 3.5 or before you would’ve gotten a FormatException but now it works!
ParseExact & TryParseExact
These are two brand new methods which let us specify the format string to use. Until now we have had to make sure we complied with: [-][d’.’]hh’:’mm’:’ss[‘.’fffffff].
Now we do not need to comply with a single format. We have two options with the format string either a build in one or a custom one. The built in ones are:
- c/t/T : These three do the same and this is what we are used to currently, namely: [-][d’.’]hh’:’mm’:’ss[‘.’fffffff].
- Examples:
- TimeSpan.Zero -> 00:00:00
- New TimeSpan(0, 0, 30, 0) -> 00:30:00
- New TimeSpan(3, 17, 25, 30, 500) -> 3.17:25:30.5000000
- Examples:
- g: The cultural sensitive short format. This is basically the same as c but the format provider supplied will be respected where c ignores it: [-][d’:’]h’:’mm’:’ss[.FFFFFFF].
- Examples:
- New TimeSpan(1, 3, 16, 50, 500) -> 1:3:16:50.5 (en-US)
- New TimeSpan(1, 3, 16, 50, 500) -> 1:3:16:50,5 (fr-FR)
- New TimeSpan(1, 3, 16, 50, 599) -> 1:3:16:50.599 (en-US)
- New TimeSpan(1, 3, 16, 50, 599) -> 1:3:16:50,599 (fr-FR)
- Examples:
- G: The cultural sensitive long format in which there is no optional items, except the negative symbol: [-]d’:’hh’:’mm’:’ss.fffffff.
- Examples:
- New TimeSpan(18, 30, 0) -> 0:18:30:00.0000000 (en-US)
- New TimeSpan(18, 30, 0) -> 0:18:30:00,0000000 (fr-FR)
We also have custom ones now, so we can really tweak it and this will be great for interoperability. I am not going to list all the parts as there is a lot, but every individual component is covered. Some examples of what we can now do are:
TimeSpan oneFranctionSecond = TimeSpan.ParseExact("1", "%F", CultureInfo.CurrentCulture); TimeSpan oneMinuteThirtySeconds = TimeSpan.ParseExact("1:30", @"%m\:%s", CultureInfo.CurrentCulture); TimeSpan oneDay = TimeSpan.ParseExact("1", "%d", CultureInfo.CurrentCulture); TimeSpan oneDayAndTwoHours = TimeSpan.ParseExact("1=2", @"%d\=%h", CultureInfo.CurrentCulture); Console.WriteLine(oneFranctionSecond); Console.WriteLine(oneMinuteThirtySeconds); Console.WriteLine(oneDay); Console.WriteLine(oneDayAndTwoHours);Which produces:

.NET 4 Baby Steps: Series Index
This page lists all the posts in the series.
- Part I: TimeSpan
- Part II: String
- Part III: Enum
- Part IV: Observer
- Part V: Lazy
- Part VI: SortedSet
- Part VII: Caching
- Part VIII: Enumerate Directories and Files
- Part IX: Stream
- Part X: Location, Location, Location
- Part XI: Special Folders
- Part XII: Numbers
- Part XIII: Tiny Steps - the place for things too small to get their own post
Writing JavaScript Easier with jQuery and Visual Studio 2010!
My first time presenting at DevDays was a great experience with me presenting in the community slot. I told the attendees of my session that they were the smart ones because being at the end of the day, only the dedicated people were left and those dedicated people got two presentations for the price of one timeslot.
The session itself covered how writing JavaScript easier with jQuery and Visual Studio 2010 which you can see below. Now the slides below are not being done using some special PowerPoint to web tool, but are HTML which uses jQuery. Using the same technology as I was presenting on and building it in Visual Studio 2010 really highlighted how powerful and easy this was to do. To navigate the slides click the grey dots at the top or click on the slide and press = to go forward and – to go back.
They are a little wide for the website, so to see them in a new window click here
The demo used jQuery and Visual Studio 2010 to clean up the page, and then connect to StackOverflow to pull down my stats and display them to the audience. The completed demo code (which is not included above, so the demo page won’t work) is as follows (this goes in the HEAD tags in demo .html page):
<script src="jQuery/jquery-1.4.2.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("#DemoButton").click(gapSO); }); function gapSO(e) { ///<summary>Gets and parses Stack Overflow Points</summary> var sourceDiv = $(this); var replacementText = "I have "; var stackOverflowURL = "http://stackoverflow.com/users/flair/53236.json"; sourceDiv.html("Loading..."); $.getJSON(stackOverflowURL, function (data) { replacementText += data.reputation + " points and " + data.badgeHtml + " badges on StackOverflow"; sourceDiv.html(replacementText); }); }; </script>
Upgrading to SharePoint 2010: In the field experience
Last week I was able to upgrade BB&D’s internal intranet site from SharePoint 2007 to SharePoint 2010! So you can properly understand what happened let me cover a little bit about the intranet first. Our intranet is a small deployment, just a single server deployment however it is kept up to date with technology so it is running on SQL Server 2008 with SP1, Windows 2008 R2 on a 64bit virtual machine. We have also not gone with heavy customisation, rather focusing on small tweaks and adjustments. A good example is we do not have a customised master page but rather use the theme options to get the colour scheme we want.
The first step I did was to download the pre-requisites for SharePoint 2010, and using the option on the installer this was a breeze. I’ve seen this before with Dynamics CRM and once again I am impressed by how a very simple feature makes such a big difference. Next step was the install, which was pain less and quick.
Once installed the configuration manager had to run and this is where I had two issues. The first problem was that I got stuck on task 1! The cause here is that a dialog box had appeared behind the main window (telling me to do the same to all servers in the farm) and won’t go until I clicked OK. This annoying little bug cost me a few minutes.
The second issue was that the SharePoint 2010 install needs to do some Active Directory queries and this meant my user account was not good enough. Not having a good enough user means that the installer produces a very unhelpful error at step 3:
System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Microsoft.SharePoint.Utilities.SPUtility.GetUserPropertyFromAD(SPWebApplication webApplicaiton, String loginName, String propertyName)
at Microsoft.SharePoint.Administration.SPManagedAccount.GetUserAccountControl(String username)
at Microsoft.SharePoint.Administration.SPManagedAccount.Update()
at Microsoft.SharePoint.Administration.SPProcessIdentity.Update()
at Microsoft.SharePoint.Administration.SPApplicationPool.Update()
at Microsoft.SharePoint.Administration.SPProcessIdentity.UpgradeToV4ManagedAccount()
at Microsoft.SharePoint.Administration.SPConfigurationDatabase.ResolveObjectAndClassVersions(SPLog log)
at Microsoft.SharePoint.Upgrade.SPConfigurationDatabaseSequence2.Upgrade()
at Microsoft.SharePoint.Upgrade.SPUpgradeSession.Upgrade(Object o, Boolean bRecurse)
It took ages to figure this out, mostly because it is not a documented requirement. To get the correct permissions you need to get a domain admin to do the following on the domain controller:
- Open up Active Directory Users and Computer.
- Select Advanced Features from the View menu. Failing to do this means that the tab in step four won’t be visible.
- Right-click the your AD account and select Properties.
- Select the Securities Tab.
- Select Authenticated Users in the Group or user names field.
- Allow Full permissions in the Permissions for Account Operators.
- Repeat this process for any SharePoint service accounts you may have created.
- Next make sure this change replicates to all domain controllers.
- Now connect to your SharePoint server, and open the command prompt (cmd.exe) and type gpupdate /force. This will force the changes to the machine as it may have a cached version.
- Finally reboot the SharePoint server and start the configuration wizard again.
After all that was done the configuration wizard completed and the upgrade process started in central admin. The upgrade process also took a while to do, but once done everything just worked.
Lastly we applied some theme tweaks and a quick run through of testing it and it was done. One thing that is important to remember about this process is that the entire time it was happening the current intranet was done so plan your deployment accordingly. This is easily the best experience I’ve ever had installing or upgrading SharePoint and shows that the product is maturing.
Find Results Tweak - Now with less suck
I posted the other day about a Visual Studio add-in which I developed. When developing it, I used the add-in model which has a nasty side effect, it needs to be installed with a MSI. Visual Studio 2010 can also be extended with packages and these can be deployed using the VSIX format.
What is this magical new VSIX format? It is basically a ZIP file which contains everything you need plus a manifest which tells VS how to use it. What makes this much better is that VS handles the install itself, so no MSI is needed. It is also then listed in the Extension Manager and so can take advantage of the features there by being disabled/uninstalled easily, not that you would want to.
A great side effect of this is that the new extension model let me add a little more error handling to the tool to help out debugging it. To get the new version go to http://findresultstweak.codeplex.com
Death of a SharePoint Developer
I have had to explain many times in the last year why I, a normal developer, am involved with Information Worker which is (mostly) a SharePoint group? I am involved because I believe that the idea of a SharePoint Developer is a fast dying one and soon, people who call themselves a SharePoint Developer will be using it just as a way to justify higher consulting costs more than anything else.
I do not think this is because SharePoint usage is dying, rather the growth (maturity and adoption) of SharePoint is causing SharePoint developers to die off. This is not because SharePoint is so user friendly we no longer need custom code, because we still need custom code in SharePoint. The two reasons for my thinking this is based on two questions, “What SharePoint development really is?” and secondly “What Microsoft is doing about SharePoint development?”.
What is SharePoint development really? In SharePoint versions past (2007 and before) you would develop code for SharePoint using development concepts unique to SharePoint. Now that SharePoint has matured, development of the code for SharePoint involves concepts that are universal to development. There are two examples which come to mind which highlight the maturity of development concepts. First is web parts, which are now the same as ASP.NET web parts, and secondly is web services (and OData if you have SharePoint 2010). Both of these concepts are the exact same as used by many other products made by Microsoft and other companies. For example if you understand how to get data from Twitter, with OData in SharePoint 2010 you will understand how to get data from SharePoint. Yes, you will have some specific bindings/API’s/code that are SharePoint specific but the concepts, which is the difficult part to learn, are the same.
I mentioned two questions and the second is about Microsoft and it’s strategy for SharePoint development, in particular their 2010 strategy (Visual Studio 2010 + SharePoint 2010). A SharePoint developer used to have to go and download special files, install them, fixed issues, try installing again, fix more issues, have special machines or virtual machines to run SharePoint on and so on. The actual process of just writing code for SharePoint meant that you became elite because you had to go through a ritual of fire before you could start. Microsoft have really made SharePoint 2010 development simple and more importantly easy to start with, both by making SharePoint run natively on Windows 7 and also by including everything you need for development within Visual Studio 2010 from day one. It is as hard start wring code for SharePoint now as it is to make a WPF application!
What I am trying to convey is that previously a SharePoint developer had “paid their school fees” by learning so much that was so specific to the process of SharePoint development that they actually had earned a special title. Now that all those barriers have been removed, the title of SharePoint developer no longer applies, we are all just developers now!
Tweaking the Find Results window in Visual Studio 2010
Visual Studio is filled with goodness and happiness and a lot of that is available for tweaking, so you can get the maximum goodness, via the Tool -> Options menu. One of the things which doesn’t have any visible options is the formatting of the way the results are displayed:
The problem, as indicated above, is a ton of white space, long file paths, no column information etc… Wouldn’t it be great to tweak how that can be displayed? Thankfully Sara Ford found a way to do exactly that via the registry. So you could tweak it to actually display the way you want it!
In my tweaked way it is far more condense with just the filename (no more path), less whitespace (since I am showing only a summary of results) and I also included the column info. The problem is that editing the registry is not user friendly :( This gave me a chance to write my first Visual Studio add-in, which gives you an option inside Visual Studio to set it.
What is really nice is that while you configure the format, the preview window will update and show you how it looks so you do not get any surprises when you save it! If you would like to find out more about it you can go to the site on CodePlex at http://findresultstweak.codeplex.com/
Installing TFS 2010 Basic on a Laptop
I decided that I would like show how easy it is to install TFS 2010 on a laptop in an upcoming presentation, but I also want to use that TFS installation for demo’s which is a worry – what happens if the install fails? So what I decided to do was create a video of me installing TFS, this way I can show the video and not worry about my demos not working because of some demo failure. As I am such as nice guy, I decided to share it with everyone on YouTube, so here is the video:
Article in the BB&D Newsletter
After being at BB&D for almost two years, I finally managed to get an article in the BB&D newsletter! The article is about my trip in January to Canada and US for the ALM Rangers work! This was a different experience than writing for my blog, because this had to go through an editor and a copywriter before it was included. They made enough changes to the article that reading it myself, it felt strange because it sounds like me, just a different me. This article will now be shipped off to the BB&D offices around the world so that should be very exciting!
Click the image for a bigger view of it.
Thanks to Martin for spotting that the clicking of the image didn't give a bigger view, which is now fixed up.
Downloaded PowerPoint files need repairs?
I download a lot of PowerPoint presentations and recently I am seeing more and more are stating they need repairs when opened!
Unfortunately repairing does not work and downloading them again doesn't help either! What is happening is that Windows is detecting that these files are from the Internet and enabling a block on them for your protection. To remove this block, you need to right click the file, select Properties, click the Unblock button and click OK.
You will then be able to open them successfully.
Thanks Joseph for spotting the type-o in the original post.