Internet Explorer added something called expression to CSS, something purists have booed at for mingling javascript and CSS. Well, boo back! I happen to like stuff that can solve problems. If I were at Microsoft I would create an entire subset of javascript and css functionality. But hey, that's just me.

Anyway, I have decided to use expression to run an initialize function on newly created elements. It would work like this:
initialize:expression(window.initializeElement?initializeElement(this):null);
This CSS bit tells Internet Explorer (and none of the other browsers) that the initialize style property should get the value of the initializeElement function every time the browser refreshes the layout of the element. In the function itself I would do something like this:
function initializeElement(elem) {
if (!elem.style.initialize) {
doSomethingWith(elem);
}
return true;
}
This basically executes doSomethingWith on each element matched by the CSS rule and only once.

Good theory, but in practice it was terribly slow and, after a while, it managed to kill Internet Explorer with a strange System.AccessViolationException: Attempted to read or write protected memory error.

What happened? The slowness, I gathered after a while, was caused by the function doSomethingWith because it changed the style of the element. That meant that the css rule was being applied again before the function ended and returned true. Changing things to:
function initializeElement(elem) {
if (!elem.style.initialize) {
elem.style.initialize=true;
doSomethingWith(elem);
}
return true;
}
fixed it.

The error that killed Internet Explorer was even stranger. After a while I narrowed it down to using jQuery. I have no idea what it did, probably trying to access computedStyle or something like that. The thing is that changing an $(elem).height() with elem.offsetHeight solved it.

I actually didn't know that a 32bit program could not use more than 2Gb of virtual memory by default. It makes sense, now that I think of it, but I just didn't make the connection. My office computer has 3Gb of memory and there is also the swap file, so having a program using more than 2GB of memory would be beneficial. And I am talking about Visual Studio here, especially since today I got an error I've never seen before: "Not enough storage is available to complete this operation".

So I've stumbled upon this article: Hacking Visual Studio to Use More Than 2Gigabytes of Memory which told me how to convince Visual Studio to use more than 2GB of memory. Also, since I am a ReSharper user, I found this little wrapper for Visual Studio that makes it use a different memory allocation method that reduces memory fragmentation: OutOfMemoryException Fix.


