Archive

Archive for the ‘.NET’ Category

March Community Calendar

March 1, 2010 1 comment

Well, after a nice hiatus, the new Community season is underway!  I’ve really been missing it, but starting this week we’ll be back in the swing of things.  March is chock full of Community Goodness:

MSDN Roadshow

Microsoft Developer Evangelists Andrew Duthie, aka the Devhammer, and Dave Isbitski are hosting a series of MSDN Roadshows on Windows Azure. I will be attending this Wednesday, March 3rd, at the Richmond installment.  Roadshows are a great way to learn about new technologies and network fellow developers and Microsoft professionals.  Space is limited, so be sure to Register!

RVNUG

Roanoke Valley .NET User Group (RVNUG), will be meeting this Thursday, March 4th, from 6-8pm.  Chris Hylton will be presenting on The Enterprise Library.

Roanoke Code Camp

March 13th will be the 4th Annual Roanoke Valley Code Camp, hosted by RVNUG and great group of contributors.  I will be presenting a couple of sessions, Silverlight 4: Ready for Business and How I Develop WPF Applications.  I’m really looking forward to it: I hate to play favorites, but if I could only go to one Code Camp, this would probably be the one.  Fortunately, I don’t have to make such a horrible decision!  Space is limited, so make sure you register today to reserve your seat!

CHODOTNET

March 18th I will be presenting Silverlight 4: Ready for Business at the Charlottesville .NET User Group.  CHODOTNET is a growing, vibrant User Group, and if you are anywhere near there you should definitely check it out!  Be sure to visit the website as the meeting location has recently changed.

Southern Maryland Give Camp

March 19-21 will be the Southern Maryland Give Camp, the first East Coast Give Camp ever!  Give Camp is a charity coding event that promises to be challenging, rewarding, and lots of fun all at once!  A bunch of developers, DBAs, and designers will all converge on St. Mary’s College of Maryland for a weekend of non-stop programming.  The beneficiaries of this effort are a group of non-profit agencies who otherwise could not afford to hire professionals to develop these websites and applications.

And as if that doesn’t sound awesome enough in its own right, if we get 100+ developers to volunteer their time, Andrew Duthie will shave his head into a Mohawk!  Come on gang, I’d just love to see that!

Don’t miss out!

With so many great opportunities, I sure hope to see you out in the Community!  As always, be sure you say ‘Hi’!

Categories: .NET

My Community Year in Review

December 29, 2009 Leave a comment

Well, December is here and another Community Year is almost over.  Fortunately for me, there are a high number of quality events and user groups within reasonable driving distance, so for 2009 I thought I could swing a presentation a month. It turns out I was mistaken: while I did not present in every month, I actually ended up speaking at 15 events!

  1. Feb: RVNUG – Using Blend and Visual Studio Together
  2. Mar: Roanoke Code Camp – Templating and Data Binding in Blend
  3. April: RVNUG – Styling a WPF/EF Application (with Tolga Balci)
  4. April: Richmond Code Camp 2009.1 – Using Blend and Visual Studio Together
  5. May: HRNUG – Using Blend and Visual Studio Together
  6. May: Nova Code Camp – Using Blend and Visual Studio Together
  7. June: Blue Ridge Community College – Application Design Careers for Graphic Artists
  8. August: CHODOTNET – Using Blend and Visual Studio Together
  9. September: Raleigh Code Camp – Using Blend and Visual Studio Together
  10. September: Richmond NUG – Using Blend and Visual Studio Together (unscheduled)
  11. October: Richmond Code Camp 2009.2 – Using Blend and Visual Studio Together & Data Binding in Blend (2 presentations)
  12. October: Philly Code Camp – Data Binding in Blend
  13. October: CapArea Silverlight SIG – Silverlight 3 & Blend 3 Launch
  14. November: CMAP Code Camp – Using Blend and Visual Studio Together & Data Binding in Blend (2 presentations)
  15. November: RVNUG – Silverlight 3 & Blend 3 Launch

I also had the chance to attend several other events, most for the first time:

  1. Spring: Roanoke MSDN Road Show
  2. July: CodeStock
  3. August: DevLink
  4. October: Richmond Java User Group (to see Andy Hunt speak)
  5. November: PDC09
  6. December: Roanoke MSDN Road Show

