Jan Schreuder on .Net

.Net code samples, experiences, observations

View my professional profile on LinkedIn

Recent Posts

Tags

News

  • Inappropriate comments will be deleted at my discretion.

    The information and code samples in this weblog is provided "AS IS" without warranty of any kind, either expressed or implied, including but not limited to the merchantability and/or fitness for a particular purpose.

Community

Email Notifications

Tool suppliers

Tools

General

Microsoft

Favorite blogs

Archives

November 2006 - Posts

USB Turntable

So it's not related to software development. But once in while you bump into the coolest gadgets. This time I bumped into the Numark TTUSB turntable. A regular turntable for those that still own vinyl audio and want to convert that to CD. Why didn't I see this sooner. Have a look at the specs:

  • Anti-skating control for increased stereo balance
  • Support for both 33.33 and 45 RPM playback speeds; 78 RPM support via software
  • ± 10% adjustable pitch control
  • RCA line outputs
  • Plug and Play USB compatibility with both PC and Mac
  • Packaged with all necessary cables to interconnect with both a computer and stereo playback system
  • Ships with Audacity software (compatible with PC and Mac) for removing clicks, pops, and other undesirable characteristics of vinyl
  • Audacity supports high-speed recording, then returns music to original playback speed
  • Audacity software includes ability to export to WAV and MP3
Sandcastle November CTP released

About two weeks ago, Microsoft have released a new CTP for Sandcastle. For those still in the dark, Sandcastle is the Microsoft tool for generating documentation based on XML tags in VB.Net and C# code.

This new CTP fixes a number of issues found in earlier CTP and introduces the ability to define custom tags. Custom tags have been a very powerful option in the NDoc era to add your own XML tags to the documentation process. Sandcastle now supports some of the custom tags defined by NDoc, as well as the option to create your own. Another new option is the improved support for Firefox. You can download the new CTP here.

A very powerful and useful addition to Sandcastle is the Sandcastle Help File Builder. This tool features an interface which looks very much like NDoc. It also allows you to import NDoc projects and Visual Studio projects. It really makes creating help files a simple task. If you want to use Sandcastle to create help files, you should also download this tool.

How to: Find out which namespace contains a certain object or class

We have all been in that situation where you want to use a specific class or object, but you just can't remember which namespace to use. Visual Studio can help you find that namespace.

Visual Studio 2003 and 2005

Both versions of Visual Studio support the key-combination Alt+Shift+F12. For example: You want to use StreamWriter and you cannot for the world remember in which namespace you can find that class. What you do is this:

  1. Place the cursor on the text StreamWriter in your code window.
  2. Press and hold the keys Alt+Shift+F12.

You will see a window somewhere on the screen which shows the results. For StreamWriter you will see the following results:

And what a surprise, StreamWriter is in the System.IO namespace. This will work for both C# and VB.Net. This option is not case sensitive, so you can type StreamWriter, or streamwriter. It will find the symbols for you.

Visual Studio 2005

This version of Visual Studio has an even better option. In this version you have the key-combination Alt-Shift-F10. Let's use the StreamWriter class again as our example. Follow this steps:

  1. Place the cursor on the text StreamWriter in your code window.
  2. Press and hold the keys Alt+Shift+F10.

What happens is that Visual Studio 2005 will display a drop-down selection menu next to your cursor, as you will see in this image:

As you can see, Visual Studio presents two options. The first option, which is the default option, will add a using System.IO; line to the code. The second will change the StreamWriter code to read System.IO.StreamWriter. What ever you prefer. Strangely enough, I only saw this work in C#. But feel free to correct me if I'm wrong. Unfortunately, this option is case sensitive.

One (big) but...

Visual Studio will only search assemblies that are referenced for object or class you're trying to find. But usually, most assemblies you need are already referenced. If these options do not find the reference for you, you will have to check MSDN. Or check the documentation of your third-party libraries.

How to: Reformat your code in Visual Studio

We're all really fast at coding, right. So you don't want to bother with things like proper casing of keywords (in VB.Net) and properly re-aligning the code. Well, Visual Studio can do that for you with just a few keystrokes. I noticed that not that many people are aware of this option, but I actually use it quite often. Especially when looking at existing code, I use this key-combination to make sure the code is properly aligned. So let me explain how this key-combination works and what it can and cannot do.