Short story shorter (for XP users with Visual Studio 2008 only - read the full articles for other configuration):
  1. Edit boot.ini to have the /3GB option
  2. Use editbin /LARGEADDRESSAWARE devenv.exe to change Visual Studio to have IMAGE_FILE_LARGE_ADDRESS_AWARE in the process header (editbin can be found in \Program Files\Microsoft Visual Studio 9.0\VC\bin\
  3. Download the Jetbrains devenv wrappers and change the signature of the Visual Studio shortcut to point to devenv2008_wrap.exe instead of devenv.exe
  4. (of course) Restart the computer


Update:
Thanks to the warnings from Lex Li, I went to study the /3G switch some more. The most important thing seems to be to also use the /USERVA switch to tune the /3G functionality.

More details here:
Memory Management - Demystifying /3GB
Summary of the recent spate of /3GB articles.


Today I've released version 1.2 of the HotBabe.NET application. It is a program that stays in the traybar, showing a transparent picture, originally of a woman, sitting on top of your other applications. Clicks go through the image and the opacity of the picture is set so that it doesn't bother the use of the computer. When the CPU use or the memory use or other custom measurements change, the image changes as well. The original would show a girl getting naked as the use of CPU went up. Since I couldn't use what images it should use, I did my own program in .NET. This blog post is about what I have learned about Windows Forms while creating this application.

Step 1: Making the form transparent



Making a Windows Form transparent is not as simple as setting the background transparent. It needs to have:
  • FormBorderStyle = FormBorderStyle.None
  • AllowTransparency = true
  • TransparencyKey = BackColor
However, when changing the Opacity of the form, I noticed that the background color would start showing! The solution for this is to set the BackColor to Color.White, as White is not affected by opacity when set as TransparencyKey, for some reason.

Step 2: Making the form stay on top all other windows



That is relatively easy. Set TopMost = true. You have to set it to true the first time, during load, otherwise you won't be able to set it later on. I don't know why, it just happened.

Update: I noticed that, even when TopMost was set, the image would vanish beneath other windows. I've doubled the property with setting WS_EX_TopMost on the params ExStyle (see step 4).

Step 3: Show the application icon in the traybar and hide the taskbar



Hiding the taskbar is as easy as ShowInTaskbar = false and putting a notification icon in the traybar is simple as well:
_icon = new NotifyIcon(new Container())
{
Visible = true
};
Set the ContextMenu to _icon and you have a tray icon with a menu. There is a catch, though. A NotifyIcon control needs an Icon, an image of a certain format. My solution was, instead of bundling an icon especially for this, to convert the main girl image into an icon, so I used this code.

Step 4: Hide the application from Alt-Tab, make it not get focus and make it so that the mouse clicks through



In order to do that, something must be done at the PInvoke level, in other words, using unsafe system libraries. At first I found out that I need to change a flag value which can be read and written to using GetWindowLong and SetWindowLong from user32.dll. I needed to set the window style with the following attributes:
WS_EX_Layered (Windows Xp/2000+ layered window)
WS_EX_Transparent (Allows the windows to be transparent to the mouse)
WS_EX_ToolWindow (declares the window as a tool window, therefore it does not appear in the Alt-Tab application list)
WS_EX_NoActivate (Windows 2000/XP: A top-level window created with this style does not become the foreground window when the user clicks it).

Then I found out that Form has a virtual method called CreateParams giving me access to the style flag value. Here is the complete code:
protected override CreateParams CreateParams
{
get
{
CreateParams ws = base.CreateParams;

if (ClickThrough)
{
ws.ExStyle |= UnsafeNativeMethods.WS_EX_Layered;
ws.ExStyle |= UnsafeNativeMethods.WS_EX_Transparent;
}
// do not show in Alt-tab
ws.ExStyle |= UnsafeNativeMethods.WS_EX_ToolWindow;
// do not make foreground window
ws.ExStyle |= UnsafeNativeMethods.WS_EX_NoActivate;
return ws;
}
}


However, the problem was that if I changed ClickThrough, it didn't seem to do anything. It was set once and that was it. I noticed that changing Opacity would also set the click through style, so I Reflector-ed the System.Windows.Forms.dll and looked in the source of Opacity. Something called UpdateStyles was used (This method calls the CreateParams method to get the styles to apply) so I used it.

Update: Apparently, the no activate behaviour can also be set by overriding ShowWithoutActivation and returning true. I've set it, too, just to be sure.

Step 5: Now that the form is transparent and has no border or control box, I can't move the window around. I need to make it draggable from anywhere



There is no escape from native methods this time:
private void mainMouseDown(object sender, MouseEventArgs e)
{
// Draggable from anywhere
if (e.Button == MouseButtons.Left)
{
UnsafeNativeMethods.ReleaseCapture();
UnsafeNativeMethods.SendMessage(Handle,
UnsafeNativeMethods.WM_NCLBUTTONDOWN,
UnsafeNativeMethods.HT_CAPTION, 0);
}
}
Both ReleaseCapture and SendMessage are user32.dll functions. What this mouse down event handler does is say to the Window that no matter where it was clicked, it actually clicked the draggable area.

Step 6: Remove flicker



Well, I am getting a bit ahead of myself, here, the flickering becomes annoying only when I implement the blending of an image into another, but since it is also a style setting, I am putting it here:
SetStyle(ControlStyles.AllPaintingInWmPaint 
| ControlStyles.UserPaint
| ControlStyles.OptimizedDoubleBuffer, true);
This piece of code, placed in the Form constructor, tells the form to use a double buffer for drawing and to not clear the form before drawing something else.

Update: It seems the same thing can be achieved by setting the Control property DoubleBuffer to true as it seems to be setting ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint and ControlStyles.UserPaint seems to be set by default.

Step 7: Blend the images one into the other



Well, in order to make an image blend nicely into the next, I used a Timer. 10 times a second I would decrease the opacity of the first, increase the opacity of the second and draw them one over the other.

A small detour: if you think about it, this is not absolutely correct. A 70% opacity pixel blocks 70% of the light and lets 30% of the image behind show. If the image underneath has 30% opacity, then it shows 30% left from 30% of the image and it doesn't get opaque. But if I just set the opacity of the bakground image to 100%, it shows really strong on the parts of the images that are not overlapping, where image1 is transparent and image2 is not.

Unfortunately there is no resource friendly way to read write/pixels. It's either GetPixel/SetPixel in a Bitmap class (which are very slow) or using pinvoke again. I prefered to use the opacity hack which looks ok.

I was already using an extension method to invoke any change on the form on its own thread (as the Timer ran on its own thread and I would have gotten the "Cross-thread operation not valid: Control [...] accessed from a thread other than the thread it was created on" exception or "Invoke or BeginInvoke cannot be called on a control until the window handle has been created"):
public static void SafeInvoke(this Control control, Action action)
{
if (control.IsDisposed)
{
return;
}
if (!control.IsHandleCreated)
{
try
{
action();
}
catch (InvalidOperationException ex)
{
}
return;
}
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action();
}
}

This is where I got the "Object is currently in use elsewhere" InvalidOperationException. Apparently the Image class is not thread-safe, so both the timer and the form were trying to access it. I tried locking the setter and getter of the Image property on the class responsible with the image blending effect, with no real effect. Strangely enough, the only solution was to Clone the image when I move it around. I am still looking for a solution that makes sense!

Step 8: Showing the window while dragging it



