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.

WPF is great for styling. They even included different default styles for each Windows operating system so that the controls look "native". So making an application look as if native to the operating system is not a problem. But how can one do the opposite: force the application to always display as if on a specific operating system?

The solution is to include the default theme for that OS in the resources of your application, window, user control, etc, so one can even style different parts for different operating systems, if need be.

Well, this is how you can make you application use the Vista/Windows7 Aero interface. In you App.xaml add an Application.Resources block and a ResourceDictionary with the source /PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml. If you have already a style in your application resources, add the resource dictionary in a ResourceDictionary.MergedDictionaries block. Like this:

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35,
ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml"
/>
<ResourceDictionary Source="/My.Namespace;component/Themes/MyApplication.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>


The operating system theme files that you can choose from are:
AssemblyTheme file
PresentationFramework.Aeroaero.normalcolor.xaml
PresentationFramework.Classicclassic.xaml
PresentationFramework.Lunaluna.homestead.xaml
PresentationFramework.Lunaluna.metallic.xaml
PresentationFramework.Lunaluna.normalcolor.xaml
PresentationFramework.Royaleroyale.normalcolor.xaml


Of course, the method of loading the theme might be through code, and so this can be used to programatically and dynamically change the theme:

protected override void OnStartup(StartupEventArgs e)
{
Uri themeUri = new Uri(myThemeUriString, UriKind.Relative);
ResourceDictionary theme = (ResourceDictionary)Application.LoadComponent(themeUri);
Resources.MergedDictionaries.Add(theme);
}
base.OnStartup(e);
}

I was working on a small ASP.Net control that inherited from Button, so nothing special. I went into Visual Studio in design mode and I noticed that the control did not display any resize handles so I could only move the control, not resize it using the mouse.

After intensive Googling, trying custom ControlDesigner classes with AllowResize set to true and all other kinds of strange things, I realised that in the Render method I would write a style tag while in DesignMode before rendering the button. The method was described in a previous blog entry to fix the problem with CSS files with WebResource entries inside and PerformSubstitution.

It appears that Visual Studio, by default, only resizes the controls that render an HTML element that has size. A style tag does not! The solution was to add a div around the control (and the style block) while in DesignMode. The only problem was that the div is a block element, while the input of type button is an inline element. That means that two div elements would place themselves one under the other, not next to the other like two buttons would. So I fixed the problem by also adding a float style attribute and setting it to left.

Here is a small code sample:

protected override void Render(HtmlTextWriter writer)
{
if (DesignMode)
{
writer.AddStyleAttribute("float", "left");
writer.RenderBeginTag("div");
// this renders an embedded CSS file as a style block
writer.Write(this.RenderDesignTimeCss("MyButton.css"));
}
base.Render(writer);
if (DesignMode)
{
writer.RenderEndTag();
}
}

I was trying to make a web control that would be completely styled by CSS rules. That was hard enough with the browsers all thinking differently about what I was saying, but then I had to also make it look decent in the Visual Studio 2008 designer.

You see, in order to use in the CSS rules (or in Javascript resources, for that matter) files that have been stored as embedded resources in the control assembly, a special construct that looks like <%=WebResource("complete.resource.name")%> is required.

The complete resource name is obtained by appending the path of the embedded resource inside the project to the namespace of the assembly. So if you have a namespace like MyNamespace.Controls and you have an image called image.gif in the Resources/Images folder in your project, the rule for a background image using it is background-image:url(<%=WebResource("MyNamespace.Controls.Resources.Images.Image.gif")%>);.

Also, in order to access the CSS file you need something like [assembly:
WebResource("MyNamespace.Controls.Resources.MyControl.css",
"text/css", PerformSubstitution = true)]
somewhere outside a class (I usually put them in AssemblyInfo.cs). Take notice of the PerformSubstitution = true part, that looks for WebResource constructs and interprets them.

Great! Only that PerformSubstitution is ignored in design mode in Visual Studio!!. The only solution to render the control correctly is to render the CSS file yourself and handle the WebResource tokens yourself. Here is a method to do just that:

private static readonly Regex sRegexWebResource =
new Regex(@"\<%\s*=\s*WebResource\(""(?<resourceName>.+?)""\)\s*%\>",
RegexOptions.ExplicitCapture | RegexOptions.Compiled);

