This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on

Friday, May 29, 2009

Setting Template Properties on a ComboBox

In WPF the ComboBox is a tricky little control that doesn’t easily allow you to adjust properties on the inner controls of the template.

If you try to override the template you will find very quickly that you might get into the trap of having to override the entire visual tree, thus having to recreate the entire control from scratch.

Below is a way to get at the controls from the template, per my answer to a question on the MSDN forums. In particular, the question was about getting the TextBox (actually, in his case, the TextBlock) to have underlined text.

cboTest.Loaded += delegate {
if (cboTest.IsEditable)
TextBox textEditPart = ((TextBox)cboTest.Template.FindName("PART_EditableTextBox", cboTest));
textEditPart.TextDecorations = TextDecorations.Underline;
Grid layoutGrid = VisualTreeHelper.GetChild(cboTest, 0) as Grid;
ContentPresenter nonEditPart = VisualTreeHelper.GetChild(layoutGrid, 2) as ContentPresenter;
TextBlock textNonEditPart = VisualTreeHelper.GetChild(nonEditPart, 0) as TextBlock;
textNonEditPart.TextDecorations = TextDecorations.Underline;

Man, code on this blog is hard to read.  :o/

Okay, so what’s going on is basically that we have to hunt down the TextBox or TextBlock, depending on if the ComboBox is set to be editable or not.

After finding that, we simply set the TextDecorations property to the pre-defined Underline text decoration. Paste that code into your code-behind after InitializeComponent and you should be good to go.

I found the elements in question by using Mole.  When we have an object that is named, we can use the Template.FindName to get the control loaded up locally.  When we don’t, we’ll need to use VisualTreeHelper’s static GetChild method to dig.

Side note: this won’t work in a big way if you’ve otherwise edited your template.  This is fairly hard-coded against the VisualTree provided by ComboBox out-of-the-box (but could easily be adapted to be a little less tightly coupled).

Thursday, May 28, 2009

Sample Data Previews in Expression Blend 3

I am so glad there are people smarter than I am.  Especially folks that are working on Blend and who knew I would be posting about sample data, and how that might work

And the fact that they were working on it for months before I ever piped up. :oD

Expression Blend 3 does the exact thing that I was hoping Microsoft would integrate into the designers for WPF: sample data can now be auto-generated for you, or you can specify an XML file to populate the design-time data.


Here’s Soma’s preview from his blog…and an inexplicitly long set of gripes from people who obviously haven’t upgraded their IDE since Visual Interdev…

For those that are highly critical I encourage you to dive a little deeper than what's at the surface here. Templating, binding, providers, extensible components, the frameworks and base classes now provided, and now behaviours...there are a lot of great tools here.  I've been using .Net since 2001 and have deployed apps with up to 10,000 users.  It has come a long way, but you have to take off your "Here's what I know" cap and adopt the new functionality.

I remember when a friend got Vista, an upgrade from Win95.  She refused to start using the new document folders and insisted on using her old DOS-style directory structure for storing.  When she finally let go and adopted the new style of organization she was pleasantly surprised…

Visual Studio 2010 – WPF Designer

The new WPF designer is quite exciting, as are many of the features that are coming down the pike for us developers in Visual Studio 2010.

Karl Shifflett posted a link to the new designer intro videos on last night and I had a dive into them.  The coolest-ever-IT-d00d at my office is in the process of building me a Win7+VS2010 virtual machine as I write this. Yum.

Of note for me are the following:

  • The visual appeal isn’t quite my thing, but I’m getting to be an old guy and am actually a fan of the existing environment.  On the other hand, I love Expression Blend and its apparent ‘awareness’ of certain things, so I’m encouraged that Visual Studio 2010 seems to be moving in that direction.
  • The Data Source tool window has had some long-overdue features added to it, such as awareness of foreign-key relationships.
  • The draggy-droppability of the designer from the highly-aware Data Source tool window is ridiculous.  Before you get too critical of using tools to do those kinds of things (I have some buddies who just hate using code-generation tools and are hesitant to switch to .Net because of it), be sure you check out what’s really going on.  All of the binding you would do by hand is being done – elegantly, I might add – behind the scenes for you.  There is no locked-in overly-cumbersome data binding through properties that makes you rip out what little hair you have left…uh…oops.  Flashback to WinForms…
  • The WPF designer has had some really nice updates to it to handle things like layout for grids.  Again, this is a vehicle for code-generation of sorts, but the extra design-time help is great for keeping you in one place.  I am not a fan of having to ride three different work areas to accomplish a task, that being the designer, the properties tool window and the Xaml editor. This is a welcome change. You can now switch between column sizing modes on-the-fly from the editor, as an example, giving you richer control over the layout.
  • There are improvements as well to the workflow of adding and displaying images in projects.  While this wasn’t terrible before, how and where it handles and stores images is more streamlined and path syntax is created dynamically (as it was in 2008, but there is a UI for this now).
  •  imageMuch like the WPF designer in Visual Studio 2008, we have search functionality in the Properties/Events tool window.  This is especially important with the emerging model of binding, preview events and the like.  If you aren’t already using this, give it a try.  The screenie to the right is from 2k8.  The Properties tool window is quite enriched and better reveals data binding status and options.
  • The search functionality has been applied to the new resource selector, as well, allowing us to quickly filter through the dozens of brushes, paths, etc. that we may have in our project.  I have to admit that this is a little bit of validation for me.  My resource libraries have grown significantly over the last little while; that they have implemented search capabilities indicates that the way I style my app is common to the community ;o)
  • It seems that the Properties tool window is getting some much-needed love.  The in-line editors for properties are not so shallow.  A control’s font, for example, has a more Word-like property editor streamlined into the property editor.
  • Data binding during the design story has been quite enhanced.  Drilling into a composite type that the designer has bound for you allows you to drill into that type, select an appropriate converter and get away from MyObject.ThisNameSpace.TheClassIWrote being displayed in your label, for example.  This is part of that “awareness” I was talking about that makes the experience more fluid.
  • The tab page for the IDE is now akin to IE’s tabbing functionality.  While I do prefer this to the style of Visual Studio 2008, I am a greater fan of the Google Chrome approach, where hovering over a tab allows me to close it without having to bring the tab to the foreground.