Using WS_EX_NOACTIVATE was great, but there is a minor inconvenience when trying to move the form around. Not only that the image is not shown while moving the form (On my computer it is set to not show the window contents while dragging it), but the rectangular hint that normally shows is not displayed either. The only way to know where your image ended up was to release the mouse button.

It appears that fixing this is not so easy as it seems. One needs to override WndProc and handle the WM_MOVING message. While handling it, a manual redraw of the form must be initiated via the user32.dll SetWindowPos method.

The nice part is that in this method you can actually specify how you want the form draw. I have chosen SWP_NoActivate, SWP_ShowWindow and SWP_NoSendChanging as flags, where NoActivate is similar with the exstyle flag, ShowWindow shows the entire form (not only the rectangle hint) and NoSendChanging seems to improve the movement smoothness.

Quirky enough, if I start the application without Click through set, then the rectangle hint DOES appear while dragging the window. And with my fix, both the image and the rectangle are shown, but not at the same time. It is a funny effect I don't know how to fix and I thought it was strange enough to not bother me: the rectangle is trying to keep up with the hot babe and never catches on :)

Step 9: Dragging custom images



I am a programmer, that means that it is likely to add too many features in my creations and never make any money out of them. That's why I've decided to add a new feature to HotBabe.NET: droppping your own images on it to display over your applications.

At first I have solved this via ExStyle, where a flag tells Windows the form accepts files dragged over it. A WndProc override handling the WM_DROPFILES message would do the rest. But then I've learned that Windows Forms have their own mechanism for handling file drops.

Here are the steps. First set AllowDrop to true. Then handle the DragEnter and DragDrop events. In my implementation I am checking that only one file is being dropped and that the file itself can be converted into an image BEFORE I display the mouse cursor hint telling the user a drop is allowed. That pretty much makes the ugly MessageBox that I was showing in the previous implementation unnecessary.

Step 10: Reading files from web, FTP, network, zip files, everywhere, with a single API



Reading and writing files is easy when working with local files, using System.IO classes, but when you want to expand to other sources, like web images or files bundles in archives, you get stuck. Luckily there is a general API for reading files using URI syntax in the System.Net.WebRequest class. Here is a sample code for reading any file that can be represented as an URI:
WebRequest req = WebRequest.Create(uriString);
using (var resp = req.GetResponse())
{
using(var stream= resp.GetResponseStream())
{
// do something with stream
}
}


WebRequest can also register your own classes for specific schemas, others than http, ftp, file, etc. I created my own handler for "zip:" URIs and now I can use the same code to read files, web resources of zipped files.

One point that needs clarification is that at first I wanted an URI of the format "zip://archive/file" and I got stuck when the host part of the URI, mainly the archive name, would not accept spaces in it. Instead use this format "schema:///whatever" (three slashes). This is a valid URI in any situation, as the host is empty and does not need to be validated in any way.

The rest are details and you can download the source of HotBabe.NET and see the exact implementation. Please let me know what you think and of any improvement you can imagine.

I've stumbled upon this Windows port of a Linux application called HotBabe. What it does is show a transparent image of a girl over your applications that looks more naked as the CPU is used more. I wanted to use my own pictures and explore some of the concepts of desktop programming that are still a bit new to me, so I rewrote it from scratch.

The project is now up on Github and is functional. Please report any bugs or write any feature requests here or on the project page in order to make this even cooler.

Features:
  • Custom images responding to custom measurements
  • Custom measures (included are Cpu, Memory and Random, but an abstract class for custom monitor classes is included)
  • AutoRun, ClickThrough, Opacity control
  • Interface for custom images and custom monitors
  • XML config file


Update: After adding a lot of new features, I've also written a blog entry about the highlights from HotBabe.NET's development, a "making of", if you will. You can find it here: Things I've learned from HotBabe.NET.

Enjoy!

This will be a long article, one that I intend to add on while understanding more about the MVVM pattern and patterns in general. Also, while I am sure I will add some code during the development of the post, this is intended mostly as a theoretical understanding of the said pattern.

For an easy and short explanation of the concepts, read this article: WPF Apps With The Model-View-ViewModel Design Pattern.

