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.

I believe this is something that any decent WPF programmer will laugh about, but there it is: I had this control derived from ContentControl and, of course, somewhere in the template I had a ContentPresenter. It all worked very well until I added a resizable option. I had two of these controls on the page, the first would contain a Grid, the other an ItemsControl. When I resized vertically the control, the ItemsControl would remain unchanged whether I made the height bigger or smaller. The Grid, though, would remain the same if enlarging the container and then squash when the size of the container got smaller than its auto size.

I have to say that I think my solution is really silly, but since it works: I've put a ScrollViewer control around the ContentPresenter in the my control template and then set its VerticalScrollBarVisibility to Hidden. This more or less is the same thing as setting overflow:hidden on the web.

and has 0 comments
Nothing interesting to say myself, so I am linking to random blog posts :) Here is one that describes 31 types of refactoring, with examples and everything:

31 Days of Refactoring.

The problem: you create an abstract class that inherits from something that can be designed in Visual Studio, like Form. Then you inherit another class from this abstract one. And when you get into the Visual Studio designer you see a nice colorful error message: The designer must create an instance of type 'bla bla bla' but it cannot because the type is declared as abstract.

The solution is detailed in a post of Brian Pepin: use the TypeDescriptionProviderAttribute decoration on the abstract class in order to tell .Net (thus to Visual Studio) what concrete type to declare and instantiate should the need arise.

Update: Brian's article is no longer available. I will update the link as soon as possible. Meanwhile, try this article from Microsoft.

Update: I have found the original article somewhere else and relinked it. Also, check out the fourth comment on this entry, where TrevDev links to a Microsoft Connect bug on the TypeDescriptorAttribute which suggests the attribute is not used correctly. That probably explains why people on VS2008 have problems, while the solution works on VS2005.

Now, all you have to do is read the post in question, with one reserve. The blog entry (and some other pages I have found on the net) say that this only works for Whidbey (VS2005), but I am using VS2008 and it worked just as well. However, for a second opinion try this CodeProject article that uses a little conditional compiling trick to switch from abstract classes with abstract methods and properties to normal classes with not implemented classes and methods based on debug/release modes. I kind of dislike the approach, mostly because it needs more effort to implement it, but it could help people that have this problem and maybe use some other IDE other than VS2005 or VS2008.

The Infragistics web controls have a way of saving design time settings into XML files and then loading them. You can do this either by loading the presets in the designer or dynamically from code, using the LoadPreset method. It accepts Stream, TextReader and string parameters and it is pretty easy to use.

The problem is that it doesn't work in inherited controls! The explanation is that a piece of its code is searching for the root element of the XML file by getting the assembly defined TagPrefix and then adding to it colon and the name of the object.

In other words, I had a control that inherited from UltraWebGrid, and in the ASPX it looked like omega:OmegaGrid, when styling it with the designer and then saving the preset, it created an XML that has its root element . Since my assembly had no assembly TagPrefix defined, it was looking for ":OmegaGrid" and failing.

The solution was to add the TagPrefix assembly attribute: [assembly: TagPrefix("Super.Desktop.GUIControls.Web", "omega")] in the AssemblyInfo.cs file.

I made a few controls that loaded and included a resource js file. And it all worked well, until I wanted to load the js file from the Page object. The generated url was invalid. After hours of nervewrecking attempts I realised that the problem was I was using control.GetType() to get the type required as a parameter in GetWebResourceUrl. And the page, even if inheriting from a custom page object that resided in the assembly where the embedded resources were, was of the site assembly.

Solution: use GetWebResourceUrl(typeof(knownClassInTheAssembly),resourceName);

Warning: my object was inherited from Page and placed in the necessary assembly. And it still didn't work. It is good to remember that ASP.Net pages are not of the type they inherit from, but a class with the name of the page and that resides in the dynamically generated assembly of the site! So be careful where you use this.GetType()

So you have some embedded resources in your ASP.Net control library and you want to use them. But instead, nothing works. Scripts are not loaded and images are not displayed.

Look in the IIS log files and check for an error like this: "Exception information: Exception type: ArgumentOutOfRangeException Exception message: Specified argument was out of the range of valid values. Parameter name: utcDate".

If you see it, then your assembly where the resources are embedded has the build date into the future! This also applies to the code you just built and the date is correct and the date of the server where you want to copy it to is in the past. It also applies when the time is in the past, as when you are copying it on a server in a different timezone!

Update: There are other reasons why axd files are not loaded. One of them is that some other IHttpHandler (defined in web.config) is messing up with your settings.

Another is that the .axd extension is not defined in the virtual directory mappings (You get the dreaded Webform_PostBackOptions is undefined javascript error). Go to IIS manager to the properties of the virtual directory, click on the Configuration button, select the Mappings tab. You have to have the axd extension defined to open with aspnet_isapi.dll. Warning: there is a checkbox in the properties for the extension mapping called Check that file exists. Make sure it is unchecked, as the WebResource.axd and ScriptResource.axd are not actual files, so the mapping will fail if the check is set! On Windows 2003 there is also a listbox at the bottom of the Mappings tab. Edit it and look for yet another Check that file exists checkbox and, of course, uncheck it.

