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 http://www.jameschambers.com/.

Thursday, June 11, 2009

IsFocused Never True on ComboBox in WPF

I recently responded to a thread on MSDN forums where a person was trying to get something to happen when the IsFocused property of a ComboBox was set to true in WPF.

Because of some of the work I had previously done on retemplating my own ComboBox, I quickly recognized that this was an issue with the way the control is templated. Largely, what is going on is that the ComboBox has a complex visual tree and when the ComboBox is in edit mode the control that has focus is actually a textbox inside the control template.

Thus, the ComboBox in WPF will never have its IsFocused property set to true.

I realized, though, that this has an effect on other things, such as trying to template a control through styles and triggers without replacing the entire visual tree.

Take the following style for a WPF Button:

<Style TargetType="Button" x:Key="ButtonStyle">
<
Style.Triggers>
<
Trigger Property="IsEnabled" Value="True">
<
Setter Property="Effect">
<
Setter.Value>
<
DropShadowEffect/>
</
Setter.Value>
</
Setter>
</
Trigger>
</
Style.Triggers>
</
Style>


If you put that in the Windows.Resources section of your window and set up a button to use that style, you’ll see that the buttonimage immediately reflects the DropShadowEffect.  Change the above IsEnabled to IsFocused and run the app.  The DropShadowEffect is only rendered if the button has focus.



Now, try the same thing with a style for the ComboBox:



<Style TargetType="ComboBox" x:Key="ComboBoxStyle">
<
Style.Triggers>
<
Trigger Property="IsEnabled" Value="True">
<
Setter Property="Effect">
<
Setter.Value>
<
DropShadowEffect/>
</
Setter.Value>
</
Setter>
</
Trigger>
</
Style.Triggers>
</
Style>



image This, again, works off the hop, even with IsFocused.  But if you set IsEditable to true, things change. 



As you can see from the screenies to the right, we don’t get our drop shadow rendered imageeven when the control has focus when it’s in  edit mode.









I think the only solution is to work around this through code-behind in the class.  This means that you’ll either need to plop some code into each form where you want to bind to the IsFocused property of the ComboBox, or you’ll need to create your own control library (not a bad idea if you’re trying to do something like this, I suppose).



So, I tried to go down that route.  My first attempt, though close, isn’t what we are looking for.  Indeed, it looks kinda cool and imagesome might find it funky, but it doesn’t put the shadow where we’d like – namely, on the ComboBox itself.



Here’s the code:



this.comboBox1.Loaded += delegate
{
TextBox tb = (TextBox)comboBox1.Template.FindName("PART_EditableTextBox", comboBox1);
if (tb != null)
{
Style tbStyle = new Style(typeof(TextBox), tb.Style);
Trigger effectTrigger = new Trigger();
effectTrigger.Property = TextBox.IsFocusedProperty;
effectTrigger.Value = true;

Setter dsSetter = new Setter(TextBox.EffectProperty, new DropShadowEffect());

effectTrigger.Setters.Add(dsSetter);
tbStyle.Triggers.Add(effectTrigger);
tb.Style = tbStyle;

}
};











Perhaps a simpler approach would be just storing a couple of style references in the window (or the control, if you’re rewriting) as such:



Style _cboDropShadowStyle;
Style _cboCleanStyle;


We build up our styles in the ComboBox.Loaded delegate:



            this.comboBox1.Loaded += delegate
{
// store the clean style
_cboCleanStyle = new Style(typeof(ComboBox), comboBox1.Style);

// build and store the dropshadowed style
_cboDropShadowStyle = new Style(typeof(ComboBox), comboBox1.Style);
Trigger effectTrigger = new Trigger();
effectTrigger.Property = ComboBox.IsEnabledProperty;
effectTrigger.Value = true;

Setter dsSetter = new Setter(ComboBox.EffectProperty, new DropShadowEffect());

effectTrigger.Setters.Add(dsSetter);
_cboDropShadowStyle.Triggers.Add(effectTrigger);
};