There was a mention in one of the videos that multi-control selection and property setting would be in the release version of Visual Studio 2010 (so, you’d be able to select four controls and set a brush for the background).  I also hope that they consider a resource palette, so that I don’t have to drill into the properties window and a popup box to achieve the same result.

I’ve also wondered why there isn’t more made of the mouse.  We aren’t too low on the experience level here, as developers, so I think that more encompassing experiences should be worked into the developer experience through that simple rodent we keep on our desk.  Middle-click, anyone?  If I were working on Visual Studio 2010, I would have tried to create accelerators with the mouse.  For example, if I highlight a block of code and middle-click, bring up the refactor menu (instead of going through the right-click submenu).  Similarly, if I’m in the designer and right-click on a control, give me the context menu related to styling and applying resources.  Again, I like to stay in one place and have the in-context toolset at my fingertips.  Especially my middle finger.  Always proves handy.

I will come back with more when I get my hands a little more dirty with the 2010 beta.

Wednesday, May 27, 2009

Wordle-me, Baby

A good friend of mine sent a link to this great web site called Wordle that allows you to build word-images from a web page, a block of text, or any RSS/Atom capable blog or URL.

My blog looks like this:


So…apparently I talk about DATA, VISUAL and STYLE a fair bit.

It also looks like this:


And this:


…but all I see is a potato!?

A good read on the approach (at 30,000 feet) and a bunch of background are on the site. As a .Net developer I sigh a little when comments like this are made:

This would have been completely impossible without the Java platform. (source)

There are actually many ways to do this, .Net certainly not the only alternative to Java.  Any development platform that allows access to font metrics would allow for something similar to be developed.  I don’t mean to trivialize the work done here, nor to turn to a Java versus .Net debate, the point is that many languages and environments (Flash output from c++ cgi running on Apache, for example) could render similar - if not the same - results.