public static string RenderDesignTimeCss2(Control control, string cssResource)
{
var type = control.GetType();
/*or a type in the assembly containing the CSS file*/


Assembly executingAssembly = type.Assembly;
var stream=executingAssembly.GetManifestResourceStream(cssResource);

string content;
using (stream)
{
StreamReader reader = new StreamReader(stream);
using (reader)
{
content = reader.ReadToEnd();
}
}
content = sRegexWebResource
.Replace(content,
new MatchEvaluator(m =>
{
return
control.GetWebResourceUrl(
m.Groups["resourceName"].Value);
}));
return string.Format("<style>{0}</style>", content);
}

All you have to do is then override the Render method of the control and add:

if (DesignMode) {
writer.Write(
RenderDesignTimeCss2(
this,"MyNamespace.Controls.Resources.MyControl.css"
);
}


Update:
It seems that rendering a style block before the control disables the resizing of the control in the Visual Studio designer. The problem and the solution are described here.

I have this ASP.Net web control that has a property that is persisted as an inner property and sets some custom style attributes. Then there is another control that inherits from the first one and overloads this custom style property with another having the same name and returning a different type. All this is done via the new operator

Now, while this is perfectly acceptable from the standpoint of Object Oriented Programming and it compiles without any issues, I get a compile error when I actually use the property and save it in the aspx code. That is a limitation of ASP.Net and I could find no way to circumventing other than changing the name of the property. This would also be the case if you have two public properties that have the same name only differently cased.

While this second situation I understand, the first is really stupid. I am specifying the type of the control so there should be no issues with an overloaded property. I guess it has something to do with the persistence mechanism, but still... Annoying.

I have been working on a class that has some properties of type Color?, a nullable Color. I noticed that, in Visual Studio 2008, when I go to edit the properties in question in the property grid I get a dropdown of possible colors whereas if I go to edit a color on a WebControl, something like BackColor, I get a nice dialog window with the title 'More Colors' with colored hexagons from which to choose a color. Researching on the net I found out that if you want to use the ColorEditor in the property grid control you should decorate the property with [Editor(typeof(ColorEditor), typeof(UITypeEditor))]. I did that and, indeed, the editor was changed. However, it was not the one for BackColor, with its hexagonal design.

Reflecting the WebControl class I noticed that it didn't use any Editor decoration, but rather [TypeConverter(typeof(WebColorConverter))], so I added that and removed the editor on my property. Now the only editing option for my property was a simple textbox. Using both TypeConverter with the Editor option didn't have any visible effect either, it just used the normal editor.

As a last test I changed the type of the property to Color and decorated it only with the TypeConverter attribute and there it was, the 'More colors' editor. My only conclusion is that the editor is chosen by the property grid itself on Color properties decorated with the WebColorConverter. It must be hardcoded and thus it will never work on other types. Just stick with the ColorEditor option for nullable values.

Needless to say, I spent quite a lot of time compiling, closing and opening the designer on a test page and so on, so I hope this helps other people with a similar problem.

Today I found out about a very cool attribute called DebuggerDisplayAttribute. What it does is tell the Visual Studio debugger how to display a certain class when making a break in the code. And it seems it is very powerful, using expressions in the string that is given as its parameter (ex: [DebuggerDisplay("x = {x} y = {y}")]). Check out the link on MSDN here.

The way the class is displayed can be further customized by using the DebuggerTypeProxyAttribute class, which actually uses a completely different class to be presented in the debugger windows. Read Using DebuggerTypeProxy Attribute for more details.

I spent several hours debugging an error that gave this exact error message: 'null' is null or not an object. Well, duh! The problem here is that the project was an ASP.Net project, with a large number of files that interacted in innovative and weird ways with the ASP.Net Ajax framework. So going line by line was a problem. Also, the Javascript debuggers stopped in a finally block that had nothing to do with the error.

As a side note, the only debugger that showed where the error originated was the Chrome debugger (and probably the FireFox one, but I didn't get to try it). The problem with Chrome is that it only gave me the file and line number in a "minimized" js file, so I had no clue on what was happening.

Ok, to cut it short, the error appeared in a line like $get('someId').value=... An element with the id someId did not exist, therefore the result of the function was null. Setting the value resulted in the error.

Conclusion: 'null' is null or not an object is an error that occurs when member access is requested on a function result without it being stored in a variable. Look for stuff of the form someFunction(params).member. It is a bad form anyway; store the someFunction result in a variable and then access its members: var x=someFunction(params); if (x) //doSomethingWith x.member

Whenever you build a more complex ASP.Net control you get to build templates. Stuff like collapsing panels, headered controls or custom repeaters are all usually working with templates, by having properties of the ITemplate type which then are instantiated into a simple control like a Placeholder or Panel. There are many tutorials on how to do this, so I won't linger on the subject.

What I find very difficult to achieve was to have a templated control that would just accept dropped controls and place them into a template, without having to enter in "template mode". First I will copy the entire code of a very simple control, then I will explain.

using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

namespace Web.Controls
{
[Designer(typeof (TestControlDesigner), typeof (IDesigner))]
[ParseChildren(true)]
[PersistChildren(false)]
public class TestControl : WebControl
{
#region Properties

[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[DefaultValue(typeof (ITemplate), "")]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate MainTemplate
{
get;
set;
}

#endregion

#region Private Methods

protected override void CreateChildControls()
{
base.CreateChildControls();
if (MainTemplate != null)
{
MainTemplate.InstantiateIn(this);
}
}

#endregion
}

public class TestControlDesigner : ControlDesigner
{
#region Member data

private TestControl mTestControl;

#endregion

#region Public Methods

public override void Initialize(IComponent component)
{
base.Initialize(component);
SetViewFlags(ViewFlags.TemplateEditing, true);
mTestControl = (TestControl) component;
}

public override string GetDesignTimeHtml()
{
mTestControl.Attributes[DesignerRegion.DesignerRegionAttributeName] = "0";
return base.GetDesignTimeHtml();
}

public override string GetDesignTimeHtml(DesignerRegionCollection regions)
{
var region = new EditableDesignerRegion(this, "MainTemplate");
region.Properties[typeof (Control)] = mTestControl;
region.EnsureSize = true;
regions.Add(region);
string html = GetDesignTimeHtml();
return html;
}


public override string GetEditableDesignerRegionContent(
EditableDesignerRegion region)
{
if (region.Name == "MainTemplate")
{
var service = (IDesignerHost) Component.Site.GetService(typeof (IDesignerHost));
if (service != null)
{
ITemplate template = mTestControl.MainTemplate;
if (template != null)
{
return ControlPersister.PersistTemplate(template, service);
}
}
}
return string.Empty;
}


public override void SetEditableDesignerRegionContent(
EditableDesignerRegion region,string content)
{
if (region.Name == "MainTemplate")
{
if (string.IsNullOrEmpty(content))
{
mTestControl.MainTemplate = null;
}
else
{
var service = (IDesignerHost)
Component.Site.GetService(typeof (IDesignerHost));
if (service != null)
{
ITemplate template = ControlParser.ParseTemplate(service, content);
if (template != null)
{
mTestControl.MainTemplate = template;
}
}
}
}
}

#endregion

#region Properties

public override TemplateGroupCollection TemplateGroups
{
get
{
var collection = new TemplateGroupCollection();

var group = new TemplateGroup("MainTemplate");
var template = new TemplateDefinition(this,
"MainTemplate", mTestControl, "MainTemplate", true);
group.AddTemplateDefinition(template);
collection.Add(group);
return collection;
}
}

#endregion
}
}


The above code is a pretty common way of making a templated control. We have a Control (TestControl) with one or more ITemplate properties (MainTemplate) and a ControlDesigner (TestControlDesigner) that decorates the TestControl class via the Designer attribute. The trick for the drag and drop to work with this scenario is in the last two methods.

First look at the GetDesignTimeHtml() override. There I did a little hack in order to set for the target control an attribute with the name DesignerRegion.DesignerRegionAttributeName and with the value of "0". This actually declares the entire control in the Visual Studio designer as the first (and only) "editable region". The region is registered in the GetDesignTimeHtml(DesignerRegionCollection regions) override and named MainTemplate.

Secondly, look at the TemplateGroups property override. This is in order for the "Edit Templates" action to appear in design mode. Since drag and drop would work very nicely, technically we don't need it. However, I noticed that if one tries to drag a control out of the templated one, it doesn't really work :). We still need Template Editing mode, but only in unlikely scenarios. Even if the template group is called "MainTemplate" it has no connection with the editing region.

Thirdly, look at the lots of attributes decorating the TestControl class and the MainTemplate property. An important one is [TemplateInstance(TemplateInstance.Single)], which says that there will be only one instance of the template, in other words, the controls can be treated as in a Panel and accessible from the code as protected members.

Finally, let's look at the methods that actually permit the drag and drop operation: GetEditableDesignerRegionContent, which has a region as a parameter, and SetEditableDesignerRegionContent, which also has a region, but also a string content parameter.

The trick lies in the conversion from this unwieldy string variable to a control tree and viceversa. The string is necessary because it is the XML/HTML as interpreted by the Visual Studio designer.

As you can see, in the get method the static class ControlPersister is used to transform the control tree into a string, while in the set method the static ControlParser class is used to do the reverse.

Hope this helps someone.

The thing to do is use .Net 2.0 web parts and override CreateEditorParts or implement IWebEditable on generic controls that are not web parts.

A good link on how to do that (once you know what to look for, duh!) is How to get EditorParts working in your WebParts.

Another link that summarises different solutions for several issues with web parts is WSS 3.0 webparts development. A quote that is relevant to this blog entry:

Toolpanes can be customized in a number of ways. A web part by itself can declare custom toolparts which show up in the toolpane by overriding the GetToolParts method (WSS WebPart) or CreateEditorParts (ASP.NET WebPart).

A developer can also customize the toolpane generically by supporting the ICustomizeToolpane interface (which allows you to redefine the structure of the toolpane UI) or supporting IAddToGallery (which allows you to add new gallery "tabs").


I am still working on clarifying that out as the documentation from MSDN is almost non existent on the subject. It appears that using ICustomizeToolPane is only supported for Sharepoint web parts and not for ASP.Net web parts. I yet know of no other way of changing the toolpane except by using some javascript from the web part editor (which would suck) and it might not even be possible.

Update: The rest of this post is not longer relevant. I believe it is the way it was done in the old Sharepoint days, when Sharepoint web parts were not based on ASP.Net 2.0.

Click to show anyway

This entry will be sort of unorganised, as I am slowly crawling to the jungle of options and bad documentation for Sharepoint. I will structure it as a list of points that I pass through and the solution for each problem. Hopefully, you will find something useful in it.

First of all, you cannot run Sharepoint on XP. Don't event try it. You need at least a Windows 2003 machine with the free Windows Sharepoint Services (acronym WSS) or with the commercial Microsoft Office Sharepoint Server (acronym MOSS) installed. In order to access the site, you will have to access the http://SharepointComputer URL.

Section: publishing a web part to the Sharepoint site running on WSS.
  • A web part project is a class library with associated libraries for it. First step is publication, which means copying the library files into the sharepoint site bin folder.
    Solution:
    1. find the physical location for the Sharepoint site onto the Sharepoint computer(usually wwwroot\wss\VirtualDirectories\80)
    2. copy the library files in the bin subfolder
  • Second step is loading the web parts into the Sharepoint gallery.
    Solution:
    1. open the http://SharepointComputer url
    2. open the Site Actions top-right menu and go to Site Settings
    3. open the Galleries - Web Parts link
    4. select the New option from the top toolbar
    5. the webparts in the library should appear in the list. check the checkbox next to them
    6. click Populate Gallery. now the web parts should be available in any page
  • Last step is adding the web parts to a page.
    Solution:
    1. go to any page that you can edit
    2. go to Site Actions and select Edit Page
    3. click the appropriate Add a Web Part header
    4. check the checkbox next to the web parts you want added, then click OK


Section: Troubleshooting the published web parts
  • If you have an error, you probably have a generic error page that says nothing of relevance.
    Solution:
    1. go to the physical location of the Sharepoint site
    2. edit the web.config file and set customErrors to mode="Off"
    3. refresh the Sharepoint site page in the browser
  • Now the error is much clearer and you see permissions errors that show Access Denied.
    Solution:
    1. go to the physical location of the Sharepoint site
    2. edit the Properties of the library files that you copied in the bin folder and set access for the asp.net user or (if you are lazy) for Everyone to read the site
  • Now the error you see other permissions errors of which you understand nothing, mostly linked to OnPrerender or Render methods.
    Solution:
    1. go to the physical location of the Sharepoint site
    2. edit the web.config file and (if you are lazy) set trust to level="Full" (capital F) or try to create your own security policy (complicated)
    3. refresh the Sharepoint site page in the browser
  • Oh, joy, the ugly error page with lots of information has vanished, leaving instead a nice error page saying nothing useful except File Not Found.
    Solution:
    1. go to the physical location of the Sharepoint site
    2. edit the web.config file and set compilation to debug="true" and SafeMode to CallStack="true"
    3. refresh the Sharepoint site page in the browser
  • Weird and unexplained errors occur.Solution:
    1. on the Sharepoint computer go to Administrative Tools and select Sharepoint 3.0 Central Administration
    2. that should open a site that is used to configure the Sharepoint site
    3. alternatively you can try the same Sharepoint URL in the browser, but using the port that was assigned to the configuration site (you can get the port from the name of the folder in wwwroot: wwwroot\wss\VirtualDirectories\[port that is not 80]
    4. go to the Operations section and select Diagnostic Logging
    5. In the Trace Log section you should see a Path, copy it to the clipboard
    6. Open the said path in Start/Run and it should open the Logs folder
    7. Open the latest log file (might need to press Ctrl-R to refresh the folder or to close the log file if already open and reopen it) and look for any cause for the errors


To be continued...

and has 0 comments
A friend of mine showed me a little information from MSDN that described the behaviour of methods that have the same name as other methods from the base class. Go to the MSDN site and scroll to the Override and Method Selection section.

A small excerpt: Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class. Only if the C# compiler cannot match the method call to an original method on Derived will it try to match the call to an overridden method with the same name and compatible parameters.

Long story short: if you create a method in a derived class that has the same name as a method in the base class, the method in the derived class will always be used, even if the base class method matches better the call signature. In other words Derived.DoWork(double value) will be used instead of Base.DoWork(int value), even the value passed is an integer. Indeed, the double value method will be used even if there is a Derived.DoWork(int value) method, but one that overrides a method in Base.

You can solve this by casting to the base class, but the best idea is to never create methods with identical names to ones in the base class.

Yay! New Github project: EasyReplace.

What it does is replace all files in a folder hierarchy with the files you drag&drop on the app info box. It is very helpful when you want to replace old library files or some other versions of your files with newer ones without having to manually navigate through solution folders.

The WPF Infragistics controls 9.2 feature a grid called the XamDataGrid, which has a lot of options and is better designed than the horrible web grid from the same company. I wanted to bind the grid to a DataSet, one that has two tables (Data and Details) that are connected through a data relation (named keyRelation). Also, the fields are not auto generated, but defined in the FieldLayouts block.

First step: define the field layouts. Then bind to the DataSet. No go. The only way I could see anything was if I bound to the first table in the dataset (Data). Even so, the fields that were shown were those from the second FieldLayout definition, not the first. After googling a while I finally found the answer: you need to have a Visible field that has the name of the data relation.

So, the final solution for binding a DataSet hierarchically to a XamDataGrid when AutoGenerateFields is set to false:
  1. Bind the XamDataGrid DataSource to the parent table (or its DataView)
  2. Define two FieldLayout sections in the FieldLayouts block for each of the tables
  3. Add a Field with the same name as the data relation between the two tables to the parent table FieldLayout block


Example:

<DataPresenter:Field Name="keyRelation" Visibility="Visible"/>

Ok, I know I promised you some cool posts and I really was going to write them. However, I am in my own personal crisis and all because of Infragistics controls. Ok, I know that some people like to complain and blame others for their mistakes. I am tempted to do that all the time and I am not always succeeding in abstaining, but this time it is not a pointless blame shift, this is totally real.

Let me put it in no uncertain terms: Infragistics controls suck shitty balls! They are poorly made, badly documented, there is no architecture that one can talk about (except in funny anecdotes at parties) and they are a complete pain in the ass. After giving some time estimates of how long it would take me to finish up some tasks I ended up repeatedly doubling that time because of the stupidity of Infragistics controls. Have I mentioned enough the shitty balls? And the sucking? Because I don't feel completely satisfied.

A small example: class A is inherited by class B. The functionality of class B is implemented in class A as "if I am B, then...". Then other classes using the A class sometimes have checks to see if it is not B, so that they would behave in a completely different way. I am not a brilliant software architect or something, but this is simply insane!

What about the grid columns and rows that are NOT web controls, nor do they implement some events or overridable methods that control their rendering. Instead, the grid is asking questions like "is this a template column? Then add this to the rendered string" (so not even a Controls collection that one can manipulate). And if this weren't enough, I get to have to fix errors in the javascript from Infragistics by replacing whole functions, because there is no other way to get through. One step forward and two back, just like bloody Sisyphus!

I had expected this to take 5 days and it took 3 weeks and I am still not done. My self esteem is plummeting, I am losing my will to live, I feel like the only satisfaction I could have is to go to the Infragistics team and tear them limb by limb, laughing all the way. I sincerely wish all of their managers, sales people, developers and remote assholes that finished tasks without consideration for the other developers they were working for a slow and painful death.

The fixes and solutions I have found are so unavoidably ugly that I don't dare to publish them on the blog, so my advice for you if you use Infragistics controls is to throw them all away and start from scratch. It will take you longer, but in the end you get a good thing, satisfaction for a job well done and a maintainable code. Don't worry, you can be a completely useless developer and you will still do a better job.

On a brighter note, I may start some attempts to code in Mono or at least create stuff in a different domain that what I have worked so far, so good things will happen on the blog, only not in the immediate future.