Then, finally, we write our event handlers (be sure to mark the XAML up accordingly):



private void comboBox1_GotFocus(object sender, RoutedEventArgs e)
{
comboBox1.Style = _cboDropShadowStyle;
}

private void comboBox1_LostFocus(object sender, RoutedEventArgs e)
{
comboBox1.Style = _cboCleanStyle;
}

I will continue to ponder a cleaner way, but for now this should be an acceptable approach.  You could easily build this into a custom control.  Or, you could extend the TextBox sample above into the custom control and expose a DependencyProperty called IsSeriouslyFocusedForRealYo that you set when the focus on that PART_EditableTextBox changes.

Tuesday, June 9, 2009

MVVM Code Generation

If you’re not already using the XAML Power Toys from Karl Shifflett, and you’re developing WPF/Silverlight apps with the MVVM pattern, well…get on it!

While he is a VB-er, he kindly makes his tools available to those of us on the dark side as well (those who develop in c#). Unfortunately there is a small issue with the code generation bits for the Create ViewModel For Class feature.

For all collection types the output is similar to the following:

private IEnumerable(Of QueueMember) _queueMember;


…instead of…



private IEnumerable<QueueMember> _queueMember;


This is a small cost for the significant benefits of this IDE enhancement and I wholly hope that, now that Karl is working for the mothership, that these features are carried into the new IDE.



Wouldn’t it be great to have a Pattern Extensions toolset, allowing for code-generation of stubs for various patterns? Of course, it would be extensible, so you could implement your own variations. Seems to me this is close already, with templates and snippets, just that it’s fractured. I routinely develop various bits working with Resharper, project templates and snippets to fill in the blanks, but an actual tool window and community support for all kinds of stub generation would be a great addition.

Monday, June 8, 2009

Thank You All

Thanks to everyone who made this last weekend’s Walk to Cure Diabetes such a success in such a small town.  We set a local record with 360 walkers and raised over $32,000 going directly to finding a cure for Type 1 Diabetes.

Here is the post from last week where I mentioned a video featuring my son: via YouTube.

To donate: go here.

Friday, June 5, 2009

Can’t Add New Items to WPF ModelView Application Projects from MVVM Template

I am running into a problem under certain circumstances with projects created by the WPF Model-View template for WPF applications in Visual Studio 2008.

When I try to add a new class to a project through the Visual Studio 2008 IDE I receive the following error message when I try to add a new class (or icon, LINQ to SQL file, etc):

image

I can reproduce this easily:

  1. Open Visual Studio 2008 (with the WPF Model-View-ViewModel Toolkit installed, download here).
  2. Create a new c# project with the new template.
  3. Accept the default and have it add a test project as well.
  4. Right-click on the Models folder, then Add->Class.
  5. Choose your name and click Add.  The error above is displayed.

I am running Vista 64, Visual Studio 2008 SP1 with .Net 3.5SP1. There are no add-ins loaded except the debugger. I do not (typically) run as Admin, but this makes no difference in this case as the same behaviour is observed either way.

I do not see this problem if I do not add the test project.

Thoughts on Raven so Far

The black art of software development is shrouded with geek-speak, bumped (read:missed) deadlines, over-budgetness and tens of thousands of lines of code that very few can appreciate the beauty of. I'm hoping to write a few words every week to keep focused on the tasks central to the success of this project.

Raven.HelpDesk

The first few bits in the Raven HelpDesk have been delivered for feedback to the the HelpDesk staff. It was well received and though not terribly functional, it has ensured that our environment is configured and they have everything they need to run the app. They are also now in the feedback loop to help establish features and process changes.

TheNextMostImportantThing

The idea on an agile project is that we're trying to get bang for the buck, continuously delivering what serves the company where it is needed most. Bang comes in two forms: saving money and making money. Which is really the same thing. Since the large part of development on Raven is internal, this means we are looking at the 'saving' side of the equation.

My goal is to be delivering a NextMostImportantThing every week. Some things will be more visible than others, some things will require process changes or new processes. With co-operation and guidance from co-workers, these will all move us to greater profitability, proficient staff, efficient software and better productivity.

Here are the five NextMostImportantThings in my queue (also referred to as Customer Stories):

  1. Identify Customer - Automated through Asterisk
  2. Create and reopen work tickets
  3. Assign and view assigned tickets
  4. Close work ticket
  5. Queue customer satisfaction survey requests

Next week, I am trying to complete "Identify Customer - Automated through asterisk", to which I am very close. I will be back into data conversion and correction mode early in the week and working with some domain experts here to get the next block of data bits in line.

Many of these stories play into each other. For example, two other stories (Poll Asterisk Queue, Present Asterisk polling results) were completed when I wrote the code this week for the Helpdesk Monitor (aka, Thompson Turkey). The queue monitor rose in priority this week as Queue Tip continues to fail on a daily basis, sometimes several times a day. This usually results in one or more emails, phone calls or visits to a technician, who must then reset the application.

Because I was preparing to work on the "Identify Customer" story, the Helpdesk Monitor was a great test-bed and served the purpose of retiring Queue Tip.

The YAGNI Principle

I have already received a number of requests for features in different parts of the app.

YAGNI stands for "You Aren't Gonna Need It". Developing under the YAGNI principle means that all feature requests and software development tasks are run through the filter of "Is this required? Is it desired? What will it cost? Can we make that money back? Will anyone actually use it? Has the person requesting the feature thought through these same questions? Do they fully understand the domain?".

Continuous input from folks in various departments helps to keep all stories in context of what is TheNextMostImportantThing and therefore helping move this project into the black as it saves the company money...in effect allowing it to pay for itself.

Thursday, June 4, 2009

Quick and Dirty Active Directory with c#

If you just want to grab some properties off a list of well-known entities in an Active Directory group, here’s some code to help you achieve that:

DirectoryEntry group = new DirectoryEntry(LDAP://CN=yourgroup,CN=users,DC=domain,DC=ca);
object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members)
{
DirectoryEntry entry = new DirectoryEntry(member);

Console.WriteLine(entry.Name);
Console.WriteLine(" {0}", entry.Properties["telephoneNumber"].Value);
Console.WriteLine(" {0}", entry.Properties["displayname"].Value);
}


If you know the data is in there, but you’re not sure what it is called in Active Directory, you can change that foreach loop to the following to dump everything you’re allowed to see.  This is pretty trivial in any .Net language, and the Active Directory properties are easy to work with (they’re just a collection):



foreach (object member in (IEnumerable)members)
{
DirectoryEntry entry = new DirectoryEntry(member);
foreach (string prop in entry.Properties.PropertyNames)
{
Console.WriteLine(" {0}: {1}", entry.Properties[prop].PropertyName, entry.Properties[prop].Value);
}
break;
}



I added the break in there so it just dumps the properties of the first entity in the list. 



Obviously, you’ll want to change the “yourgroup”, “domain” and “com” to whatever your server is configured to use.  Then, you’ll be well on your way to extracting properties for users stored in Active Directory.

Wednesday, June 3, 2009

Tough Kid on YouTube

I am so proud of my son, who gets over 3000 needles a year and still wears a smile on his face.

Please pledge online if you would like to support Juvenile Diabetes. (That’s http://jdrfca.donordrive.com/index.cfm?fuseaction=donorDrive.participant&eventID=700&participantID=13898 if you have trouble in your reader.)

Brandon has been living with Type 1 Diabetes since the age of 4 and receives daily insulin injections to keep him alive.

Juvenile Diabetes is not contracted from something you do or don’t do, from how much of something you eat, or how much exercise you get.  It is an auto-immune disease that strikes kids, who live with the disease their entire lives.

Thanks to all who have helped Brandon and his Screemin’ Beemers raise over $10,000 so far!