The start of every concept research these days seems to start with Wikipedia. The wiki article about Model View ViewModel says that MVVM is a specialization of the PresentationModel design pattern introduced by Martin Fowler specific for the Windows Presentation Foundation (WPF). Largely based on the Model-view-controller pattern (MVC).
Further reading from Martin Fowler's site on the MVC pattern, which seems to stand at the core of all this specialization, revealed this: Probably the widest quoted pattern in UI development is Model View Controller (MVC) - it's also the most misquoted. [...] In MVC, the domain element is referred to as the model. Model objects are completely ignorant of the UI. [...] The presentation part of MVC is made of the two remaining elements: view and controller. The controller's job is to take the user's input and figure out what to do with it. There is a lot more there, about how in the early MVC concept there were no events or binding of any sort. Instead the controller would get the input from the UI, update the model, then the View would change as the model changes using some sort of Observer pattern. Even from these few quotes, one can see that in this "holy trinity" there are actually two basic actors: the Model (which, to make it easier to differentiate later on from other models, I will call Data Model) and the Presentation (controller+view in MVC).
Let's see what the PresentationModel pattern is all about: Presentation Model pulls the state and behavior of the view out into a model class that is part of the presentation. The Presentation Model coordinates with the domain layer and provides an interface to the view that minimizes decision making in the view. The view either stores all its state in the Presentation Model or synchonizes its state with Presentation Model frequently. As I see it, it introduces a new model, one specific to the Presentation side but independent of the UI controls. Martin Fowler specifically says about the PresentationModel pattern: Probably the most annoying part of Presentation Model is the synchronization between Presentation Model and view. It's simple code to write, but I always like to minimize this kind of boring repetitive code. Ideally some kind of framework could handle this, which I'm hoping will happen some day with technologies like .NET's data binding. and Presentation Model allows you to write logic that is completely independent of the views used for display. You also do not need to rely on the view to store state. The downside is that you need a synchronization mechanism between the presentation model and the view. This synchronization can be very simple, but it is required.

I also find this article about different Model View Presenter patterns very informative and the diagrams easier to understand than Fowlers UML or whatever that horrible diagraming he uses is :)

This brings us to MVVM. It is basically the PresentationModel pattern, where WPF/Silverlight types of complex binding take care of the synchronization of View and ViewModel. For me, one of the most important aspects of this approach is that the complex interactions between UI components (and that don't involve the data in the DataModel) can be left in the View and completely ignored further down. That makes interchanging Views something very easy to do, as the entire "UI logic" can be separated from the more general presentation logic. In this, I see that the UI becomes a third layer by the introduction of the ViewModel/PresentationModel in between the Data Model and the Presentation.
I have imagined doing this in a Web or stricly Windows Forms environment. As Fowler said, the plumbing required for synchronization between the view and the viewmodel makes it not worth the effort. That is where the WPF Data Binding comes in.

Let's start the MVVM chapter with a simple example. There is a need to search people by using different filters, display the list of found people and give the ability to click a person and see the details in a separate detail pane. The filters can be simple (Google like textbox) or complex (specific role, age, etc searches). The complex filters of the search are hidden in a separate panel that can be shown or not.
An ASP.Net or Windows Forms application would probably create a form containing the searchbox, the additional filters in a panel with a checkbox or button to show/hide it, the details panel with textual information and a grid where the list of people would be displayed. Events would provide all the needed plumbing, with the code executed on them placed in the code behind of the form, changing what was needed. See, the code behind was already an attempt to separate the presentation from code, although the separation was mostly symbolic. One might have employed a flavour of the MVC pattern, creating a separate controller class that would have worked with the data model and the form (as a view) through interfaces. That means a lot of plumbing, anyway.
In WPF, one creates the form, as in the Windows Forms approach above, but then it binds no events (or very few, I will talk about that later). Instead, it uses data binding to link UI components to properties that it expects to find on the object that will be provided to the view as a DataContext, that is the ViewModel. It doesn't know what the format of this object is and, indeed, the properties are found using reflection, which makes this slightly slower than other methods.
What this means is that any code that reacts to a change of a UI component would be placed on an event handler of the property to which it is bound. When the property changes, stuff happens, not when someone clicks a checkbox. This makes the architecture a lot more testable from code, as all a test needs to do is change a property, not perform a click. It also means that a lot of extra plumbing must be done on those properties, for example the ViewModels could implement INotifyPropertyChanged and then notify on any property being changed. Also lists must not only inform on the get/set operations on them, but also on their items, which implies using ObservableCollection, ObservableDictionary, BindingList and other objects that observer their items and notify on change. On the Views, Dependency and Attached properties come into play , and I will link to some explanatory posts later on. They are extremely important in WPF, because they compute the value, rather than store it, but that's another story altogether.
What this also means is that events, in the way there are used in Windows Forms scenarios, are almost a hinderance. Events cannot be bound. If they are handled in bits of code that change properties in the ViewModel, then the code must either have a reference to a specific type of ViewModel, which defeats the whole purpose of MVVM, or to read/write properties using reflection, which means extra plumbing in the View code. Not that this cannot be done, and there are several solutions to that. However, it would be ugly to write a view completely in XAML, binding everything you need to properties that are to be found on the ViewModel, then starting writing code just for a few events. Here is where commands come in.
The Command pattern is an Gang of Four pattern, useful in WPF by providing objects that can be bound and that encapsulate a behaviour that will be executed. Read more about Commanding on MSDN. Many WPF controls exposes events as well as commands for common actions, for example the Button class exposes the OnClick event, but also the Command property (which will be executed on click) and the Clicked property (which will be set on click).
Commands in WPF implement the ICommand interface which exposes the Execute method as well as the CanExecute method. A default WPF button that has a command bound to its Command member will appear as disabled if the CanExecute method returns false, that because the ButtonBae class implements ICommandSource. More about commands when I present the RelayCommand class, which has become quite commonplace in the MVVM world.
A problem is that not all controls have a command for every concievable event. A solution is, of course, to inherit from the control and create your own command for a specific event. It only requires that you handle the event internally, expose a property that implements ICommand and execute that command inside the event handler. This brings the advantage that the control can be reused with minimal changes in the XAML. There are other solutions, one of them is to use Attached Properties. If you don't want an attached property for every event that you use, read this article. A very comprehensive article about the application of Commanding in WPF can be found here: WPF Command-Pattern Applied.

So far so good. Using the concepts above we can separate the UI from the data completely, as the View only uses binding on the Data Model and can be replaced with any other View that binds to existing properties. This pattern can be used on any level, be it the window or the user control level. Controls that are strictly UI, of course, don't need to implement MVVM. There are other aspects that were not covered here, more specific to WPF, like Routed Commands and Events and concepts like global messaging. But since they are not really part of the MVVM idea, I will leave them for other posts.
There is also the question of code. I will not be doing any in the post for now. However, I will be ending this with a few links that seem relevant.

Extra links:
Adventures in MVVM -- Ball of Mud vs MVVM
Hands-On Model-View-ViewModel (MVVM) for Silverlight and WPF
Exploring a Model-View-ViewModel Application; WPF Password Manager, Cipher Text

Another important thing to consider is the myriad MVVM frameworks out there, all of them implementing some helper classes and prewiring of applications. I was talking earlier about the RelayCommand. Imagine you want to create a ViewModel that exposes a Command. That command would need to implement ICommand, therefore being an object that has two methods: one to execute and the other to determine if it is possible. Creating a class for each such command would be tedious. The RelayCommand is a generic class of T (where T is the type of the command parameter) with a constructor that accepts an Action of T and a Func of T. You instantiate it with the methods in your class that are to be used and that is it.

I will update this material with more information as it becomes available and if I have enough time for it.

I've encountered this situations a couple of times, what happends is that, at the end of the body of the document or of a major element like a form or a page wide div, sometimes (I haven't really been able to reproduce it at will) hidden elements start having height. This includes hidden divs and spans and even script elements. It seems to be happening mostly on Internet Explorer, but the behaviour has reportedly also been found on Opera and even Chrome.

