Tuesday, December 15, 2009

C# Compact Framework: Numeric TextBox

I was recently in need of a numeric textbox for a small compact framework application I’m writing at home. The best I could find on the web was this MSDN article, but unfortunately it wasn’t as bullet proof as I’d like it to be, so I used the code as a base, and wrote my own.

Features:

  • Allows numeric only entry
  • DecimalPlaces property
    • Specify how many decimal places the number should have. 0 decimal places = integer numbers (no decimal separator allowed)
    • Defaults to 2 decimal places
  • AllowNegatives property
    • Specifies whether to allow negative number values or not
    • When the number is negative, the font changes color from black to red
    • defaults to not allow negative number entries

Sample application with code:

The code isn’t exactly pretty, but it works, and that’s all I was after.

Feel free to take it for a spin, and let me know if you can break it, so I can fix any loopholes.

Monday, October 26, 2009

GetType From Referenced Assembly In Silverlight

I recently implemented a ValueConverter for our comboboxes in silverlight, whereby the translations for an enum would be shown as a list in the combobox, and when an item is selected, the value bound to the model would be whatever was described on the enumeration as the model value that gets persisted to the database (it’s a legacy database, so I couldn’t save the enumerated value on the model). Anyways, more on how that was done is for another blog post.

The converter gets an enumeration type as a converter parameter, so I needed to construct the type of enum at runtime (so I could get access the the enumerations that were defined, and the ModelValue attributes on each enumeration definition), since the converter should be able to handle any enumeration type that has been defined according to a specific convention. Trouble is, the enumerations were defined in a seperate silverlight assembly that was referenced from the client assembly, so I couldn’t just simply:

   1: Type type = Type.GetType("ClassLibrary1.Class1, ClassLibrary1");

… only if you specify the culture and the version in the above string parameter, will the type get returned, and since those change frequently, it wasn’t a practical solution.

So here’s helper method I wrote to get a type referenced in another assembly:

   1: public static Type GetAssemblyType(string assemblyName, string className)
   2: {
   3:     StreamResourceInfo info = Application.GetResourceStream(new Uri(assemblyName, UriKind.Relative));
   4:     Assembly assembly = new AssemblyPart().Load(info.Stream);
   5:     Type type = assembly.GetType(className);
   6:  
   7:     return type;   
   8: }

Usage:

… if you know the fully qualified class name and which assembly it’s in:

   1: Type type = GetAssemblyType("SilverlightClassLibrary1.dll", "SilverlightClassLibrary1.Class1");

… or if you only know the fully qualified class name, and don’t know which assembly it’s in:

   1: public static Type GetAssemblyType(string className)
   2: {
   3:     Type type = null;
   4:     foreach (AssemblyPart part in Deployment.Current.Parts)
   5:     {
   6:         type = GetAssemblyType(part.Source, className);
   7:         if (type != null)
   8:             break;
   9:     }
  10:     return type;
  11: }

usage:


   1: Type type = GetAssemblyType("SilverlightClassLibrary1.Class1");

Notice that in each case  that the class name that is specified is fully qualified with it’s namespace.


Happy Coding :)

Tuesday, October 20, 2009

Daily Links 20/10/2009

Silverlight 3: Calling a WCF service without a proxy using Binary XML

Silverlight 3's New Client Networking Stack

Clean shutdown in Silverlight and WPF applications
...with some MVVM Light Toolkit usage

Silverlight Toolkit adds DragDrop targets!

Silverlight Streaming to be discontinued
What a pity (it seems the Azure replacement service has costs associated with it) Guess I'm going to have to find another way (or remove) my silverlight advertisement on my blog page now :|

Event aggregator

"Agile is treating the symptoms, not the disease"
Highlighting a need to revert to the simplicity of development we had a decade ago.

LightSpeed 3.0 Beta Release

Microsoft SharedView finally RTM
"Connect with up to 15 people in different locations and get your point across by showing them what's on your screen"
It's free.

Terminals
codeplex project: "secure, multi tab terminal services/remote desktop client"
alternative application - RDTabs

Visual Studio 2010 dates and details

Re-imagining the Desktop with 10/GUI

Monday, July 13, 2009

Daily Links 13/07/2009

Silverlight 3 RTW Released

Silverlight RIA Services July Preview
now with go-live licence

Silverlight Toolkit July Release

Pushing Data From the Server to Silverlight 3 using a Duplex Wcf Service

20 Most Interesting Silverlight Tutorials

Silverlight 3 Polling Duplex Chat and Realtime Stock Updates

Creating a ComboBox Style AutoCompleteBox Control in Silverlight

EntitySpaces, Silverlight, and WCF a Fantastic Combination

Everything search
Search files and folders on your NTFS files instantly. It's not an indexing service, so it won't hog your resource like Google Desktop / Windows Search. From the forum: "When I read about it in PCWorld, I thought it might be worth a look. When I saw that it did wildcards (and was portable!), I figured it was definitely worth a try. When I read that it did REGULAR EXPRESSIONS I was certain I wanted it. And when it indexed all my huge volumes in a couple seconds, I nearly had a stroke"

Thursday, June 25, 2009

Event Extensions: Methods for firing events and managing event listeners