That said, this is very cool work from a bright mind.

VS.Net Crashes When Editing Xaml Resource File

I have found what I believe to be a bug in Visual Studio 2008 when editing a Xaml Resource file.

Visual Studio 2008 stops responding if you edit an in-use style to be something invalid.  Now, you may be thinking, “Why on Earth would you want your style to be invalid?” …and that’s not really where I’m going with this.

Below is a visual to get where I’m at.  Just, please, brace yourself before you set eyes on this image; I used up the remainder of my annual illustration budget to enhance and superimpose qualifiers to properly indicate the exact cause of the problem.  For inexperienced graphic observers, the following image may just cause your retinas to implode with visual excitement:


Pretty crazy graphics, eh?

Well, you’re still reading so your eyes must still be in tact.  Here’s what I was doing:

  1. Created a button style for use in a user control
  2. Moved the style into a resource file
  3. Applied the style to my button
  4. Wanted to change the margin as well, so I copied and pasted the ‘BorderThickness’ line. The only thing I like less that copy-and-pasting is typing…
  5. Visual Studio implodes (as your eyes may have from the previous illustration.

I’m assuming that the problem is that, internally, an exception is being kicked up somewhere because either the style can’t render (other invalid states cause Visual Studio to puke, too, like incomplete Xaml tags in the style), or because of a problem like I’ve illustrated with a property being set multiple times.

I did a little more digging and found that Visual Studio only stops responding if you have a designer open that uses the style.  In other words, if I close all the designers that have a button using the style in question, I am able to successfully copy and paste invalid code into the style.

The good news is that the work-around is easy: close all your designers before editing in-use styles.  The bad news is that, if you’re like me, you’re working in multiple designers at once and re-using styles.

I have five MVVM views implements as UserControls that compose my main UI (each spawning other views) so when you’re trying to pull everything together this can be a pain in the arse.

UPDATE: I did find this KB article that will allow for a hotfix download for qualified parties…calling in now for download instructions…

Tuesday, May 26, 2009

Out With the Old…

…and in with the new:

imageScreenie showing contact info, time in queue, 
customer feedback and technical rating of the caller.

I am really trying to follow some of the current trends in visualization.  What I’ve come to learn is that software users know what they want to do, they just don’t know how they want to do it.  What’s worse is that we’ve reinforced behaviours developed under poor software design and now many of us in the software development world are guilty of holding up those behaviours to point of encouraging them.

When a call comes into our helpdesk, the service reps don’t want to see all of the customer information; they want to see the information they need to confirm a customer’s identity.

The previous version of the software, which officially began development nearly a decade ago, wasn’t focused on a role or a task.  It was data-centric.  If you requested to see more data – because it would better serve your role or task – it was layered onto or composed into existing screens. 

The end result was that, over time, data started get lost.  Many bits of data were forgotten about, overlooked, under-used and – worse – re-implemented in different areas with slightly different meanings.

Using MVVM and WPF we are already improving the experience for the customer by improving the experience for the call staff.

I’m not saying I knocked it out of the park here, and arguably, someone with a little more design experience could improve this dramatically (go ahead! Write your own View and bind to my ViewModel!) but I think this is proof that software can look sexy and be functional at the same time.

Monday, May 25, 2009

Design Time Data in WPF

I came across an excellent article from Karl Shifflett that discussed a couple of different approaches for viewing data during a design time story.  There is nothing, by default, in Visual Studio that stubs out data for us so that we can see something in our template as we edit it.

The design-time and run-time experience, left-to-right.

Basically, if you’re creating templates for grids, listboxes or any other control in XAML you’re going to want to be able to see how that data looks without having to compile and run the app continuously.

By (heavily) using Karl’s project as a starting point, I have rebuilt his sample to a WPF-specific approach with imagesome suggestions on how to structure some of the project in a way that can grow a little better.

I also added a concrete example of how a design-time and run-time object could be set up for a little more clarity on how these objects play together.  These are found in the Data hierarchy in the project.

Also, as per Karl’s suggestion, I added a couple of data triggers to play with formatting in that way. There are triggers that reveal changes in either design time or run time (look for the comments).

Again, I borrowed heavily from Karl’s sample here, but wanted to make this sample a little more accessible to anyone who is a little newer to WPF.  There are still tons of opportunities to expand and explore this concept and to figure out how to make it work for you in your application development.

This is all cool, but it’s basically meaning more work and prep on any project you do.  I would love to see an extension to the designer that, in an intelligent way, would allow us to set a boolean value in the DataContext called, say, “EnableDesignTimeData”, that would then stub out as many instances of that class as we specify, perhaps in a “DesignTimeDataRowCount” property on the DataContext.  Allow the designer/support classes to build up rows based on this idea, but also allow us to drop an XML file (or build one through yet another extension to the designer, perhaps with pre-populated rows?) to use as the design-time data.  This would allow us to create data to cover all of the possible formatting scenarios that we may wish to express.

You can download the zip of the project here (VS.Net 2008).

When I get a chance this week, I also hope to MVVM-alize this sample and add a couple of commands.  That would be rockin-cool.

Thursday, May 21, 2009

Mind if I catch a ride?


And this, my friends, is how we do it when we work at an ISP:


That is a full NINE megabits of gee-golly-darn-fast-sucking-the-files-down bandwidth, baby!

Wednesday, May 20, 2009

Technologies that Drive Patterns that Drive Tools (that Drive Technologies!)

I recently hosted the first .Net user group here in town and was pleased to be joined by D’Arcy from the Winnipeg .Net User Group.  Afterwards we had a chance to sit down – probably for too long, given his two-hour drive home afterwards! – and talk about everything from past projects to past employers to the impossible fact that we didn’t know each other given how many times our paths have nearly crossed.

We got to talking about design patterns at one point in the conversation and how it was interesting to see some of the emerging patterns and how tightly coupled they were to some of the technologies that we have as developers.

One such instance is how MVVM serves WPF nearly exclusively.  Sure, it’s a derivative of past patterns, but this has been very tightly coupled to the WPF experience.  So, here’s a technology that, as developers began to share code, helped to surface a pattern.

Then, MVVM was used to create the very tools that designers and developers are using to scratch together WPF applications. Now there are even extensions to VS.Net that allow easier implementation of MVVM (see Karl Shifflett and the WPF Toolkit).

WPF drove the creation of MVVM.

MVVM served as the backbone for tools development.

Now, it’s getting really interesting.  Because of limitations in the command binding syntax and underlying framework, the folks on the WPF are actually considering changes to WPF to allow for simpler binding. 

Where did this come from?  MVVM exposed a need for binding to commands that was not native to WPF.  Some of the tools that are being created have features that allow for developers to work around these WPF limitations.  The WPF team recognizes this – good on them – and are now updating the framework to improve this aspect of WPF development.

Tech –> Pattern –> Tool –> Tech.  We’ve come full circle.

Lather, rinse, repeat.

Tuesday, May 19, 2009

Because I Always Keep Digging…

I just realized that I like to make things harder than they need to be. ;o)