And of course, about 20 regular RVNUG and CHODOTNET User Group meetings. I’ve been taking it easy in December, but I’m already looking forward to hitting the road again next year.  Here are events I already have on my calendar:

  1. Jan 12th: HRNUG – Presenting on Silverlight 4
  2. Jan 30th: Richmond SQL Saturday
  3. March 13th: Roanoke Code Camp
  4. March 18th: CHODOTNET (topic TBA)
  5. April 6th: CMAP NUG (topic TBA)
  6. May 22nd: Richmond Code Camp 2010.1
  7. May 19th: Innsbrook NUG (topic TBA)
  8. June 3rd: Richmond NUG (topic TBA)
  9. June 24-26: CodeStock
  10. October 2nd: Richmond Code Camp 2010.2

I’ll be adding more as the year goes.  There are a bunch of great Code Camps I don’t have on here yet: Raliegh, NoVa, CMAP, Philly, and more.  If you have a User Group and would like to schedule a presentation for the second half of the year, just email me (link is in the right hand sidebar) or hit me up on Twitter (@joelcochran).

No really, Thanks!

I want to say thanks to all of you out there, it’s been a great year for the for the community, and the people make it all worthwhile.  Have a great holiday season, and I’ll see you next year!

Categories: .NET

You know what they say about assuming

December 22, 2009 1 comment

I had an experience I thought was worth sharing.  As much as we all try to write reusable code, we still end up riding the Copy-Paste express more often than we care to admit.  (Come on, admit it… you know you do it…)  Of course, it helps if you do this with code that actually works…

The Copy-Paste Express

Several months ago, I wrote an application that required a custom Validation Rule for IP Address format validation. It worked great, and that project was the inspiration for my post on Custom Validation Rules.  Now, 2 months later, I want the same functionality in a new application.  While the ValidationRule class itself is reusable, the XAML code to implement it is not, so to add it to the new application, I copied the XAML over for the IPAddressTextBox.  Much to my dismay, when I executed the program the validation did not work.

Knowing that Application 1 worked as desired, I pored over the code and logic, line by line, and they were the same.  Since the XAML was a straight copy, they even used the same field and template names.  I was pulling my hair out, so I finally went back and read my post, comparing it to the code I had in place.  I was able then to find that some of the validation code was missing from the XAML.  Now I was really confused: the code on both applications was missing the same critical piece, so how could Application 1 possibly work?

If you don’t see it coming yet, it turns out that Application 1 no longer worked either.  I was testing the installed application and not the current copy of the code: when I ran it from Visual Studio, I experienced the same issue.  It took me a while to figure out what happened, but in this case my reliance on Blend was the culprit.  At some point I used Blend to update the Binding (I don’t remember why).  Normally this wouldn’t be a problem, but Custom Validation rules have to be inserted into the XAML manually.  By using Blend to update the binding, Blend removed all my custom validation logic.

Lesson Learned

The lesson here, of course, is not to make assumptions, but more importantly you need to test all changes to an application.  In this case, testing the IPAddressTextBox and the Custom Validation had been completed a long time ago, and since the functionality was never intended to be changed, it was never tested after it was complete.  And the working copies in the field were correct, so the bug would never have been reported, at least not until another release.  Even then, this particular piece of the software is typically only used once when the user configures the application, so even subsequent releases of current installs would never have revealed the issue.  Instead, it would have only shown up on a new install or a reconfiguration.  Even worse, since this is purely for validation to prevent the user from entering erroneous data, a new user would never realize the functionality was missing: instead, they would just be able to enter any value for an IP Address.  So who knows how long this bad code would have been out there, me all the while assuming it worked.

I’m still floundering in the Unit testing area, and I honestly don’t know if Unit testing would have caught this error or not since it was a GUI issue.  It does indicate to me that I need to get a better grasp on all things testing: what if this had been a similar but far more serious bug?  It also tells me I need to find more ways to get off the Copy-Paste Express.  While we’ll never get away from it completely, if I had taken the time to develop a custom control for IPAddressTextBox that implemented the validation, I never would have had this issue.  In any case, it really is the little issues that can teach you the most.

Categories: .NET

Another Silverlight Centering Trick

December 15, 2009 5 comments