Reformat VB.Net code

Suppose I have the VB.Net as it is shown here:

private _myPropertyValue as String
 
public property PropertyValue as string
    get
        return _myPropertyValue
    End Get
    set 
        _myPropertyValue = value
    End Set
End Property

This code will compile and it will work. However, you will also notice that the casing of keywords is not as you would expect as a VB.Net developer. To re-format the code, follow these three steps:

  1. Select the code you want to re-format.
  2. Press Ctrl-K
  3. Press Ctrl-F

The code should now look like this:

Private _myPropertyValue As String
 
Public Property PropertyValue() As String
    Get
        Return _myPropertyValue
    End Get
    Set(ByVal Value As String)
        _myPropertyValue = Value
    End Set
End Property

As you will see, all VB.Net keywords are now properly cased. But you also get the (ByVal Value As String) code after the Set keyword, all for free. The key combination Ctrl-K + Ctrl-F only works on selected text, so make sure you select the code you want to re-format before using it. You can easily reformat the entire code by pressing Ctrl-A + Ctrl-K + Ctrl-F.

Reformat C# code

The key combination also works in C#. But the functionality in C# is really only useful to re-align the code. Look at the following example:

internal class temp {
    private string _mypropertyvalue;
 
    public string PropertyValue {
        get {
            return _mypropertyvalue; 
        }
        set { 
            _mypropertyvalue = value; 
        }
    }
}

When you use the Ctrl-K + Ctrl-F combination to reformat the code, it will look like this:

internal class temp 
{
    private string _mypropertyvalue;
 
    public string PropertyValue 
    {
        get 
        {
            return _mypropertyvalue; 
        }
        set 
        { 
            _mypropertyvalue = value; 
        }
    }
}

As you will undoubtedly notice, the code is merely re-aligned. But I still found it useful in C#, because I don't have to worry about re-aligning my code. I just use this key-combination to do it for me. 

How to: Change casing in Text to TitleCase

At Tech-Ed 2006 I attended a session about hidden treasures in .Net. One of the treasures mentioned there was the ToTitleCase() method. This method changes the case of the first character of each word in a text to Upper case:

System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase();

The method works fine, but when something is already in upper case it is not changed. Also, having to type the full path to the current culture in the current thread is a bit annoying. So I created the following method which allows me to use this function a bit simpler:

/// <summary>
/// Change the case of the first letter of each word to upper case.
/// </summary>
/// <param name="text">The string to convert to title case.</param>
/// <param name="culture">The culture information to be used.</param>
/// <param name="forceCasing">When true, forces all words to be lower case before changing everything to title case.</param>
/// <returns>The string in title case.</returns>
private string ToTitleCase(string text, System.Globalization.CultureInfo culture, bool forceCasing)
{
    if (forceCasing)
    {
        return culture.TextInfo.ToTitleCase(text.ToLower());
    }
    return culture.TextInfo.ToTitleCase(text);
}

I also implemented a few overloaded methods that use the one above:

/// <summary>
/// Change the case of the first letter of each word to upper case.
/// </summary>
/// <param name="text">The string to convert to title case.</param>
/// <returns>The string in title case.</returns>
private string ToTitleCase(string text)
{
    return ToTitleCase(text, System.Threading.Thread.CurrentThread.CurrentCulture, false);
}
 
/// <summary>
/// Change the case of the first letter of each word to upper case.
/// </summary>
/// <param name="text">The string to convert to title case.</param>
/// <param name="forceCasing">When true, forces all words to be lower case before changing everything to title case.</param>
/// <returns>The string in title case.</returns>
private string ToTitleCase(string text, bool forceCasing)
{
    return ToTitleCase(text, System.Threading.Thread.CurrentThread.CurrentCulture, forceCasing);
}
 
/// <summary>
/// Change the case of the first letter of each word to upper case.
/// </summary>
/// <param name="text">The string to convert to title case.</param>
/// <param name="culture">The culture information to be used.</param>
/// <returns>The string in title case.</returns>
private string ToTitleCase(string text, System.Globalization.CultureInfo culture)
{
    return ToTitleCase(text, culture, false);
}

The following code can be used to test the functionality:

private void TestTitleCase()
{
    System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
 
    string text1 = "change this to title case.";
    string text2 = "chanGe This to TITLE case.";
    string text3 = "ChanGe This to TITLE case.";
 
    Console.WriteLine(string.Format(culture, "[{0}] => [{1}]", text1, ToTitleCase(text1)));
    Console.WriteLine(string.Format(culture, "[{0}] => [{1}]", text2, ToTitleCase(text2)));
    Console.WriteLine(string.Format(culture, "[{0}] => [{1}]", text3, ToTitleCase(text3)));
    Console.WriteLine(string.Format(culture, "[{0}] => [{1}]", text3, ToTitleCase(text3, true)));
}

The code produces the following result:

[change this to title case.] => [Change This To Title Case.]
[chanGe This to TITLE case.] => [Change This To TITLE Case.]
[ChanGe This to TITLE case.] => [Change This To TITLE Case.]
[ChanGe This to TITLE case.] => [Change This To Title Case.]

You will notice the effect that casing has on this method. When a word still contains lower case, then the word is changed to Title case. But when the word is already in upper case, then the method leaves the casing as it is. Which explains why I added a forceCasing boolean as an argument.

Is it useful? Probably not. But I still found it interesting enough to blog about smile_nerd. I wonder how many of us have written methods to do this...

TechEd - It's over

It has been an eventful week, here in Barcelona. I have seen a lot of new things, and learned a lot over the last few days. Too bad it's over? Well, yes and no. Yes, because there is so much more to learn. No, because I will be flying back tomorrow and be with my wife and daughter again.

It has also been a very exhausting week. There is so much information coming your way, that at a certain moment, your mind will stop sucking it all in. 5 sessions per day packed with information is really a lot. But I'm glad that I got this opportunity.

Tomorrow at 10 am I will fly back. I have already checked-in on the Internet using my E-Ticket at KLM, so all I have to do at the airport is deliver my suitcase to the baggage handlers.

TechEd - AJAX Patterns with ASP.NET AJAX

A very interesting session in which the presenters went beyond the Hype that Ajax has recently become.

In a number of demos, they quickly showed what (not) to do when implementing ASP.Net Ajax in your web application. An example:

If you have already seen ASP.Net Ajax, or Atlas as it was once called, you might have seen the UpdatePanel control. Now this panel allows you to quickly Ajax enable your application. Only the part of the form that is contained in the UpdatePanel will be updated after a post-back. But that doesn't mean your web page is not performing a post-back. In fact, it does a normal post-back and only once the server is past the rendering stage, it does some magic to only send stuff back that needs to be updated. To the user it looks like a quick change on the web page, but it's almost the same as a full post-back for the web application. So what can you do?

  1. Set AutoPostBack to false on all controls in the UpdatePanel that do not require an update to the web page.
  2. Set the UpdateMode property on the UpdatePanel to Conditional and add AsyncPostBackTrigger items to the TriggerElement for the UpdatePanel Control in the aspx page, or call the Update() method on the control when you need a post-back.
  3. And of course, think about what parts of the screen will require a post back.

Another option that was shown is calling a Web service to get information for a partial update. I won't go into details on this, that would be too much work. Keep an eye out for the TechEd sessions when they are made available and check out this session if you're interested in ASP.Net Ajax.

TechEd - Building Ad-Hoc Reports using the SQL Server 2005 Reporting Services (SSRS) Report Builder

Very interesting session on the new Report Builder application for Report Services. The tool is aimed at business users that need to design their own reports. It works an a model of the database, kind of like Business Objects. And with SP2 CTP2 for SQL Server 2005 Reporting services (available soon) it will also feature integration into Sharepoint 2007.

It's not as advanced as the Report Designer, which is more aimed at developers. The tool is deployed to a user machine using ClickOnce deployment, so it's actually running from the ClickOnce cache. It uses an interface that's built on Microsoft Office paradigms, so people with knowledge of Excel and Powerpoint should feel right at home. Reports created using the Report Builder can be stored on the server, just like the 'normal' reporting services reports, and in Sharepoint 2007 using the new add-in. However, that function is still very much beta, as the error messages proved.

The data model required for Report Builder can be created using the Model Designer application. And a lot of it is automated, so you should be able to create a model quite easily. You can create models for SQL server database, but the current version also supports Oracle out-of-the-box. It's not possible to create a model for Analysis Services. If you want (or need) to use that, simply add Analysis services as a datasource to Report Builder.