If you want to paste files into Visual Studio, you don’t need to go the add to project route I just wrote about, you can just navigate to the source directory (as in my previous post), copy the files and then return to your target solution (in Visual Studio) and paste the files into the desired folder.

This not only pastes a copy of them into the right directory, but it also adds them properly to the project without having to do the “Show all files” thing.

Copying Files from Solution to Solution

(…or from project to project in another solution!)

I do a fair bit of spiking before I get into the thick of things with code (anyone who’s worked closely with me has seen my endless projects in my Spike directory). 

It can be frustrating if you’ve got a collection of small classes that you’d like to copy from one of your spikes to a new project/solution to start unit testing.  Visual Studio does not allow you to copy from the solution explorer, switch to the other Visual Studio instance, and then paste the files.  Instead, you get the following error:

The source files for this operation cannot be found in this solution.

While it’s a bit of a pain-in-the-arse, there is a fairly simple workaround to this.  image

Start in the solution with the files you want to copy.  Right-click on the containing folder (or the project) and click Open Folder in Windows Explorer.

Next, using Windows Explorer, select the files that you want to copy and put them on the clipboard.

Flip over to your target solution, and find the project or folder that you want to put the files into.  Use the same right-click trick to open the folder location on the hard drive.  Now, paste the files into this directory in Windows Explorer.