Not too long ago, I posted about how to center a Silverlight Application within an HTML page.  Last weekend, I was working on a Silverlight application and I wanted to stretch the background brush across the entire browser, but retain the content in a fixed space in the middle of the screen.  I could have done this by creating a gradient and then applying it as the background in my HTML/CSS, but I wanted the ease of design and flexibility that I have within Silverlight.  Here is what I did to accomplish the trick.

Sizing the UserControl

To begin with, we have to set the width and height properties of the UserControl so that the UserControl will stretch to fill all available space within the browser.  We’ll start by setting Width and Height of our UserControl to Auto and the LayoutRoot container to a fixed size with a Background color so we can see it along with our Background work.  This way we can tell what effect we are actually having. 

[Note: click on the images for full size]

Content1

So far, it seems like we are centering, so all we should need to do is add a Background to the UserControl, right?  Unfortunately, that will not do what we want.  Adding a Background to the UserControl gives us the exact same results.  Since the screen shot is the same, I won’t repeat it, but if you are following along at home try it and you should get the same result. 

Also, not to be picky, but this is not actually centering: this is setting the HorizontalAlignment and VerticalAlignment properties to their default values of Stretch.  The Grid is actually stretching to fill up the available space, but it is still limited to its fixed size, so it gives the appearance of centering.  Not to worry, it’s a minor technicality.

Setting the Background

Our goal is for the Background, in this case a GradientBrush, to stretch across the entire surface of the browser window.  Above we saw that fixing the LayoutRoot to the size of our desired content won’t allow this to happen.  Instead, we’ll need to set the LayoutRoot Width and Height properties to Auto, and set the Background of the LayoutRoot element to the desired Gradient. 

Running the application at this point will show our Background filling the entire browser space.

StretchedGradient 

And here is the XAML:

StretchedGradientXAML

Centering the Content

Now that we have our Background properly visible across the entire surface of the browser, we need to center the Content inside our LayoutRoot Grid.  This is easily done by adding another Container to the LayoutRoot to act as a wrapper for our fixed size content.  This example shows a Grid, but I initially did it with a Canvas. I’ve added a Black Background color so you can see the content Grid.

ContentOverStretchedGradient

Now set the HorizontalAlignment to Center.  I think the default VerticalAlignment value of Top looks best, but of course you could center it or add some Margin around the content Grid to suit your preference. 

CenteredContentOverStretchedGradient

Now just add your content to the internal Grid, and you will have an automatically sized Silverlight page with centered, fixed size content.

Adding a Clipping Region

One last thing you should be aware of: if you are doing any animations with content off screen, using this method will make them visible outside the bounds of your content.  While this has some interesting potential, it is probably not the behavior you want. 

To correct this, you need to add a Clipping Region to your content Grid.  This will ensure that child elements of that Grid are only visible inside its visual boundaries. Since you can’t do this visually, you’ll need to edit the XAML directly.  The key here is to set the Clipping geometry, in this case a Rectangle, to be the same width and height as the content Grid.

ClippingRegionXAML

Conclusion

It’s important to note that since we are letting Silverlight do all the work, you do NOT want to use the HTML and CSS from the previous Centering post.  Doing so will result in only the width defined in the CSS being displayed.  Instead, just use the default HTML and CSS settings.

I like this approach better since it gives my application an integrated background.  It gives me more creative options and more control.  Let me know how it works for you!

Categories: .NET, Silverlight

Wrox Silverlight 3 Programmer’s Reference Book Review

November 19, 2009 2 comments

In July, I was offered the opportunity to review Wrox Publishing’s newly released “Professional Silverlight 3”, a massive full-color book covering nearly ever aspect of Silverlight 3.  I’ve long been a Wrox fan and as a WPF developer with a web background I have a keen interest in all things Silverlight, so naturally I jumped at the chance to review this new book.  Unfortunately, life did what it always does and prevented me from completing the review until now. 

NOTE: I finalized this article while attending PDC09, where Scott Guthrie announced Silverlight 4.  This release interval for Silverlight has been unprecedented: only three months after the official Silverlight 3 launch!  I am confident though that you will still find this book timely and valuable.

As expected, Wrox does not disappoint.  Authors J. Ambrose Little, Jason Beres, Grant Hinkson, Devin Rader, and Joseph Croney, all from Infragistics, have provided a wonderful edition that should capture the attention of both fledgling and experienced Silverlight developers.  In fact, the introduction and first four chapters should be mandatory reading: they provide the perfect overview to this game changing technology all .Net professionals should understand whether or not their particular interests run towards Silverlight.