For a specific example, I had this page with a lot of script tags at the end of the form element. Curiously, only when some spans with display:none were added at the end of the body element the problem would become evident as the height of the page would increase by 12px and a vertical scrollbar would appear. I also encountered the issue when I moved, via script, the calendar popup div for a datetime editor at the end of the body element to solve a positioning issue. Both were happening in "quirks mode" because I am forced to use a HTML 4.01 Transitional doctype.

To me it seems that the browser considers that script tags have no layout, so there is no problem to put them all one above the other in that extra 12px bit, but it does consider it needs to reserve that 12px space. Well, does it have layout or doesn't it?

I looked on the web for people with similar problems and I have encountered very few that actually tackled it. Here is one example of a solution from the Perishable Press blog: Prevent JavaScript Elements from Breaking Page Layout when Following Yahoo Performance Tip #6: Place Scripts at the Bottom.

For short, the solution in the above link is to place all the scripts at the end of the page, but inside a hidden div element. If you have access to all the layout, that is a great solution. However, I found that I could not use it, since the scripts were not added by me and I had no control over their placements. So I found an alternative solution, after noticing that the extra size would dissappear if the popup div of a control was shown.

Well, my solution is quite obvious: if there are issues with hidden and script elements placed at the end of the page, then why not try to add an element at the end of the page and thus make hidden elements NOT be at the end? :)

A short jQuery script did it for me:
$('script').each(function() { 
if ($(this).height()>0 && !$('form').children(':last').is('div.scrollFix'))
$(this).parent().append('<div style=\'position:absolute;background:transparent;width:0px;height:0px;line-height:0px;font-size:1px;\' class=\'scrollFix\' />');
});
or, in normal Javascript:
var scripts=document.getElementsByTagName('script');
for (var i=0; i<scripts.length; i++) {
var script=scripts[i];
var parent=script.parentNode;
var lastChild;
if (parent&&parent.childNodes.length>0)
lastChild=parent.childNodes[parent.childNodes.length-1];
var isFixed=(lastChild&&lastChild.tagName&&lastChild.tagName.toLowerCase()=='div'&&lastChild.className=='scrollFix');
if (script.offsetHeight>0&&!isFixed) {
var div=document.createElement('<div style=\'position:absolute;background:transparent;width:0px;height:0px;line-height:0px;font-size:1px;\' class=\'scrollFix\' />');
parent.appendChild(div);
}
}