Lastly, return to your target solution; here, we have to let Visual Studio know that these files are part of your project.  Even though they are in the project folder, they won’t be included and can’t be image referenced until you express your interest in doing so.  Select the target directory and click on the Show All Files icon in the toolbar for Solution Explorer.  Your new files will now appear in the project, but they will have a different icon.  Select them all (use shift-selecting or ctrl-selecting if you need to) and right-click to reveal this menu:


Click on Include in Project and you’re set.  Now you can move classes and resources from one project to another using Visual Studio (and Windows Explorer).

Friday, May 15, 2009

SQL Server Management Studio Request

A feature I would love to see in SSMS would be the ability to write plug-ins – a little more easily – that would allow developers to hook-up templates and actions to objects on the design surface.

As an example, here’s a shot of a couple of selected tables (from a throw-away sample…don’t mind the conventions!):

tables from the designer

When I right-click on these tables, I would like to invoke an action/template that could start some code generation.  Much like right-clicking on a table in the Object Explorer allows you to Script Table –> INSERT to –> Clipboard, I would like to be able to setup a template that allowed for more complicated code to be generated.

Here’s one that I would do: create a multi-insert stored proc template that took n tables as parameters.  When invoked, it would create a stored procedure that would take care of things like inserting the parameters (while omitting the identity columns), ordering the inserts to satisfy relationships, storing SCOPE_IDENTITY() into locally declared vars as it works, etc.

There’s still too much grunt work in creating stored procs.  Dunno, maybe I’m just too lazy ;o)

More People Getting Access to OneNote

Every time I flip open a copy of OneNote and jot something down, or paste in a screenie or to take some notes (or any one of the endless things I do in OneNote) someone asks me what software that is and I am floored that they aren’t already using it.

I’m actually (unreasonably) waiting for a commission cheque from Microsoft as an independent OneNote evangelist. I’m probably good for Gold Partner status. ;o)

Anyways, the Office 2010 IT Blog has confirmed that OneNote will now be included as part of the suite that volume licence (pro, anyways) Office users get.  This is great, because most people that I know who use Office do just that: they use it.  They don’t install it, or download templates, or administer patches, or likely even register.  So they would never be on the Office site and they would never be exposed to OneNote.

This is a great piece of software – my favourite feature being the password protected pages – and something that I think you should start using.  Really, it has put an end to the randomly scattered ToDo.txt files on my machine, and if all the other gains were lost, that would still be a win worth obtaining!

Also on Office, check out the Office 2010 movie site (what?!) for a hilarious, over-the-top, tongue-in-cheek approach to introducing the next version of the software that everyone claims to hate but uses 4 hours a day.

Thursday, May 14, 2009

Open a Project in Expression Blend from Visual Studio

If you work in both Blend and Visual Studio you will notice that there are significant gaps in functionality between the two.  In Blend you get a rich design and animation interface (and it looks way cooler, too) but don’t get some of the much-needed development tools.  In Visual Studio, you get productivity-focused tools like intellisense but lose out on easy storyboard manipulation and the like.

Basically, if you do at least a little of design and a little of development, you need to be running both Expression Blend and Visual Studio.

From within Blend there are a number of actions that will result directly in Visual Studio opening (such as drilling into a click event on a button) if you have Visual Studio installed.  However, Visual Studio doesn’t reciprocate the favour when you’re looking for something more design-friendly.

To open your project in Blend directly from Visual Studio, you’ll need to hack together an external tool link.


Go to Tools –> External Tools in Visual Studio and add a new entry to the menu contents.  You can set your title to whatever you like (I used Send to &Blend).  Your Command should be set to the path for the EXE where you have Blend installed.  Lastly, set the Arguments property to the following:


…which will tell Visual Studio to pass the current project path and name to Blend as it opens the project.

Happy Blending!