If you have never read a full color technical book, you’ll quickly find this is wonderful addition.  The numerous graphics and screen shots jump off the page, making the material easily consumable.  In addition, all code and XAML samples are in full color as well, mimicking the default IntelliSense color scheme.  This is perhaps the best part of having a .NET volume printed in full color because it allows us to read code on the page in the same manner in which we are used to reading it on screen.  I’ve always found it a bit unpalatable to read code on the printed page, but this feature makes the code imminently more readable.

The book itself is very well written and easy to follow.  The style of the authors reveals their mastery of the material without being overbearing.  This is an extremely accessible book to those new to Silverlight but contains plenty of material for the more experienced developer.  While the text is clear and concise, in no way is this a light read.  Silverlight is a very large topic and any book that attempts to do it justice needs to be sized to the task.  That being said, I would not attempt this book, or many like it, cover to cover.  While none of the chapters is superfluous, if you are new to Silverlight or WPF, beyond the requisite 4 chapters mentioned above, I would begin with chapters 7, 8, 12 and 14.  I would tackle the rest of the chapters on an as needed basis.

Another item I really appreciated in this book was the frequent inclusion of Microsoft Expression Blend. Blend is an invaluable tool for developing WPF and Silverlight applications and yet I find it frequently passed over in technical publications.  Going forward, the more complex XAML based applications become, the more imperative it is going to be for developers to learn Blend, so it is nice to see a Silverlight book give Blend the attention it deserves.

On a scale of 1-5, I give this book 4.5 stars.  This book is exactly what it needs to be, a great reference aimed at professional developers.  I know that as I get more serious about my Silverlight development efforts, I will be reaching for this book frequently.

Categories: .NET, Book Reviews, Silverlight

IBM iSeries .NET Managed Provider ObjectDisposedException problem SOLVED

October 23, 2009 1 comment

I can’t believe how remiss I’ve been: this has been a big problem for me since early 2007, and we finally got it solved a couple of months ago, and I can’t believe I never blogged about it!

Two things to fix this:

1) Install iSeries Client Access V5R4.  Be sure to install the .NET Managed Provider if it is not already installed.  A full install will NOT do this, you must check the box to include it.

2) Install SI35287 on any PC that is connecting to the 400.  This is essentially V5R4 SP1 and will finally solve this little issue.

I do not know what the status of this bug on V6R1 is, but I will say that once I installed the SP this problem finally stopped.

Categories: .NET, AS400, iSeries, System i

Fall Community Calendar

August 3, 2009 1 comment

I was just going over my calendar and there are some great events coming up.  Here are the events I am attending or speaking at (that I know of at this time):

  • Aug 12-16th DevLink – I’ll be going to DevLink for the first time this year. The slate of presentations looks great and is full of a bunch of our finest community members.  Should be a great time!
  • Aug 20th CHODOTNET – I will be presenting on using Visual Studio and Blend together to develop WPF applications.  This is an entry level presentation intended to get developers over that initial hump of learning Blend and setting up WPF applications.  Meeting starts at 6:00.
  • Sep 10th MSDN Roadshow in Roanoke – I’ll be there with bells on to see presentations from Microsoft about Silverlight 3, Expression 3, Prism, MVVM, and RIA Services. If you can’t make this one, there are many others close by on the list.
  • Sep 10th RVNUG – What a deal!  Two for one!  After the Roadshow, G. Andrew Duthie, Microsoft Developer Evangelist extraordinaire will be presenting on lessons learned in developing real Silverlight applications.
  • Sep 17th CHODOTNET – Monthly meeting of the Charlottesville .NET User Group.  I haven’t heard yet what the presentation is, but I plan to be there regardless.
  • Sep 19th Raleigh Code Camp – I’ve submitted several presentations, so I hope to be speaking.
  • Oct 3rd Richmond Code Camp 2009.2 – I’m hoping to have something special for this event: I’ll keep you posted.

The only other item I have on my calendar is Philly Code Camp Oct 17 (no details out yet), but I don’t think I’ll be able to attend.  Just too many great events to choose from!