The script is improved by actually scanning the last element of the parent element for the hidden div so that it doesn't add a zillion divs, one for each script tag. However, it doesn't cover the situation where other elements, rather than the script elements, cause the problem. However, the principle remains sound.

A very informative article, one that examines the differences of CSS interpretation between versions of Internet Explorer (and ignores any other browser), appeared yesterday in Smashing Magazine. Since I found it very informative, I am blogging the link to it: CSS Differences in Internet Explorer 6, 7 and 8.

I was creating this XAML to hold the design of all the controls in a library as a theme (generic.xaml). After a while it just got too big and so I had to use merged dictionaries to split the file into smaller parts.

First problem is that you can't just use the name of the file as the source of a ResourceDictionary, you need to specify the assembly name kind of like this:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Library.Namespace;component/Themes/OneOfMyControls.xaml" />
Notice the keyword component, which is NOT part of the folder or namespace structure.

The second problem is when you want to use merged dictionaries and then reuse a style key, for example, that you would expect to just place directly in generic.xaml or in the first merged dictionary. You will soon get a "Resource not found" error. Googling, one notices a lot of people having the same problem, but only in the generic.xaml/themes scenario. The solution is to add the common style file as a merged dictionary in each of the dictionaries merged in generic.xaml. That means that if you have 5 controls that use the same style and you have a xaml file for each control and one for the style, you need to add a MergedDictionaries entry in each of the 5 control files and merge the style xaml there.

I could have sworn I wrote a collation article a while ago. Anyway, here are some links:
  • an article about getting and setting the collation for Transact SQL databases and tables:TSQL to change collation of database
  • A list of available collations
  • if you get a collation conflict error, you need to collate every join or where like in this example:select * from profile, userinfo
    where profile.custid collate database_default = userinfo.custid collate database_default

Attached properties allow you to add new properties and functionality without changing one bit of the code of the affected classes. Attached properties are quite similar to Dependency properties, but they don't need an actual property in the affected object. You have probably worked with one when setting the Grid.Column property of controls inside a WPF Grid.

How does one implement it? Well, any class can have the static declaration of an Attached property for any other class. There are decorative attributes that indicate to which specific classes the property should appear in the Visual Studio property window. The caveat here is that if the namespace of the class has not been loaded by VS, the property will not appear, so it is better to place the class containining the property in the same namespace as the classes that the property is attached to.

Well, enough with the theory. Here is an example:

public static readonly DependencyProperty SizeModeProperty
= DependencyProperty.RegisterAttached(
"SizeMode",
typeof (ControlSize), typeof (MyEditor),
new FrameworkPropertyMetadata(
ControlSize.Custom,
FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior,
sizeModeChanged)
);

[AttachedPropertyBrowsableForType(typeof (TextBox))]
public static ControlSize GetSizeMode(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (ControlSize) element.GetValue(SizeModeProperty);
}

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public static void SetSizeMode(DependencyObject element, ControlSize value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(SizeModeProperty, value);
}

In this piece of code I have just defined a SizeMode property for a class called MyEditor, the default value being ControlSize.Custom. To use it, I would write in the XAML something like MyEditor.SizeMode="Large" and it would attach to any DependencyObject. The FrameworkPropertyMetadataOptions flags are important, I will review them later on. This also declares a sizeModeChanged method that will be executed when the SizeMode changes.

The GetSizeMode and SetSizeMode methods are needed for the attached property to work. You might also notice this line: [AttachedPropertyBrowsableForType(typeof (TextBox))], decorating the getter, which tells Visual Studio to display SizeMode in the properties window of TextBox objects. Another possible attribute is [AttachedPropertyBrowsableForChildren(IncludeDescendants = true)] which tells Visual Studio to display the property for all the children of the control as well.

Now, how can this be useful? There are more ways it can.
One of them is to bind stuff to the property in Triggers or Templates like this: Binding="{Binding Path=(Controls:MyEditor.SizeMode), RelativeSource={RelativeSource Self}}". This is interesting because one can use in the visual UI properties that are not part of the actual code or ViewModel.
Another solution is to use the change method, but be careful that the method must consider all possible uses for the property and also it will not work for when you explicitly set the default value (as it doesn't actually change)! Let me detail with a piece of code:

private static void sizeModeChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
FrameworkElement elem = d as FrameworkElement;
if (elem == null)
{
throw new ArgumentException(
"Size mode only works on FrameworkElement objects");
}
switch ((ControlSize) e.NewValue)
{
case ControlSize.Small:
elem.Width = 110;
break;
case ControlSize.Medium:
elem.Width = 200;
break;
case ControlSize.Large:
elem.Width = 290;
break;
case ControlSize.Custom:
break;
default:
throw new ArgumentOutOfRangeException("e",
" ControlSize not supported");
}
}


Here I am setting the Width of a control (provided it is a FrameworkElement) based on the change in SizeMode.