TechEd - Unit Testing Best Practices With Visual Studio 2005 Team System

This session proved that it's impossible for all sessions to be interesting. Now don't get me wrong here. There were a lot of delegates at this session, and for a lot of them it is probably interesting. But I was expecting something completely different.

As the title suggested, I was expecting to here best practices for developing unit tests. After about 20 minutes into the session, all I saw was how to create a unit test in Visual Studio Team System Suite. Not really mind bloggling or rocket science. But that's not my point. I had only heard two things of interest to me:

  1. When do you write unit tests.
    1. Before writing code: In Testdriven Development, Agile or XP scenarios.
    2. After writing code: Quality Assurance, bug discovery, regression tests
  2. KIS(s). Keep It Simple (stupid). Which was accompanied with the remark that copy & paste is usually bad, but not when you write unit tests.

I gave up after hearing that. Too bad, but when you're tired after a long day at TechEd, you need to be stimulated. Not put to sleep. Still, this was the first session I walked away from. And probably the last.

Tomorrow, Friday November 10, will be the last day of TechEd.

TechEd - .Net Hidden Treasures

Not all sessions I go to have to be about new stuff, now do they. So this session was interesting because they showed some items in .Net (and SQL 2005) that not everybody knows about. I have tried to remember a few I found interesting. You won't see many details, I just can't write that fast ;-)

  • Alt-Shift-F10. In VS 2005, when you know of a class that resides in a namespace, and you don't know which one, then press this key combination. VS 2005 will attempt to find it and if it does, offers to add the Using statement (or imports in VB.Net) for you.
  • System.Diagnostics.Stopwatch. Exactly what is says, but you can use it to time method calls in code if you want. Check which (part of a) method is slowing your application down!
  • Common Table Expressions in SQL 2005. A way to resolve recursive queries, but also a great way to do paging through a result set on the server.
  • INSERT INTO [TABLE] DEFAULT VALUES. Replace [TABLE] with a table name and simply insert a row with all default values filled...
  • ASP.Net ExpressionBuilder. You can add AppSettings : SettingName in the script on your ASP.Net page and ASP.Net will just read the setting for you and add it to the form. You can even build your own by creating a class that derives from ExpressionBuilder
  • CultureInfo.TextInfo.ToTitleCase. pass in "this is all lower case" and get "This Is All Lower Case" back. Only works when it's all lower case though.

There was a lot more, but for that you'll have to wait until the sessions are available on the web!

Blue Screen of Death

Not .Net related, but while I was reading a Dutch news website to keep an eye what is happening back home, I read that the Blue Screen Of Death screensaver can be downloaded from a Microsoft web site. Yep, you read it correctly, a MICROSOFT web site.

"One of the most feared colors in the NT world is blue. The infamous Blue Screen of Death (BSOD) will pop up on an NT system whenever something has gone terribly wrong. Bluescreen is a screen saver that not only authentically mimics a BSOD, but will simulate startup screens seen during a system boot.

On NT 4.0 installations it simulates chkdsk of disk drives with errors!

On Win2K and Windows 9x it presents the Win2K startup splash screen, complete with rotating progress band and progress control updates!

On Windows XP and Windows Server 2003 it present the XP/Server 2003 startup splash screen with progress bar!

Bluescreen cycles between different Blue Screens and simulated boots every 15 seconds or so. Virtually all the information shown on Bluescreen's BSOD and system start screen is obtained from your system configuration - its accuracy will fool even advanced NT developers. For example, the NT build number, processor revision, loaded drivers and addresses, disk drive characteristics, and memory size are all taken from the system Bluescreen is running on.

Use Bluescreen to amaze your friends and scare your enemies!

Bluescreen runs on Windows NT 4.0, Windows 2000, Windows XP, Windows Server 2003 and Windows 9x (it requires DirectX)."

Had to give you the link: http://www.Microsoft.com/technet/sysinternals/Miscellaneous/BlueScreen.mspx

TechEd - Windows Presentation Foundation (WPF) in the Real World: Zurich Airport Monitoring System

This session had an enormous WOW factor. I was really impressed with the way Ronnie Saurenmann from Microsoft Schweiz GmbH used WPF to build an airport monitoring system. The basis was a completely digitized map from a GIS system which was translated into vectors. Buttons in the shape of images floated around the airport to indicate plains taking-off, landing and moving around the airport buildings. Everything scalable of course, thanks to WPF.