Wednesday, May 13, 2009

Adding a Hint to a Search Textbox in WPF

Are you running Vista?  Good.  Press the start key (or click on the Vista orb).  See how it says, “Start Search”?

It’s a nice effect: it’s contextual, it gives the user direction and it disappears the instant you start typing something.

If you want to give your users a similar experience with minimal effort, here’s how you add a hint (or help text) to a textbox or similar control in WPF.  I am added the hint to a combobox, so adjust your code as needed.

The approach we’re going to take here is similar to using a reflection surface in WPF, in that we’ll use a VisualBrush.  A couple of quick things: first, we set Stretch and TileMode to None (it would look a little weird, if not); second, we apply a slight transform to pad out the text (otherwise it hugs the border).

<VisualBrush x:Key="SearchHint" TileMode="None" Stretch="None" AlignmentX="Left">
TranslateTransform X="5" Y="0" />
TextBlock FontStyle="Italic"
Text="Enter search text…"/>

You’ll need to add this visual brush to the window or control resources, or put it in a resource file.

Next, we want to use a trigger so that the background is changed from it’s default when the string is empty to be the SearchHint instead.  WPF takes care of changing it back for us when there is text in the box.

I have this as code in my ComboBox tag:

Style TargetType="ComboBox">
<Trigger Property="Text" Value="">
Setter Property="Background" Value="{StaticResource SearchHint}"/>

There you have it.  You may want to add multiple brushes, or even an image or anything (I used a grid for this purpose in the Visual, but you can set this to any single element you like).  If you’re presenting data or there is a chance you could get a null in there you may wish to handle that Trigger condition as well.

Man, alive…I really need to do something about this blog template so my code doesn’t look like arse.

edit: Here is the original article I based my work off of. 

I Like My Puter

I am running IIS, SQL Server, four virtual machines, four instances of visual studio, MS SQL Server Management Studio, four explorer windows, Expression Blend, six copies of IE, Word, Excel, Outlook and 43…YES forty-three copies of Chrome.  There also a couple of Notepads running as well as some task tray utilities and, obviously, I’ve got my blog writer open.

Physical memory usage is at 36% and CPU usage is hovering between 3-6%. Up time is 7 days, 20 hours, there’s 115 processes running and 1581 threads.

This beast is responsive, compiles are quick, Start+Tab application switching is lightning quick.

I love Vista 64.

Tuesday, May 12, 2009

Getting at the Text of a ComboBox in WPF – Part 2

- You all finished?
- Yeup, it compiles!

At the end of the day yesterday I thought I had made a bit of progress with my filtered-combo box. Unfortunately, though it compiles, I’ve found that I can’t get my app loaded and binding to that event at run-time gives me an exception.

However, in looking for a solution, I found the DependencyPropertyDescriptor object, which allows us to access dependency properties from code.  Using this object I can now observe the text for changes and add my event handler as such:

public Window1()

DependencyPropertyDescriptor comboText;
comboText = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox));
comboText.AddValueChanged(this, this.ComboTextChanged);

private void ComboTextChanged(object sender, EventArgs e)
// ...

Monday, May 11, 2009

Getting at the Text of a ComboBox in WPF

I am writing a small wrapper for WPF’s ComboBox and want to hook up (optionally) a delegate that filters the list of items, based on what the user has typed already into the text box portion of the control.

I have achieved this with the help of Mole and the FindName method on the Template object.

TextBox input = ((TextBox)comboBox1.Template.FindName("PART_EditableTextBox",comboBox1));
input.TextChanged += new TextChangedEventHandler(input_TextChanged);

FindName allows us to walk across a templated control and search for a child element by the name we pass in.  This allows us to get at some of the innards for some of the existing controls and, in my case as above, attach to events or check properties and the like.

Thursday, May 7, 2009

MS SQL Server: Writing String.Split

UPDATE: A reader pointed out a scenario that I had not tested for: trailing data after the delimiter.  I did not run into this in my testing (I was using line breaks and always had them at the end of the document I was testing) but I have updated the code below to reflect how to grab the rest of the text.

