and has 2 comments
I won't get into explaining in detail what the dynamic keyword does in .Net 4.0, enough to say that it is enabled by the DLR (Dynamic Language Runtime) and it allows an object to have a type determined at runtime, not at compile time. I will use this feature to select the appropriate method for a specific type.

I've long had this problem with the object oriented principles that stated that methods with different signatures should be chosen based on the type of their parameters, but if the type of the parameter was unknown at compile time (let's say it was boxed in an object type) the method executed was always the one with the object parameter:

void DoSomething(object o) {
Console.WriteLine("I'm an object");
}

void DoSomething(int o) {
Console.WriteLine("I'm an int");
}

void Test() {
int i=1;
object o=i;
DoSomething(i);
DoSomething(o);
}

The result of this would be "I'm an int" followed by "I'm an object".

Solutions for this range from having a type casting cascade (because the switch statement doesn't work with Type) or using a Dictionary<Type,Action> or even using reflection to get the method with a specific signature and execute it.

A typical OOP solution that is correct, but really cumbersome to use is the double dispatch pattern. You can read an interesting article about it here.

The worst thing about this is that o.GetType() is System.Int32. It's like it's mocking us (and not in a unit testing way either).

Here comes dynamic:

void DoSomething(object o) {
Console.WriteLine("I'm an object");
}

void DoSomething(int o) {
Console.WriteLine("I'm an int");
}

void Test() {
int i=1;
object o=i;
dynamic d=o;
DoSomething(i);
DoSomething(o);
DoSomething(d);
}

This will have the same result as before followed by "I'm an int"! Pay attention to the fact that I did not set the value of d to the int, but to the object! What is ever cooler is that one can use only the methods that make sense, without the need of a general method that received a parameter of type object (unless, of course, you want to catch it and throw some meaningful error). No more casting insanity!

I use this technique to get an object that inherits from a base class, without knowing what the object is, then passing it to private methods that have the same name but different parameter types. All I have to do is cast my object to dynamic and pass it to the private method and the DLR does the rest for me.

I have not yet tested the performance aspect of this, but, considering that the DLR is the base for all dynamic languages in .Net like Ruby and Python, I bet it is faster than dictionaries with Actions in them.

So, to recap, if you ever want that a boxed object behave differently based on its true type, use myMethod((dynamic)obj) rather than myMethod(obj) and you are set.

Update: I have implemented this pattern in an application I am working on and I am very satisfied with it. I've created a separate assembly that adds the DynamicPatternAttribute and DynamicPatternIgnoreAttribute classes, which help decorate the methods I am using and also a PatternChecker class that can be used to check that there is a method implementation for each type inheriting from a specific base type. Here are some details on how it works.

First of all, we must define the purpose of such a pattern. As I said above, one can use it to specify behavior based on specific types that inherit from a base type. This can be desirable when the types in question cannot be changed to add new behavior. Even if they can be changed, it may not be desired to add a reference from the project containing our classes to the project containing the behavior. It is almost like defining static extension methods.

Then there are the elements:
  • The base class from which all classes that determine behavior inherit (object if nothing specific)
  • The routing method that receives at least a base class parameter
  • The behavior methods that have as a parameter the subclasses of the base type
  • The pattern implementation checker class


So far I've used it in the following way:
  • The new behavior is encapsulated in methods in a static class
  • The routing method receives as the first parameter the base type for the classes that should determine behavior
  • The only code in the routing method is calling the private behavior method(s) using the same parameters as itself, except the first which is cast to dynamic
  • The behavior methods usually are private methods having the same name as the routing methods, but ending in "handle"
  • The routing method is decorated with [DynamicPattern("nameOfTheBehaviorMethods")]
  • The routing method is decorated with [DynamicPatternIgnore(typeof(subClassToIgnore))] which tells the checker which classes do not need behavior implementations
  • The static class containing the pattern has a static constructor that calls a method to check the implementation of the pattern
  • The checker method is decorated with [Conditional("DEBUG")] so that it doesn't hinder the functionality of the program with slow reflection checks
  • The checker method calls PatternChecker.CheckImplementation(typeof(staticClass)) or PatternChecker.CheckImplementation(typeof(class).Assembly)


The PatternChecker class only checks if there is a method with the name specified in the DynamicPattern contructor for each of the subclasses of the base type of the first parameter in the routing method.

I hope you like this pattern. I certainly do. I leave you with an actual implementation example:

public static class RequestHandler
{

static RequestHandler()
{
checkDynamicPattern();
}

[Conditional("DEBUG")]
private static void checkDynamicPattern()
{
PatternChecker.CheckImplementation(typeof(RequestHandler));
}

[DynamicPattern("getObjectsHandle")]
[DynamicPatternIgnore(typeof(BaseDeleteRequest))]
[DynamicPatternIgnore(typeof(DeleteUsersRequest))]
[DynamicPatternIgnore(typeof(DeleteCategoriesRequest))]
[DynamicPatternIgnore(typeof(DeleteDataRequest))]
[DynamicPatternIgnore(typeof(DeleteApplicationsRequest))]
[DynamicPatternIgnore(typeof(GetEntityRequest))]
[DynamicPatternIgnore(typeof(BaseObjectActionRequest))]
[DynamicPatternIgnore(typeof(GetEntitiesRequest))]
[DynamicPatternIgnore(typeof(GetEntityByIdRequest))]
[DynamicPatternIgnore(typeof(BatchOperationRequest))]
public static BaseEntitiesResponse GetObjects(BaseRequest request, Coordinator coordinator)
{
return getObjectsHandle((dynamic)request, coordinator);
}

private static BaseEntitiesResponse getObjectsHandle(BaseRequest request, Coordinator coordinator)
{
throw new ArgumentException("Cannot find a suitable getObjects method for type of request " +
request.GetType());
}

private static BaseEntitiesResponse getObjectsHandle(GetApplicationRequest request,
Coordinator coordinator)
{
DataObject entity = coordinator.ApplicationManager.GetObject(request.Id,
request.IncludeOptions);
return getEntitiesResponse(entity);
}



Update: There is an wonderful unintended side-effect of the dynamic pattern when casting to generic types. Imagine you have a generic interface like ICustom<T> and you want to use the standard model of checking the type and selecting behaviour. You can't do it with as! There is no valid method of doing
var custom=obj as ICustom<T>;
so you are forced to use GetType() and then some weird methods that interogate the Type object. You can do it with the dynamic pattern.



checkIfCustom(obj);

private void checkIfCustom(object obj) {
dynamicCheckIfCustom((dynamic)obj);
}

private void dynamicCheckIfCustom(object obj) {
//do nothing
}

private void dynamicCheckIfCustom<T>(ICustom<T> iCustom) {
doSomethingWith(iCustom);
}


This thing works! If anything than an ICustom<T> is given, nothing happends. If it is the correct type, then doSomething is executed with it. Pretty neat, huh?

This will be a short post to describe my own stupidity. I was testing the new Entity Framework Plain Old CLR Objects (POCO) support and so I made a small test to:
  • Clear the database
  • Insert new items in the database
  • Select the items from the database, with and without related items

Every time I got the entire object tree, with child collection and parent objects, thus making me think that in this implementation of EF, the need to use Include was gone, instead an Exclude method was needed in order to tell the framework to NOT LOAD related objects! Insane!
After looking everywhere to find the answer, I finally turned to profiling SQL only to see that the database was not accessed with related items, but only what I had asked for. Then I had my "I'm an idiot!" moment. I was using the same context and EF knew the entire hierarchy of objects because (duh!) I had just inserted it a few code lines above. Using different contexts solved the "problem" and only returned the requested objects, making Include a necessity again.

Well, there are a lot of good reasons why that could happen because of your bad code, but this time it is a plain ugly Microsoft bug. You see, the code in the RaisePostBackEvent method in the TreeView control first checks if the control has an Adapter and if not, it just does its thing. If there is an Adapter, it tries to cast it to a IPostBackEventHandler and then fires the RaisePostBackEvent event there. However, if the TreeView control has an adapter and it is not a RaisePostBackEvent, nothing happends!

Here is the offending code:

protected virtual void RaisePostBackEvent(string eventArgument)
{
base.ValidateEvent(this.UniqueID, eventArgument);
if (base.IsEnabled)
{
if (base._adapter != null)
{
IPostBackEventHandler handler =
base._adapter as IPostBackEventHandler;
if (handler != null)
{
handler.RaisePostBackEvent(eventArgument);
}
}
else ...


Bottom line, you need to either not use an adapter for the TreeView, or use one that knows how to handle the postback. And given the complexity of the code in the method, it is better to just not use an adapter.

The solution I have adopted is to recreate the functionality in an override of the RaisePostBackEvent method and add some more (like TreeNodeClicked and SelectedNodeClicked). Hint: you need to also get in LoadPostData and remember which nodes are selected in order to check if the selected node has changed.

I am only linking to this blog post that shows how to instantiate the converters directly in the binding, without having to define a resource just for that.

WPF Quick Tip: Converters as MarkupExtensions

Update: After careful deliberation I've reached the conclusion that instead of custom converters that would have to be instantiated in the binding XAML I can just create new binding types. Here is how you can do it:
  1. Inherit from Binding
  2. Implement IValueConverter
  3. Set Converter=this in the constructor
  4. Use the new binding where you see fit


Actually, I have created a more complex Binding object that chooses the type of conversion based on an enumeration or, alternatively, gets converters as content and pipes them one after the other for a more dynamic reuse of converter power. I am still not sure which of these two solution I will use more often, though.

Here is a post from Phil Haack about extra extensibility options in ASP.NET 4.0. I would like to emphasize the third "gem", the one that lets you add an assembly programatically to the list of loaded assemblies (equivalent to adding it in the assemblies tag in web.config). I wanted this from .Net 1.0 ! Unfortunately it must be called during the Application_PreStartInit stage of the application, but maybe the first gem can help with that.

Of course, I haven't been using these things yet, so I may be saying stupid things. It is a distinct possibility... Quite distinctive... Oh, shut up!

I was minding my own business doing this ridiculous ASP.Net project and suddenly I am hit with: "Multiple controls with the same ID 'lbTitle' were found. FindControl requires that controls have unique IDs.". I was using this web control that contained two others, each of them having a lbTitle control.

If you think about it, it does make sense to throw this exception when the FindControl method is used in the parent control. Which control did I mean? But the error appears even if the FindControl is used inside one of the child controls, what is up with that?

As a secondary thought, I wasn't using any FindControl. It seems that what does is the AssociatedControlID property of the Label control. Therefore I will set the HtmlTextWriterAttribute.For attribute manually to resolve this. Pretty damn ugly, if you ask me!


Update: My fault! The controls needed to implement the INamingContainer interface. It's not that the ClientID was not different, but FindControl works by going to the NamingContainer control and finding then children by ID. Too bad that you can't just specify the ClientID and be done with it, but that's that.

I don't want you to think that I started working on ASP.Net MVC, but this article about a 36 year trek through backward compatibility hell was really funny and needed to be linked. What is so funny, I guess, is that it is factual and the humour is in the situation more than in the article itself.

On a separate note, ASP.Net 4.0 fixed this issue with a web.config setting.

A while ago I was writing about the annoying The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>). error and how to fix it by using a PlaceHolder or another container to hold your code blocks you can resolve this.

But what if the ASPX code is not yours and you are only building the control? How can you get around the dreaded code blocks? First, let's try to understand the mechanism that renders the code blocks. When the markup code is read, a CodeDomTreeGenerator class is used to parse it. All DOM tree generators inherit from BaseTemplateCodeDomTreeGenerator which does the following: if the block read is a control, create the control and add it to the control collection, if it is a code block, generate a dynamic render method and use that. From that moment on, you can't change the control collection because (stupid, if you ask me) the render method has already been generated and it only knows about the controls it had then.

You can test if the ControlCollection object cannot be changed via the IsReadOnly property. If it is read only, code blocks have been added. Indeed, in the ControlCollection class, a private field is used to hold an error message and, if not null, it will be used as the exception message when trying to add or remove controls from the collection.

Are you in the mood for some insanity? Ok, let's unset the string via reflection, see what happens! Well, first of all, no error! You can manipulate the control collection at your leisure. The problem is that the render method is still the generated one. If you change the control collection weird stuff will happen, like not getting your control rendered or, if inserted or deleted, seeing controls rendered instead of others or being pushed out of the "rendering queue". So, what is we remove the render method as well? Then the normal Render mechanism will be used. That means that the code blocks will be completely ignored!

So, if you are a mean son of a bitch like myself, instead of begging junior programmers to never use code blocks or to encapsulate them at least, screw the controls so that they ignore that bad code. Not very smart, but oh, so mean :)

Here is a bit of code to remove the "readonlyness" of control collections:



public static class MSOAB
{
private static readonly FieldInfo _readOnlyErrorMsgFieldInfo =
typeof(ControlCollection).GetField("_readOnlyErrorMsg",
BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly PropertyInfo _rareFieldsEnsuredPropertyInfo =
typeof(Control).GetProperty("RareFieldsEnsured",
BindingFlags.Instance | BindingFlags.NonPublic);

private static FieldInfo _renderMethodFieldInfo;

public static void FixReadOnlyControlCollection(Control control)
{
if (control.Controls.IsReadOnly)
{

_readOnlyErrorMsgFieldInfo.SetValue(control.Controls, null);
var rareFieldsEnsured = _rareFieldsEnsuredPropertyInfo.GetValue(control, new object[] { });
if (_renderMethodFieldInfo == null)
{
_renderMethodFieldInfo = rareFieldsEnsured.GetType().GetField("RenderMethod");
}
_renderMethodFieldInfo.SetValue(rareFieldsEnsured, null);
}
}
}


This isn't really tested except the basic functionality and I haven't used it in a production environment, but it was fun as it was. I hope you enjoyed it as well.

Coincidence made it that this week people have asked me twice about how to preserve focus during postbacks, especially during auto postbacks. I didn't really know much about how ASP.Net does this other than building your own script, so I started investigating.

When you post back, there is a postback event reference that is used. The Page.ClientScript property, of the type ClientScriptManager, has a bunch of methods called GetPostBackEventReference which return different script strings for different options. The options are encapsulated into a PostBackOptions object which has, interestingly enough, a property called TrackFocus. Wow! Exactly what I wanted.

The problem comes when digging in the System.Web sources and seeing that no one actually sets this property. I did a bunch of code to add the script with the TrackFocus property and it seems it works. Not only does it preserve the focus before the postback, but also the scroll bars position. I tested in Internet Explorer, FireFox and Chrome and it worked on all.

So what is going on? Why does this feature, which I imagine is quite useful, seem only half done? And that since the era of .Net 2.0? I have no idea. I will post this method, applicable on TextBox controls, although I guess it could be applied on most if not all AutoPostback controls, that replaces the script for a normal AutoPostback with one that also preserves focus:

private void fixAutoPostBack(TextBox tb)
{
if (!tb.AutoPostBack)
return;
tb.AutoPostBack = false;
PostBackOptions options
= new PostBackOptions(tb, string.Empty)
{
TrackFocus = true,
AutoPostBack = true
};
if (tb.CausesValidation)
{
options.PerformValidation = true;
options.ValidationGroup = tb.ValidationGroup;
}
string onchange = string.Empty;
if (tb.HasAttributes)
{
onchange = tb.Attributes["onchange"];
if (!string.IsNullOrEmpty(onchange))
{
onchange = onchange.TrimEnd(';') + ";";
}
}
onchange += ClientScript
.GetPostBackEventReference(options, true);
tb.Attributes["onchange"] = onchange;
}

As you can see, the only thing I do differently from the normal AutoPostback code is to set TrackFocus to true.

I was trying to add some content to Infragistics WPF controls and some of the images used were blurry. I have tried setting SnapToDevicePixels, but to no visible effect. I did stumble upon a property in the Infragistics.Windows.Utilities class, called SnapElementToDevicePixels. I didn't know what it does, but I tried it anyway. Voila! The image got crisp and clear.

This is the comment from the property in the Infragistics WPF sources:

/// <summary>
/// SnapElementToDevicePixels Attached Dependency Property
/// </summary>
/// <remarks>
/// <p class="body">The SnapsElementToDevicePixels is meant to be used on elements such as an Image that
/// does not currently support SnapsToDevicePixels.</p>
/// <p class="note"><b>Note:</b> The RenderTransform of the element is used so you should not set the RenderTransform
/// on the same element on which you are setting SnapElementToDevicePixels to true. You may set the RenderTransform on
/// an ancestor element. Also, you should not set this property on an element that is an ancestor of one or more
/// elements that have this property set to true. In such a case the results are undefined since the child element's
/// RenderTransform could be calculated before that of the ancestor element. Since this property should be set on
/// discrete elements such as an Image, this scenario should not be required.</p>/// </remarks>

In order to use it, make sure you load the Infragistics.Windows namespace in your XAML:

xmlns:Windows="clr-namespace:Infragistics.Windows;assembly=Infragistics3.Wpf.v9.2"

and then set the Windows:Utilities.SnapElementToDevicePixels property to True.

I had this control that functioned as a textbox. The request was that it behaved differently when used as an editor in a grid and was in the "add new record" line. I agree that the best solution would have been for the grid to set a property to the editor when placing it somewhere or at least when adding to the grid, but that is not relevant.

The solution was, of course, to add a DataTrigger that would check a property of the parent grid row object, by using RelativeSource and FindAncestor. However, that approach resulted in an ugly binding error in the Visual Studio debug view window when the textbox was being used stand alone. It didn't break execution, but I kind of disliked it.

The solution, at first, was to use a Converter. However, the converter class does not apply to the RelativeSource, but to the referenced property. The binding would first look for the parent row, find nothing, then return a null reference exception when trying to access the path property.

Another solution would be to look for the parent in the LayoutUpdated event (only the first time) then look for the trigger and enable or disable it. Yet another is to reference a property that the textbox would set depending on the parent found above. Both solutions would be cumbersome if you don't have ownership of either control.

It appears that there is no way to determine the way a relative source is found. I don't know if they changed that in the WPF4 implementation, but it would have been a nice touch. That being said, I believe one can create a custom Binding object to take care of this. I will update the post with some sources when I get to working with WPF again.

Update: I've reached the conclusion that the problem is the question, not the answer. In order to make an element have a certain behaviour when a child of another element, a style should be added to the resources of the parent. This way, the problem is solved. I agree that sometimes it is cumbersome to do so, but the alternative is that your control will always search for a parent that might not be there. So, the solution is to make the parent make the child do what you want.

There are all these attributes that can be used to decorate properties and classes so that the Property Grid control knows to handle them. One of these attributes is PersistenceModeAttribute, which specifies how to persist the information in ASP.Net markup. More often than not, you need to persist a complex object with subproperties as an inner tag. In that case one uses [PersistenceMode(PersistenceMode.InnerProperty)]. For the possible values of the constructor parameter, just follow the link if interested.

The problem comes when you want to persist the properties as attributes, in the ASP.Net specific "flattened" syntax, using a hyphen to separate property from subproperty. (<Style Color="red"/> as an inner tag is the same as Style-Color="red" as an attribute). You want this because some controls interpret their inner content as controls to be placed in them, such as the Panel control. You cannot add a Style tag in it because it just gets rendered in the page. The solution is to not use PersistenceMode! Of course, you might say, that's obvious. But it is not when your property already has the PersistenceModeAttribute decorating it and you are desperately looking for a parameter that does what you want. There is no such parameter. Not decorating the property is a separate option and it is the default behavior.

There are cases when pages need to use the same session, even if they are started from different contexts. One example is when trying to open a new window from within a WebBrowser control, or maybe issues with the ReportViewer control, or even some browsers who choose to open frames and new windows on different threads, like FireFox did for me a while ago. One might even imagine a situation where two different browsers open the same site and you want to use the same session. You have a SessionID, you are on the same server, so you should be able to use the session you want!

Here is how you do it:

var sessionID=(string)Request.QueryString["SessionIdentifier"];
if (Request.Cookies["ASP.NET_SessionId"] == null
&& sessionID != null)
{
Request.Cookies.Add(new HttpCookie("ASP.NET_SessionId", sessionID);
}

This piece of code must be added in the Global.asax.cs file (create a Global.asax file for your web site if you don't have one) in the void Global_PostMapRequestHandler(object sender, EventArgs e) handler and the sessionID must be given in the URL parameter SessionIdentifier.

Unfortunately you can't do it anywhere else. I've seen attempts to abandon the session in page load or page init and then do this, but it doesn't work. Basically, this post describes a horrible hack that replaces the default cookie where ASP.Net saves the SessionID value just before it is read.

As it can be a security risk, you should also add some validation logic so that the session hijacking is done only on certain pages that are likely to be opened in different application threads.

I had this scenario where a property was attached to objects but I wanted different default values for different objects. The code made it easy to just check if the property was set or not, then set the default myself. In order to do that, use the DependencyObject.ReadLocalValue instead of DependencyObject.GetValue and then check if the result equals DependencyProperty.UnsetValue. Like this:

return element.ReadLocalValue(MyProperty) == DependencyProperty.UnsetValue;
Of course, this can be used as an extension method for any element and/or property.

Short answer: you can't! The color of the text selection (not of the background) is given by an (internal) class System.Windows.Document.CaretElement, inheriting from Adorner. Here is the bit of crappy code that makes this impossible:

protected override void OnRender(DrawingContext drawingContext)
{
if (this._selectionGeometry != null)
{
Brush brush = new SolidColorBrush(SystemColors.HighlightColor);
brush.Opacity = 0.4;
brush.Freeze();
Pen pen = null;
drawingContext.DrawGeometry(brush, pen, this._selectionGeometry);
}
}

And you might be thinking that it is a simple template change issue and if you don't add the bloody caret to the template it will work. Wrong! The Caret element is instantiated via code in classes as TextSelection, as an implementation of the ITextSelection interface which only has a getter for the Caret property. The TextSelection class is instantiated in all the controls that support text selection as internal properties or fields. Yay!

So unless you recreate the entire selection functionality, you are stuck with the SystemColors.HighlightColor color for selection. As Dr. WPF himself says: "It is entirely impossible in the current .NET releases (3.0 & 3.5 beta). The control is hardcoded to use the system setting... it doesn't look at the control template at all."

Better luck in WPF 4.0... maybe.