This is part of a general use utility that I frequently use. An odd bug that came out of this is that the overloaded method
Image.FromStream(Stream, Boolean, Boolean);
C#
was added in Service Pack 1 for .net v1.1 BUT NEVER DOCUMENTED!!!. Well, ok that’s not entirely true It is documented… in v2.0 documentation. So if you wrote this in 1.1 sp1 and deployed it to a machine without sp1 you’ll get a method not found exception when trying to load the image from stream using the above overload–non sp1 only has FromStream(Stream, Boolean)
Nothing like being incompatible with the same version of the framework eh?
C# Binary Serialization Oddities
Ok, it’s been a while since I wrote about anything, so sue me!
Today’s topic is an interesting find (at least to me)… When you serialize an object that has events (or a delegate) that have been assigned a value (and that value is outside of the class containing the event or delegate), .NET’s binary serializer will attempt to serialize the entire object who’s function is assigned to it (it’s an interesting thing to think about why they attempt to persist the event association as well). Said more simply, it will attempt to save the class being serialized, as well as all other classes who contain function definitions for those events or delegates.
Now, when we run the app, we get the following exception:
Exception message
An unhandled exception of type ‘System.Runtime.Serialization.SerializationException’ occurred in mscorlib.dll
Additional information: The type SerializationWoes.Class1 in Assembly SerializationWoes, Version=1.0.0.39766, Culture=neutral, PublicKeyToken=null is not marked as serializable.
What interests me here is why the binary formatter attempts to persist the event (and the other object, which contains the method for that event) as well.
A delegate / event is a function which is used like a variable. It can be assigned to and used just like a variable, so why not save its value as well. It makes sense when you think about it that way (Trust me. We spent far too much time wondering why some random UserControl was trying to be serialized into a custom object we had just written at work–until we realized that its events were being persisted as well). To persist a delegate or event, the framework also has to serialize the object whose function is the value of that event or delegate. Oddly enough, to do this, that object must be marked as [Serializable]. If not the above exception will be thrown every time you attempt to serialize your object containing the event.
There are 2 ways to get around this issue:
Make the class who subscribes to the event or delegate [Serializable] (if persisting that event / delegate is critical). This is often not the preferred choice.
Break your event out into a delegate / event Property. (as shown below)
The way to implement the latter is as follows. Change the public event to a private delegate, and a public event property. Our sample class changes to look like the following:
As you can see, we’ve added a using statement for System.Runtime.CompilerServices, which is actually for the MethodImpl attributes placed in the add and remove blocks of the event property.
Next, we created a private delegate, and public event property for the event. We added the necessary Add & Remove blocks for the event property (events use add & remove to keep event’s in sync) and add the MethodImpl attributes which take care of making the appropriate locks when we compile so that only 1 thread can access the event at a time to add and remove event definitions.
Next, we mark our delegate with the [NonSerialized] attribute, so that the serializer doesn’t attempt to serialize the value of our event’s delegate (aka our event handler).
The first suggestion–Marking your event handling class as [Serializable]–only works in a few situations, because we don’t always have code for the base class we’re extending (which also must be marked as serializable).
Here you have the final product which can have non-serializable objects define event handlers for it, and no exception will be thrown.
Now hopefully anyone having the same problem we had today at work (who has access to Google), won’t have to spend as long with the problem as we had to (not that an hour or two is much time, just annoying).
All About The @T Sign (C# Verbatim Identifier)
Bad form. Bad style. People will hate you. But, its totally legal.
I think I read this back in the language specification, or maybe a college professor said it, but I had forgotten about it until I read it on someone else’s blog.
namespaceTest {usingSystem;publicclassTest { staticvoidFoo(string@namespace) {bool@true = @namespace == "hello";if(@true) Console.WriteLine(@namespace); } } [STAThread]static void Main(string[] args) { Test.Foo("hello"); // prints out "hello" Test.Foo("world"); // prints nothing }}
C#
Odd eh?
If you’re ever have a sudden urge to use a reserved word, and just *HAVE* to have the word “true” as a variable name, @true will work.
Now… if you ever use that in public, you may be bludgeoned to death by co-workers.
its called a “verbatim” identifier, and should only be used in tandem with a goto statement for maximum annoyance.
C# 2 Language Specification
I’ve been reading over the new beta 2 C# specification lately. Good Read: Download it here
Cant wait until its production ready!
A Simple Line Control
Some time ago, I was working on a clone of Solitaire (the one that comes with windows), and I needed a line control (for… surprise surprise… the about box) like the one shown in its about window:
Example Line Control
after a brisk 2 seconds I came up with the following class:
Now to talk over a few points in this very simple control.
There were 2 requirements I had for the control:
It had to have an inherent size when I dragged it onto the canvass
it had to keep its aspect ratio (meaning I couldn’t make it look inconsistent)
I was able to accomplish this using a class designer, and by overriding the DefaultSize property of the control. I could have gotten much more fancy with the control, but since I was going to be the only one using it (well… that was the plan anyway :D), I kept it super simple.
This allows the control to default to this size. Anytime the control needs its base size, it uses the DefaultSize property. My first iteration of this control actually set the size property in the InitializeComponent method, but after reading up on it, using the DefaultSize property and specifying its size is the better solution.
The next thing was to keep its aspect ratio. This is achieved by providing my control with a designer. There are lots of articles out there on how to implement a designer, so I’ll leave that for another topic, and just discuss what I used in the designer to accomplish this. There is a property in the ControlDesigner called SelectionRules. This tells the control host at design time, how it can be used. Here’s our designer class. It’s actually an inner class of the Line control.
Notice we’re only overriding the SelectionRules property. It returns a bit flag value of which types of selection are possible in the designer. I didn’t want the control to be sized up or down, so I left those selection rules out. I did want it to be able to be sized right or left, and movable (and obviously visible), so these are the rules I return.
Other than this, all we need is to draw the line. This is achieved by overriding the OnPaint function in the control. I have provided functionality (however ugly it may be) for flat style, but for simplicity, I’ll speak to the normal line. The line in the about box has a highlight line and a shadow line. In our OnPaint method, I draw both lines using Control.Dark and Control.LightLight colors (this is so these colors can match whatever theme is being used).
Obtaining Key State info in .NET (A C# GetKeyState implementation)
Sometimes it’s usefull to know the current state of a given key. The platform SDK provides this functionality however .NET (at least v1.1) doesn’t provide access to it.
GetKeyState allows a developer to get information such as whether or not the given key is currently being pressed down, or if the key has a toggled state, whether or not it is currently being toggled.
The following utility is a .NET complement to the GetKeyState platform SDK function. I’ve created a struct which has 3 properties: Key, IsPressed, and IsToggled. These properties are set when GetKeyState is invoked. The return value of this GetKeyState is this struct, to give easy access to the data provided. As MSDN documentation states, the return value of this function is a number who’s high bit denotes whether or not the key is being pressed, and the low bit denotes whether or not the key is currently toggled. The “Key” property is simply being passed through. Another thing to take notice of, is that the platform sdk uses the virtual key VK_<XX> definition for keys. These have been mapped into .NET’s System.Windows.Forms.Keys enumeration, so that the value of the given Keys.<key> has the same value as the VK_<key> winuser.h definition.
Its admittedly small, and hardly anyone uses CRC32 for security purposes (at least I hope not), but it is a decent checksum generator for small non-critical items.
I needed a 32 bit sized number generator–I was implementing my own object.GetHashCode() and wanted to get an int hashcode for my own objects–and this seemed like a decent way to do it.
If you need for this code to be CLS compliant, you can change the method signature’s return type from uint to long and it will operate the same (the uint crc value will be implicitly converted from uint to long)
I’m also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package
Numeric Text Box: A Number Only Text Box Control in C#
Here’s my numeric only text control. I’ll admit there’s not much too it, and there are masked edit controls, but for those who dare…
What this does, is watch the Windows Message Queue for incoming messages (specifically WM_KEYDOWN and WM_PASTE). If a key has been pressed, it will look to see if the key is actually a number. It also looks to see if a paste command has been sent. if a key has been pressed and it is a numeric key (there are a few more keys for convenience sake) or the paste operation has been invoked (the contents of the paste operation are checked to make sure that anything that gets pasted is a number, else it fails to paste in the data) and its contents are numeric, allows that data to be pasted into the textbox.
Since originally posting this control on my older website, I’ve made some minor updates, checking the key pressed against its text character, checking to see if the resulting value will parse as a decimal and adding a few more keystroke character checks in there.
For Clarity sake, PreProcessMessage is invoked before the Message is sent into the message queue. If the control handles this message, it returns true, and the message ends there. If it returns false, it will send the Message into the message pump for further processing. WndProc is similar to WindowProc in win32, and one can filter messages sent here like they used to in standard windows programming. In this sample, we’re peeking at the KEYDOWN message, in the PreProcessMessage function. Commands are not sent through here, but are passed in WndProc, where we can listen, and handle this Message ourselves (because we need to check the contents of the clip board for numeric data).
If PreProcessMessage‘s Message contains numeric or one of our allowed keys, it returns false which forces the base TextBox to handle the instruction like normal, if not it returns true meaning we’ve handled it and it doesn’t get passed into the base TextBox control and nothing flows to the textbox. If WndProc receives a numeric only string in the clip board, then it sends the message to the base TextBox
base.WndProc(refm);
if the clipboard contains alpha or other data, it sets the LResult to 0, and returns without passing the message to the base TextBox effectively saying we’ve handled the message, and there’s no need to process it any further.
ScrollableRichTextBox
The standard RichTextBox’s “Auto-Scroll” functionality is so obscure, that most rarely ever find out how to use it. This class appends text and gives the option for the user to scroll to the bottom of the textbox.
There used to be a threading problem which would throw an unhandled exception every now and then, but due to an article recently published on msdn blogs this has been fixed, and the change is reflected above.