When you come from a programming background you might find it hard to believe when you flop over to the MS SQL side of the world that SQL Server does not have a SPLIT function for string manipulation.  In .Net, we have the string.split method that allows us to break up text based on a delimiter.

In MS SQL, you have to write a string SPLIT function yourself.  Not having a great head (yet) for performance, I would suggest that because of the walking the string bits in here, my stab at this shouldn’t be used in high volume situations.  That said, I walked across 3,500 rows generating 70,000 rows of split-output (and inserting them to the DB) in less than 20 seconds.

The following method returns as a table variable, so the correct syntax for calling requires a SELECT as such:

select * from Split(YOUR_TEXT, ',')

Here’s the function for your compilation happiness:

create function dbo.Split
(@SourceText varchar(max), @Delimiter char(1

returns @Table table(StringID int, Value varchar(max

@textPart varchar(max

set @count = 1
set @prevPos = 0
set @curPos = 0
set @nextOcc = charindex(@Delimiter, @SourceText

while @nextOcc > 0
@curPos = @nextOcc
set @nextOcc = charindex(@Delimiter, @SourceText, @nextOcc + 1
set @textPartLength = @curPos - @prevPos

-- grab the substring from the source text and remove the delimiter
set @textPart = substring(@SourceText, @prevPos , @textPartLength
set @textPart = replace(@textPart, @Delimiter, ''

insert into @Table (StringID, Value) values(@count, @textPart

set @prevPos = @curPos
set @count += 1

-- get any text after the last delimiter
set @textPartLength = LEN(@SourceText) - (@prevPos - 1
set @textPart = substring(@SourceText, @prevPos , textPartLength
set @textPart = replace(@textPart, @Delimiter, ''
if(LEN(@textPart) > 0
insert into @Table values (@count, @textPart)



Tuesday, May 5, 2009

Slightly Better Version

Last week I posted a function to convert an IP address to its decimal value using c#.

I have a mildly better approach, though by better, admittedly, I really just mean “I’m using some new stuff from the current version of c#”.

It occurred to me that in place of the anonymous delegate I could just as easily use a lambda expression, therefore we end up with this approach:

private static string IpToDecimal(string ipAddress)
// split up the IP into octets and prep our string builder
List<string> octets = new List<string>(ipAddress.Split('.'));
long decIP = 0;
int shift = 3;

// loop through the octets and compute the decimal version
octets.ForEach(octet => { decIP += long.Parse(octet) << (shift * 8); shift--; });
return decIP.ToString();

Now, if you wanted to, you could really use var instead of List<string> and you could likely inline the initialization, but that ends up unreadable.

HOWEVER if you are adamant about using new things, like LINQ, lambda expressions and the language features of c# to convert this bad boy over, you can do it!

I just wouldn’t likely throw this code at the rookie…

private static string IpToDecimal2(string ipAddress)
// need a shift counter
int shift = 3;

// split and loop through the octets
var octets = ipAddress.Split('.').Select(p => long.Parse(p));
return octets.Aggregate(0L, (total, octet) =>
(total + (octet << (shift-- * 8)))).ToString();

This is actually cool because it’s really only three lines of code.  A couple of things to note:

  1. Using LINQ we are able to parse out the string bits and convert the octets to longs with the Select method.

  2. I’m using the Aggregate method and passing in a seed of 0, which I type with L so that the compiler doesn’t see it as an int.

  3. total is used to keep the running track; octet is the parameter passed in from the octets collection.

  4. shift is decremented each pass as we walk across the octets.

Monday, May 4, 2009

ASP.NET 2.0 Has Not Been Registered

I got an error on a clean-install machine today (Vista 64, .Net 1-3.5 installed, VS.NET 2008) that read:

ASP.NET 2.0 has not been registered on the Web server. You need to manually configure you Web server for ASP.NET 2.0 in order for your site to run correctly, Press F1 for more details.

Before I get to the fix, I like to poke fun where I can.  When I press F1, I get nothing.  The help tries to update itself, then just “encounters an error” and shows me the help file for migrating a VS.NET 2002 project to 2008.  Also, I think it should read, “configure your Web server”.  Web is capitalized? Comma instead of a period? hehehe…k. I’m done.

Anyways…it’s a simple configuration thing in Vista’s “Features”.  Open up Control Panel and go to Programs.  On the left-hand side of the window is a link for “Turn Windows Features On or Off”, which you click.  Drill in until you find Internet Information Services –> World Wide Web Services –> Application Development Features and then make sure the ASP.NET box is checked off (it will also likely light up a few other boxes for you too).

Thar ya be.  You should be good to go for building ASP.NET web sites and services on IIS7 in Vista.

If you’re still having trouble, I have run into a case previously where there was an issue using a UNC path (and the IIS user didn’t have perms on the target dir).  You will get an error like

The requested page cannot be accessed because the related configuration data for the page is invalid.

  There are also a couple of similar errors that can be resolved here: MSDN KB942055

Friday, May 1, 2009


Just occurred to me that you can also fairly easily convert the IP if you shift the values as you walk across the octets. 

Here’s a simpler version of the same method.  I’m not using any of the formatting, but I still employ the anon delegate on the generic list. 

private static string IpToDecimal(string ipAddress)
// split up the IP into octets and prep our string builder
List<string> octects = new List<string>(ipAddress.Split('.'));
long decIP = 0;
int shift = 3;

// loop through the octets and compute the decimal version
octects.ForEach(delegate(string value)
{ decIP += long.Parse(value) << (shift * 8); shift--; });

return decIP.ToString();

Here’s a bit of trivia on IP addresses and the internet: it’s all a lie.  You don’t actually “go” to a web site by name; that’s just what you type.  A web site end point is actually a port on an IP address.  Typically HTTP runs on port 80, so that’s assumed by the http prefix.  So, you can go to, or you can go to and it’s the same thing.  What’s cool is that if you take that IP and convert it to decimal, such as http://3512052580, you can also go to that address and see the Google home page. Depending on your browser, it might convert that 3512052580 to the IP address for you, but it all goes to the same place.

Here’s how that code works:

  • Using the string.Split function and a character ‘.’ we break apart the list of octets from the IP address into a generic list of strings.  string.Split returns an array, which we can pass into the constructor of the List<T>.

  • Quickly, we create a variable to hold our result, then a counter to help us shift the bits.

  • Next, we ‘walk’ across the list using the ForEach method.  This method can accept a delegate to an existing function or an anonymous delegate in-line.

  • We tell the compiler that we want the in-line version by creating a code block {…} that accepts a string parameter called value.

  • Each octet is passed into the method, which, in turn, shifts the value 8 bits (times the number in our shift counter) and adds it to our result.  The first octet needs to be shifted 24 bits (3 bytes), the second 16 and the third 8.  The last octet does not need to be shifted (0 * 8 = 0) so it is evaluated to its decimal value and added to the result.

Easy peasy lemon squeezy.  And that’s how you use .Net – not just loops and old-school brute force – to convert an IP address to a decimal.

Hrm…actually…I guess I’m returning that as a string…

Converting an IP Address to Decimal

I am working through some interop code to manage a DHCP server from c#, which requires that I pass in IP addresses as their decimal value.

There are a number of ways to do this with loops and conversions and such but I wanted to write a way that actually uses some of the features of the .Net Framework.

This is a good example of using an anonymous delegate for iterating through a generic list (using the ForEach method) and building a hexadecimal string.  I use a simple formatting syntax to pad the lower-value bytes as required and then parse the entire string to get our decimal value.

private static string IpToDecimal(string ipAddress)
// split up the IP into octets and prep our string builder
List<string> octets = new List<string>(ipAddress.Split('.'));
    StringBuilder ipAsHex = new StringBuilder();

// loop through the octets and build up a hexidecimal string
octets.ForEach(delegate(string value)
    { ipAsHex.AppendFormat("{0:X2}", int.Parse(value)); });

// convert the hex to decimal and return
long decimalIP = long.Parse(ipAsHex.ToString(), NumberStyles.HexNumber);
    return decimalIP.ToString();