What impressed me most was how easy it is to create a basic map and how simple it is to add events to the WPF application. New for me was, that XAML can also run inside a "normal" WinForms application. That of course offers a lot of new possibilities. It is not always required to build everything in XAML and present it using WPF.

Some lessons learned in this session:

  • Now what the limits are for the target hardware. Everything in WPF is vector-based. So the more vectors in your XAML, the more computing power your machine and GPU need.
  • The Expression Designer is extremely useful for designing XAML forms. The XAML support in VS 2005 is still somewhat limited. Always use both tools, just make sure you save everything in one tool before moving to the next.
  • Expression Designer is also a great tool to start working with WPF. You can really learn a lot about the possibilities of XAML and WPF from that tool.
  • WPF is easy to learn, at least it seems that way. It also seems to perform pretty good, although so far I have only seen it being demo'd on dual-core machines.
  • You don't need knowledge of DirectX or DirectX3D. That's all hidden for you. You simply design and run.
  • WPF looks to me as a very powerful tool to build map based solutions or simulations.
  • And last but to me not least: Do not use WPF for stuff that a normal Windows Forms application can do. It needs a lot computing power compared to ordinary WinForms.

TechEd - Too much information

Greetings from a warm and sunny Barcelona. Although that warm and sunny is completely useless as I'm inside a conference center :-(

Ever had that feeling that there's just too much information coming at you? It is dawning on me now. Mind you, I love all the information I'm getting. I feel like a humongous sponge at the moment. So why am I telling you this.

Well, I had the feeling myself that what I'm blogging is not having as much detail as I would like. I can imagine that you as a reader of my blog have that same feeling. I'm trying to do my best, but recapturing everything you here in a session is just impossible. So for now, you will have to make do with what I can flush from my notes and memory.

When the TechEd is over, all sessions will be made available by Microsoft. So you will be able to get all the information, and more, straight from the horses mouth. As soon as that happens, I will post a link to that information. But until then, you will have to make do with what you see here.

TechEd - Proven Practices for Implementing Services

What promised to be a session where proven practices for implementing services would be presented, turned out to be more of a session about the impact of migrating from ASMX webservices to WCF webservices.

Migrating ASMX to WCF is not that difficult. It is possible to keep the ASMX service operational while adding WCF specific attributes to the code. This allows you to test both versions and make sure that your WCF version works the same as your ASMX code. When you're done, simply remove the ASMX stuff (such as [WebMethod]) and you have a WCF service.

The presenters (Beat Schwegler, Architect and Don Smith, Service Factory product Manager) demonstrated how easy implementing a webservice is when using the Service Factory. A lot of the infrastructure for a service is generated automatically. So most of what you need to do is implementing the interfaces and business logic. The demo proved this by building a webservice to do some simple math in less than 10 minutes. The service factory for ASMX is already available, the one for WCF will be made available mid-December.

The Loosy-Goosy problem was explained including a way to get rid of it. Loosy-Goosy is the effect where the soapmessage that reaches your webservice does not contain all the arguments for your webmethod. In general, the method will not fail but simply return a result you do not expect. Consider the following method: public int Add(int a, int b). When the soap method does not include a value for a or b, you will not get an error when you call the method. You will just get a result. You can solve this by changing it to the following: public nullable<int> Add(nullable<int> a, nullable<int> b).

A better option to pass data to a service is to use Request and Response messages. All methods then have one argument, the response message, and all return a response message. These messages can be stored, logged, validated and re-used. Which is not possible with method arguments.

TechEd - Building Rules-Based Systems in Windows Workflow Foundation

This session provided me with some more background on Workflow Foundation or WF. WF is a combination of a workflow engine and a rules engine. The WF engine uses the rules engine to store conditions and such. The rules engine itself can run separate from the workflow engine.

That provides you with the option to define business rules in a database and have your application act on the evaluation of those rules, instead of using hard coded conditions. A business rule can be changed without having to recompile and redeploy the application.

The Workflow designer in WF offers Business Analysts the option to model business workflows and rules without having to have any knowledge of the underlying code. The code required to build the application that processes these rules is left to the developer. Integrating this technology will prove an interesting challenge for any Architect.

More information on WF can be found at:

Here you will find samples and detailed information on what WF has in store for you.

More Posts Next page »