Of course you can always find more events all over the country at Community Megaphone, so do yourself a favor and get yourself to an event! I hope to see you around the community this fall.

Categories: .NET

Geek Gadget Friday: Amazon Kindle and The Apple Store

April 24, 2009 2 comments

I must preface this by letting you know that I am in no way a “Gadget Geek”.  I know many of my geek brethren are, but not me.  If you want to talk power tools or musical instruments, then I am there, but I’m just not that into gadgets for the sake of gadgets.  However, I do appreciate a good tool: if it happens to be in gadget form, then so be it!

The Amazon Kindle

I’ve been wanting an Amazon Kindle for some time now, ever since I saw one my Dad was borrowing from a friend at Christmas this year.  If you have yet to experience the magic of electronic paper, ubiquitous book shopping with instant downloads, then you don’t know what you are missing.  I have an entire library at my fingertips – or rather I will as I buy more books.  I bought it to replace my huge collection of tech books, you know, the ones that form the leaning tower of Pisa on my desk?  I always have at least half a dozen of them sprawled out, most of them open to the last page I was on or turned upside down marking the last problem I was trying to solve.

The Kindle is an amazing piece of technology.  It does not look or feel like a computer, which is good because it doesn’t really act like one either.  Follow the link above to get the juicy details, but here are the highlights.  Ubiquitous connection to the Kindle Store.  Sure, Amazon wants you to buy stuff, so it is easy to be cynical about this, but don’t: this is the best feature by far.  You can shop for a book directly from the reader, buy it in a one-click process (meaning no entering CC information), and have it downloaded to your Kindle in about a minute.  You can subscribe to Blogs and newspapers and they will be delivered to your device automatically.  You can store up to 1,500 books on your device at once.  You can read it in direct sunlight, but not in the dark since there is no backlight.  You can read it from almost a 90 degree angle.  It is very easy on the eyes and comfortable to read.  I have already found that I read faster on the Kindle.

Over the years, my comapny has spent thousands on technical books.  Yes,of course I use the Internet, but there is still nothing so rewarding as a book.  The great thing for my company is that the Kindle versions of the books are less expensive.  Add in the facts that there is no shipping cost and no wait time, and I was easily able to justify the expense.  I can find a book I need and be using it to solve a problem in minutes.  If you consume books like I do, then you owe it to yourself to check out the Kindle.

The Apple Store

I’m in my hotel room in Richmond for this weekend’s Richmond Code Camp.  I live a couple of hours away, so I took the opportunity to stop by the Apple Store.  Now, before I go any further, let me say that I am NOT an Apple guy.  I do not own or use iMac, iPOD, iPhone, iTV, iDishwasher, or any of the other i’s out there (except the “IBM System i”, but that is another story for another time.)  My 15 year old daughter, on the other hand, as well as my Dad, are iPOD users.  Unfortunately, hers quit working a while ago, so I took it into the store since I was in the neighborhood.  I was absolutely shocked at the experience.

I had in mind a pristine temple full of nerdy young 20 somethings where I would immediately be found out and scoffed at as “a PC guy”.  (I almost wore my Visual Studio 2008 shirt today: that could have been interesting.)  And, frankly, I expected to be condescended to by a kid who was still in grade school when I began programming.  I have to be utterly fair and say that instead, I found a pristine temple full of nerdy young 20 somethings where I was immediately be found out as “a PC guy”. However, I was *not* scoffed at, and I was not alone.  No one could feel alone in this store: there were probably a dozen associates, and every one of them was busy with a customer.  It was 2pm on a Friday in a near empty mall and the place was packed.

I definitely felt out of place: I wasn’t the oldest one in the store, but I was the most uncool.  The people there, customers and associates alike, oozed coolness.  Snoopy would have been proud.  There were a lot of … alternative … dress style.  Many piercings and tattoos, and at least one spiked mohawk – on an associate.  And I must say, I had a great experience.  The associates really knew their stuff and the store layout was excellent.  There were no cash registers: the checkout people were using handheld devices, servicing customers whereever they happen to be.  Folks, if you haven’t experienced this, you must check it out.  Apple got this right: PC retailers need to be paying attention.

And one more Apple note: I never quite got the fuss about the iPhone until I played with one today.  Great, another gadget to covet. My plan with Verizon is up in October…