Ok, that is almost it. I wanted to shaed some extra light to the FrameworkPropertyMetadataOptions flags. One that is very important is Inherits. If set, the property will apply to all the children of the control that has the property defined. In the example above I first set FrameworkPropertyMetadataOptions.Inherits as a flag and I got an error, because it would try to set the Width to children controls that were not FrameworkElements like Border.

Another interesting page that is closely related to this is I’ve created an Attached Property, now how do I use it? where an Attached property is used in a Behavior, which is actually implemented by the Blend team and, as such it is still in the Expression assembly. Here are two other pages about this:
Using a Behavior to magnify your WPF applications
The Attached Behavior pattern.

and has 0 comments
When you want to enumerate through the items in a Resource class, you find that its ResourceManager class doesn't have a method for it, only GetString or GetObject for when you know the key. The solution to get all of the items in a Resource class comes with the GetResourceSet method of the ResourceManager, which returns an IEnumerable class, but not a collection. The enumerator can be of different types, but by default it is a HashTable, therefore the items the enumerator returns are of the type of DictionaryEntry.

So the code is as follows:
var resourceSet = ResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, false, true);
foreach (DictionaryEntry resource in resourceSet)
{
DoSomethingWith(resource.Key, resource.Value);
}

I had this situation where in Internet Explorer, in quirks mode, I would open a dropdown calendar (so showing an absolutely positioned element that was until then hidden) and the scrollHeight of the entire page would increase by a magical 19px.

This was caused by a fix for another problem, where the displayed calendar would not position itself under the text input element where it should have positioned, so I made it so that the displayed calendar would be the last child of the body element. This way it would always show in the correct position, but displaying this situation when elements were trying to fit in the height of the page.

I could not find the cause other than a problem in the Internet Explorer render engine, but I did find a fix. Instead of placing it at the end of the body element, place it at the beginning. With jQuery that simply translates into:
if (!elem.parent().is('body')) $('body').prepend(elem);
Notice my use of prepend instead of append.

I was using these GIF images stored as embedded resources and suddenly I got an Out of memory exception from a component that I had no control over. All images were icon size, 16x16 or a little more, so a lot of the explanations for the error based on "you don't have enough memory!" (duh!) were not helpful. The images did have transparent pixels, and my gut feeling is that it all came from there.

I still don't know what caused it, but I did find a solution. Where I get the image I add an additional
image = image.GetThumbnailImage(image.Width, image.Height, null, IntPtr.Zero);
I know it's not something very intuitive, but it solved the problem.

The only significant difference between the image before and after the thumbnailization is the PixelFormat property that changed from PixelFormat.Format8bppIndexed to PixelFormat.Format32bppArgb.

The stack looks like this:
   at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs, DrawImageAbort callback, IntPtr callbackData)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr)


And, using Reflector, I could go as far as pinpointing the error to the method System.Drawing.SafeNativeMethods.Gdip.GdipDrawImageRectRectI which wraps the gdiplus.dll GdipDrawImageRectRectI function. It returns error status 3, which is Out of memory, and that is that. I couldn't find a C++ code for the GdiPlus library and even if I had, who I am kidding? :)

It started with a simple request for a custom control to perform some validation. Seems easy enough, but it is not. Sure, there is an easy solution and that is to create a composite control, containing the original control and a normal validator, but that means you don't inherit from either control and you have to copy all the properties and methods you are interested in. If, as I did, you do not like this solution, you will soon find out that there are a lots of obstacles to be conquered if you want all the features of a validator, the first of which being that a control cannot easily change the Controls collection of its parent. It would be bad design. Therefore simply adding a Validator from inside the control does not work.

Let's start with what others did: Self Validating ASP.NET Text Box. This CodeProject article shows how you can build a control that is validated only on the server side and implements the IValidator interface. However, you will notice that it did not implement the ValidationGroup behaviour. And that is due to a simple fact: there is a method of the Page class called GetValidators(string validationGroup) that is used all around ASP.Net. It looks kind of like this:

public ValidatorCollection GetValidators(string validationGroup)
{
if (validationGroup == null)
{
validationGroup = string.Empty;
}
ValidatorCollection validators = new ValidatorCollection();
if (this._validators != null)
{
for (int i = 0; i < this.Validators.Count; i++)
{
BaseValidator validator = this.Validators[i] as BaseValidator;
if (validator != null)
{
if (string.Compare(validator.ValidationGroup,
validationGroup, StringComparison.Ordinal) == 0)
{
validators.Add(validator);
}
}
else if (validationGroup.Length == 0)
{
validators.Add(this.Validators[i]);
}
}
}
return validators;
}
Notice anything? There is no mention of IValidator, instead only BaseValidators are sought and the reason the IValidator approach works at all is the line before last where a validator is added to the list if the validationGroup parameter is empty. That is, it will work with IValidators but only on Buttons or other postback controls that have an empty ValidationGroup.