As you have probably noticed, a lot of my recent posts have been about WPF. Having to do a demo in this new (for me) technology I had a lot of thing to learn and a lot of brick walls to hit. It was exciting, but also difficult, with new concepts that felt awkward, mind twisting. I even burst one day shouting "I hate WPF".

However, I am now working, temporarily, with ASP.Net (no Silverlight) again. And guess what? At every step where I need to design something, I think in the WPF way and find the web way lacking. Riddle me this, riddle me that. :)

Of course, some might say that this is another proof of my whiny personality. I hate when people say that about me!

I only met this while working on a Menu control, but who knows, maybe it occurs in other situations as well. Bottom line I wanted to create a CSS friendly Menu without using an adapter. So I inherited from Menu, did some stuff, then Kaboom! "A PopEndTag was called without A corresponding PushEndTag" error.

I could not determine where it cam from. The only helpful article on the net seemed to be one from a guy that also wanted to inherit from Menu. Strangely enough his problem only appeared in Design mode, while mine was a runtime thing. And weirder still, the problem was "solved" by the same ridiculous fix, that of calling an extra
base.RenderBeginTag(writer);
in my RenderBeginTag method override. However, his explanation that is all came from IControlDesignerAccessor did not solve anything for me. Menu only overrides the SetDesignModeState and GetDesignModeState methods from IControlDesignerAccessor and when I also overrode them and removed any code inside, I still got the error.

So, after an hour of searching, I solved it by overriding the Render method with
protected override void Render(HtmlTextWriter writer)
{
if (this.Page != null)
{
this.Page.VerifyRenderingInServerForm(this);
}
if (this.Items.Count > 0)
{
this.RenderBeginTag(writer);
this.RenderContents(writer);
this.RenderEndTag(writer);
}
}
which is the exact implementation from the original Menu source code, but without the 'false' parameter in RenderContents and RenderEndTag.

Hope it helps someone.

and has 1 comment

Foundations of Programming is a free ebook written by Karl Seguin, a member of the CodeBettter community. As you might have guessed by now from the fact the book is free, he is Canadian. :)

There is even a Foundation of Programming site, where there are a lot of free resources on programming as well as other free ebooks.

About the book, it is a good read. A bit inconsistent, it seemed, since it starts with chapters on Domain Driven Design, Persistence, Dependency Injection, Unit Testing, then moves to Object Relational Mappers and then has three "Back to Basics" chapters about Memory, Exceptions and Proxies. There is a logic to this, but the jump from expert to junior programming and then back again was a little annoying.

Interestingly enough, Karl Seguin is a former Microsoft MVP that advocates ALT.Net.

Bottom line, it is a good and easy read for all levels of programming. People might be attracted to the way Karl is expressing his opinion without actually being biased towards any of the usual debate parties. Beginners might learn about the foundations of the stuff they take for granted, like heap/stack, while more advanced developers can start thinking about structured ways of doing work, like DDD and automated unit testing. Neither chapter is a complete new revelation, but taken together, they do present a clear picture of programming from Karl Seguin's perspective and can surprise you on matters you thought you had complete control over.

I don't want to write a long blog entry, just to attract attention to this blog entry from Josh on WPF which is very concise, to the point and also directing to more complex articles that add more detail.

Even so, I want to cite a part which I think is essential to understanding the concept of Dependency Properties: Remember, a DP never really “has” a value…its value depends on various external factors. That’s why they are called dependency properties.

The problem is moot. The StackPanel doesn't work like that. You need to use a DockPanel to make inner children of the Panel stretch vertically and make the Panel fill all available space. The elements inside should have DockPanel.Dock="Top" to fill only the space they require , then no Dock for the element(s) you want to stretch, then DockPanel.Dock="Bottom" for the rest of the elements. That's how you get that "Outlook feel", too.

I was trying to use the Infragistics WPF controls and got stuck in the XamComboEditor. I was setting its ItemsSource to a list of ComboBoxDataItem objects and I wanted to have none of them selected by default. I had tried SelectedIndex -1, SelectedItem {x:Null}, Value {x:Null} to no avail. By some ridiculous functionality, the XamComboEditor would select some item in the middle of the list.

Then, in a flash of luck, I got it right. Value="". That was it! Even if IsEditable was false and the documentation mentioned Value could not be changed if IsEditable is false. Of course, they probably meant the user cannot change the Value not me, the developer, but still. Also, setting the Value to null did not work. Once in a lifetime I am not lazy and use {x:Null} instead of a simple empty string and it backfires. Sheesh!

Yay! The patch list for the Ajax Control Toolkit shows my two patches (for the dynamical adding of TabPanels to a TabContainer and the one for the zIndex of the PopupExtender) were 'applied in change set 54957'!

I don't know when the next official release of the ACT will be available, but you can always get the latest 'unstable' version (with the patches) here.