In most modern C# applications, generous usage of events have become the norm. Gone are the days where we were afraid to use them because of the "black magic" code that they seemed to execute.

Today, perhaps the opposite is true, and they are used too lightly, with disregard for the memory leeches they are (those small, black  slimly kind that you're never aware of what damage they're doing until it's too late).

Here's some code to make usage of the leeches a little easier :).

The typical firing of an event from C# code looks something like this:

   1: if (MyEvent1 != null)
   2: {
   3:     MyEvent1(this, EventArgs.Empty);
   4: }

There are 2 essential problems with this code:

  1. It's too many lines of code for something so mundane.
  2. What happens if there are more than 1 listeners listening to the event, and one of them throws an exception? Normal .NET behaviour dictates that the other listeners never get to hear about the event, but what if it's important that all listeners know about the event before application execution is halted?

Solution to problem #1: wrap the logic in an extension method

   1: MyEvent1.Raise(this, EventArgs.Empty);

there - isn't that better? Here's sample of the implementation:

   1: public static void Raise(this EventHandler handler, object sender, EventArgs e)
   2: {
   3:     if (handler != null)
   4:     {
   5:         handler(sender, e);
   6:     }
   7: }

Solution to problem #2: expand on the extension method (now that all the logic is conveniently in one place)

   1: MyEvent1.Raise(this, EventArgs.Empty, true);

...where the boolean parameter tells the extension method to make sure that all the event listeners get to hear about the event before throwing an exception. The exception that is then thrown, is an EventListenerException, which is just basically a wrapper for all exceptions that occurred on the event listener's event handling code.

sample implementation: (called from the event extension method)

   1: private static void ManageEventListeners(IEnumerable<Delegate> delegates, object sender, EventArgs e)
   2:       {
   3:           EventListenerException eventListenerException = null;
   4:           foreach (Delegate listner in delegates)
   5:           {
   6:               //the listner could throw an unhandled exception in the handler method
   7:               //make sure that the other listners still handle event if this is the case
   8:               try
   9:               {
  10:                   listner.DynamicInvoke(new[] {sender, e});
  11:               }
  12:               catch (TargetInvocationException ex)
  13:               {
  14:                   //add a new event listner
  15:                   EventListener eventListener = new EventListener
  16:                                                   {
  17:                                                       Listener = listner,
  18:                                                       ListenerException = ex.InnerException
  19:                                                   };
  20:                   
  21:                   //NOTE: The exception which occurs is "TargetInvokationException", but the 
  22:                   //actual exception which occurs in the listner is contained in the innerException
  23:  
  24:                   //add listner to eventListnerException
  25:                   if (eventListenerException == null)
  26:                   {
  27:                       eventListenerException = new EventListenerException();
  28:                   }
  29:                   eventListenerException.EventListenerCol.Add(eventListener);
  30:               }
  31:           }
  32:  
  33:           //if an exception was thrown by one of the listner's event handlers
  34:           if (eventListenerException != null)
  35:           {
  36:               throw eventListenerException;
  37:               //then re-throw the exception that thrown in the handler 
  38:           }
  39:       }

Here's some sample code with unit tests included in case you need to play with the code (NUnit 2.4.7 & VS 2008)



PS: It's Silverlight compatible (of course :) )

Daily Links 25/06/2009

Silverlight: Product Maintenance Application ( Part 1 - Authentication, Roles and Logging In )

Silverlight - Resizing Childwindow

Synchronous Web Service Calls with Silverlight 2: Dispelling the async-only myth

Distribute Mobile Applications On Windows Marketplace

Visual Studio's Database Publishing Wizard and the new 1-Click Web Deployment

Visual Studio 2010: Web application packaging and publishing

Microsoft ADO.NET Entity Framework Feature Community Technology Preview 1

Feature CTP Walkthrough: Self Tracking Entities for Entity Framework

Feature CTP Walkthrough: Code Only for Entity Framework

Thursday, April 30, 2009

Daily Links - 30/04/2009

Silverlight 3 - Simple "Flip Control" built on PlaneProjection

Silverlight 3 - Simple Control for Online/Offline

Silverlight Count Down Control - Your days are counted

Silverlight out-of-browser apps: Local Data Store
Comprehensive article on storing data to the client file system

Creating Rich Data Forms in Silverlight 3 - Introduction

Construct domain models faster than ever before!
ORM I am seriously considering for my home project. A little birdy told me there is some sweet silverlight support coming in their next release which is due shortly.
The big win for me is the Domain Driven Design which they follow in the article highlighted above, added to this Mindscape's "convention over configuration" development approach, and excellent price entry point (which is esp important for developers like me working at home on a tight budget)

Getting your Func along with your Action on

All Your Repositories Are Belong To Us
Discussion on Repository vs Command Query Seperation (CQS) Patterns

RefCard for Scrum
Handy summary of the scrum process

Agile Adoption - decreasing time to market

StatSVN
"generates various tables and charts describing the project development"

Shelving Subversion
Would be nice if this mechanism was more actively supported by the SVN toolsets. I want my "Shelve" and "Preserve Pending Changes" button and checkbox in Ankh!

Getting up and Running Quickly with ScrewTurn Wiki & SQL Server