So let's start from the idea of the original article: an IValidator TextBox control with server validation only. For simplicity I will compare the value of the control with a constant string and fail the validation if the comparison fails.

Click to expand


You notice that the entire logic of this method is that the validators in the Page.Validators collection will be validated when need arises. In order to implement the ValidationGroup behaviour, we need to either fool the GetValidators method or to actually add a BaseValidator to the collection, not the IValidator control. I would have preferred the first method, but GetValidators is executed not only in Page.Validate but, being public, can also be executed in other situations (and in fact it is called by every control that wants to cause a postback).

My first attempt was to simply add a dummy validator to the collection, with the proper ValidationGroup set. It worked for the client side (we'll get to that) but then it failed miserably when Page.Validate tried to loop through the collection. I was forced to create my own validator control that inherits from BaseValidator. Do not worry, though, it is very lightweight and does not need to be added to the Controls collection. Here is the source:
Click to expand

public class DummyValidator:BaseValidator
{
private readonly IValidator _realValidator;

public DummyValidator(IValidator realValidator)
{
_realValidator = realValidator;
}

protected override bool EvaluateIsValid()
{
_realValidator.Validate();
return _realValidator.IsValid;
}

protected override bool ControlPropertiesValid()
{
return true;
}
}


Note: the following code has a property called ValidationGroup. The TextBox already has it, for its own AutoPostBack behaviour. I left it there, though, because you might want to use this on a control that doesn't have it natively.

Now the code for the ValidatedTextBox class looks like this:
Click to expand

private DummyValidator _dummyValidator;

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Page != null)
{
_dummyValidator = new DummyValidator(this){ValidationGroup = ValidationGroup};
Page.Validators.Add(_dummyValidator);
//Page.Validators.Add(this);
}
}

protected override void OnUnload(EventArgs e)
{
if (Page != null)
{
//Page.Validators.Remove(this);
Page.Validators.Remove(_dummyValidator);
}
base.OnUnload(e);
}

private string _validationGroup;

public string ValidationGroup
{
get
{
if (_validationGroup == null)
{
if (ViewState["ValidationGroup"] == null)
ValidationGroup = "";
else
ValidationGroup = (string) ViewState["ValidationGroup"];
}
return _validationGroup;
}
set
{
_validationGroup = value;
ViewState["ValidationGroup"] = value;
}
}


So the ValidationGroup is now working on the server side since there is an actual BaseValidator in the Validators collection calling the Validate method of our control. Since the DummyValidator class doesn't implement any specific behaviour, it can be reused for any type of validated control.

Now for the client side part. The client validation scripts work with a javascript array called Page_Validators. The validators are rendered as span elements (where the error message is displayed) and the array holds all these elements, with some extra properties like isValid, errorMessage, evaluationfunction, controltovalidate, validationGroup, focusOnError, enabled and display. The first three are like the IValidator members, only in javascript, controltovalidate is the client id of the control to be validated while focusOnError is used to scroll the page/container in order to see the invalid control without looking all over the page to find it.

All the ASP.Net validation functions are in a javascript file called WebUIValidation.js and embedded in the System.Web.dll library. We need to load it in order for validation to work. Then we need to render a span element and set its attributes. Lastly, but most important of all, we must create a function that will evaluate the validity of the control.

I will just post the entire source, since all the client code is practically copied from the BaseValidator code.

Click to expand


There are several things you need to take care of.
One of them is the client display of the validators. Normally, a validator's span element is rendered with the ErrorMessage as inner html. The ASP.Net framework then changes the visibility of the span depending on the validity of the control. I have chosen to not render the error message, as I wanted a different behaviour (in this case, a red background). The span element is still shown and hidden, but being empty, there is no visible effect.
Another thing is when you would use validation summaries. The error message is being rendered as a property of the span. It WILL be used in the summary, even if it is not normally displayed.

This code will work with almost no change for any control, so you could encapsulate it into a ValidatorHelper class or something. The only variants are the Validate method and evaluatefunction function.

Also note that having inherited from BaseValidator, I bypassed the normal functionality of the default validator controls. If you want to inherit from one of those, like RegularExpressionValidator, you might encounter problems, especially for controls that are not normally validated and for which the normal validator controls try to get their value. Take a look at the ValidationProperty attribute that you might need to use to decorate your control in order to work with default validators. Also, the javascript behaviour is to look for a control that has a value attribute. If not found it searches deeper into the children. So if you want to use a default validator, you might want to add script to keep a value attribute updated on the validated control HTML element.

And that was all.

It is weird that this doesn't happen with all types of Visual Studio projects, but only with Web apps. You have all those annoying .MySCMServerInfo files that pop-up in your check-in window and then cause errors because SCM knows they should not be checked in.

Enter StackOverflow with a really good solution: Hidding source control files within Visual Studio’s solution tree. No need for me to copy paste, just remember you need to restart Visual Studio for this to work.