Categories: .NET

Dynamically Switch WPF DataTemplate

January 9, 2009 10 comments

This post is based on this thread I started at MSDN Forums.  You can read the original situation and questions there: this post is more of a generic “how to”.

The Problem

In my original scenario I had a simple DataTemplate for ListBoxItems.  When an Item was Selected, I wanted to use a different DataTemplate that had more details.  The Binding was the same for each, so it seemed to me that I should simply be able to switch the DataTemplates at will.  Unfortunately, this is not the case.  I attempted to pull the selected item from the ListBox on the SelectionChanged event and assign it a different DataTemplate, but it did not work.  It still seems to me that it would be possible, but my efforts failed and I couldn’t find anything similar online.

The Solution

Since I couldn’t simply apply the DataTemplate resource to the SelectedItem, I had to find a different way.  After reading many suggestions for how to accomplish this, I settled on using a DataTemplateSelector.  This is a custom class with a method that returns a DataTemplate based on whatever criteria you need.  The custom DataTemplateSelector is then assigned to the element: in the case of ListBox it is the ItemTemplateSelector property.

I had previously read about DataTemplateSelector, but I was under the mistaken impression that it was used only in the context of state changes for the bound object.  This may have been because every example I found online that uses the selector approach was written with that scenario in mind.  It finally occurred to me, however, that I could access the Application state as well, which means that I could pull basically any information I needed, such as the currently selected item in my ListBox.

OK, so enough background: let’s get to how to do this.  Feel free to download the demo project for this post.

Create the Data Templates

There is nothing special about the DataTemplates themselves, so just create them as you normally would.  In the sample project, I have created a simple template and a complex template.  We’ll assign the complex template to the SelectedItem and the simple template to all the others.

Create the DataTemplateSelector

This is where the magic happens.  The code will process whenever a DataTemplateSelector instance has been assigned as well as everytime the DataSource changes.  I’ll get back to that in a minute, but for now you need to create your custom DataTemplateSelector class by extending DataTemplateSelector and overriding the SelectTemplate method:

public class PersonDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item != null && item is Person)
        {
            Person person = item as Person;
            Window window = System.Windows.Application.Current.MainWindow;
            ListBox list = window.FindName("PeopleListBox") as ListBox;

            Person selectedPerson = list.SelectedItem as Person;
            if (selectedPerson != null && selectedPerson.FullName() == person.FullName())
            {
                return window.FindResource("PeopleTemplateComplex") as DataTemplate;
            }
            else
            {
                return window.FindResource("PeopleTemplateSimple") as DataTemplate;
            }
        }

        return null;
    }
}

A few things to note:

  • the first parameter coming in is an object, so we need to test it to make sure it is the object type we expect.  Once we do that, we can then cast it to a usable instance of that type.
  • We use WPF’s knowledge of the Application to get a reference to the MainWindow where our ListBox is defined.  I then use the FindName method to get a reference to the ListBox.  This approach basically makes the entire application open to your selector instance.
  • Finally, we get a refence to the appropriate DataTemplate and return it.

So in the case of our ListBox, this method will be called for each ListBoxItem.  If no items are selected, then all of them will apply the simple template.

Assign the DataTemplateSelector

Now that we have our selector created, we need to use it in our XAML.  The first step towards this is to add a reference to our Window for the local Namespace.  I find it a good practice when I create the project to just automatically add this reference so I always have access to any local classes I may create, like ValueConverters.  Here is the line in the demo project that does this:

xmlns:prog="clr-namespace:DemoDataTemplateSelector"

Now we need to create an instance of our custom DataTemplateSelector in Window.Resources, like so:

<prog:PersonDataTemplateSelector x:Key="personDataTemplateSelector" />

Now we need to add the ItemTemplateSelector property to our ListBox and reference the object we created:

ItemTemplateSelector="{StaticResource personDataTemplateSelector}"

Finish the Code

If you run the application at this point, the simple template will be applied as selected, but the template will not change when an item is selected.  Above I said that the selector code would execute whenever the DataSource changes: selecting an item in the ListBox does not alter the DataSource, so the selector code is not activated.  The way around this is to create a new instance of the selector object and assign it programmatically to the ListBox.  In this case, we want it to execute when the SelectionChanged event fires:

private void PeopleListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    PeopleListBox.ItemTemplateSelector = new PersonDataTemplateSelector();
}

Now if you run the code it should work as desired, changing the DataTemplate from simple to complex for the selected item.

An Alternative Approach

Another approach posted here was to use a single DataTemplate containing a Trigger to switch them out.  The trick in my scenario was to figure out how to fire the trigger when the selected item changes.  I found a post at StackOverflow that demonstrated this well.  Merging these two approaches together achieved the result I wanted.  Here are a few key elements to this approach:

  • Change the original DataTemplates to ControlTemplates.
  • Create a new DataTemplate containing a single Control element that defines the default Template.
  • Add a DataTrigger that binds the RelativeSource to the Ancestor ListBox’s IsSelected property = true.
  • On the ListBox itself, instead of using the ItemTemplateSelector property, set the ItemTemplate property to the new DataTemplate.

Learning this method really opened my eyes to the power of DataTriggers.  I shied away from this at first because the XAML is more complex, and I’m still in the adolescent stages of XAML knowledge.  But having implemented it, there are definitely some benefits.  Using the DataTrigger approach requires a lot less coding: I do not have to create a custom DataTemplateSelector class; I do not need ListBox.SelectionChanged event; I do not need to declare the DataTemplateSelector instance in my XAML.  Since it can be argued that this is a purely UI problem, so keeping as much of it as possible in the XAML does a better job of separation of responsibilities.  Which means that in a scenario where designers really are separate from developers, the designer does not need to rely on the developer to achieve this feature.

Conclusion

Working through this has taken me a lot farther down the road of understanding binding, templates, and triggers.  And of course, both approaches are perfectly valid (so the sample code includes both approaches.)  I think for simple situations, triggers win hands down.  But for more complex scenarios, such as needing to base the DataTemplate selection on multiple factors, or processing more than two DataTemplates, then the custom DataTemplateSelector offers more flexibility and options.  In either case, this is one tool in my toolbox that I think I’ll be using a lot.

Categories: .NET

Storing an Image in an XML file

October 1, 2008 5 comments

I recently had a project that required a custom subset of data from a database be stored in an XML file. Each “row” of data also had a related image on a separate server. The project required that both the data and the image be transferred to a client for subsequent consumption by another program. In designing the project, it seemed unnecessarily complex to transport the data and the images as separate entities. Mostly the problem was that this process would simply add more moving parts, which would add to the complexity and increase the probability of “user inspired difficulties.”

Since both the data and the images were to be consumed by the same process, it appeared logical to embed the Image objects directly in the XML file as part of the data description. I found several examples on the web and eventually hobbled together my own version.

Saving the Image to XML

Since XML is ultimately just a formatted text file, the first step is to find a way to represent the Image object as text.

Bitmap bmp = new Bitmap(imageFileName);
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Bitmap));
XElement img = new XElement("image",
    Convert.ToBase64String(
        (byte[])converter.ConvertTo(bmp, typeof(byte[]))));
element.Add(img);

There are several things going on here. We want to convert the element to a byte[] so that we can extract a string representation of the object. To do this we create a TypeConverter object over the Bitmap type. Now we can use the TypeConverter to convert the Bitmap to a byte[]. Now, to properly encode the byte[] for writing to the XML file as a string, we convert it to a Base64 String.

Reading the Image from the XML file

Now that we have the Bitmap as part of our XML file, we need a way to read the Base64 String back into a Bitmap object:

string val = currentXml.Element("image").Value;
byte[] bytes = Convert.FromBase64String(val);
MemoryStream mem = new MemoryStream(bytes);
Bitmap bmp2 = new Bitmap(mem);

In this example, we retrieve the XML text, convert it to a byte[] using Convert.FromBase64String(), use that to create a MemoryStream, and finally use the MemoryStream to create the Bitmap. Naturally, you can make this more concise:

Bitmap bmp = new Bitmap(new MemoryStream(Convert.FromBase64String(currentXml.Element("image").Value)));

Wrapping it up

I’m a novice when it comes to encryption and such things, so I’m not claiming that this is the best solution. It did work and the application is functioning as designed, but I’d like to get some feedback about this method, comments, alternatives, etc. If there is a problem with this solution or a better way to do it, please comment below.

Categories: .NET
Follow

Get every new post delivered to your Inbox.