Wednesday, August 25, 2010

Handling Leaking Handles




If Handle count reaches more than 5000 count, whole PC might freeze and become unresponsive.

In the Event Log, you might have seen: “The server was unable to allocate from the system nonpaged pool because the pool was empty” message before system frozen.


This application had many wpf third party components, events and ui updates that were happening every 5 seconds, including tree updates. And it was leaking handles.

I verified that by cycling major logical parts, handle leak was not happening. But it happened when the whole flow was executed. When in debug mode, following the flow, leak does not happen. This was timing related.



Short Story Shorter, this is how I fixed it. Calling GC.Collect(2, GCCollectionMode.Forced) on each cycle fixed the leak. Yes, you would say that eventually GC should collect the thread. Here is a relevant issue that other people reported. And Microsoft defect that had to do with how GC cleans up unused threads, this is what they say:

“The problem is that CLR thread handles (and other associated data structures) are cleaned up by the finalizer thread, which normally only runs in response to a garbage collection (GC). If many threads are created and destroyed before a GC occurs (which would be the case if there were few memory allocations in the meantime) then it has the effect of "leaking" handles and memory, althgough these will be reclaimed the next time finalization is triggered. A workaround is to periodically manually trigger finalization, through calls to GC.WaitForPendingFinalizers. As I said, we are working to correct this in a future CLR release.“ –Microsoft.


Solution 1:

So if you are in a long run leaking handles, see if GC.Collect(2, GCCollectionMode.Forced)  fixes it. If not, then you deal with logical gaps. Readon further.


Solutions 2,3,4,..:

Possible Leak Causes:


What does NOT leak Handles:

  • Extra subscriptions to Events do not lead to leaking Handles
  • Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart((), does not leak handles. Verified.



Close or Dispose on StreamWriter related objects? In most cases, it is more appropriate to Dispose it instead of Close, it depends, see article Close vs. Dispose.


More about Handles.

Tuesday, August 10, 2010

if This, Then else That


If Else statements are the major part of Coding. These are the roads that split and divert the streams of logic. The point that I want to tackle here is about how phrasing the “If Else” statements can influence the mindset of writer and reader of the code. The claim that I would make is that “If” statements are better be phrased in positive term. And the operations in “If” block, are better be handling the main, a general, a positive flow of logic. And the rest is for “Else” block.

Thus, developer is concentrating first on positives and only then on negatives. Goal first, diligence second. Main flow first, edge cases second. Wall first, coloring it second.



If (something)


   do this




  do that



By concentrating first on the positive aspect helps person to get into the subject of the statements. “do this” communicates the context, a pathway towards some goal, and “do that” communicates the edge case, a complimentary addition to “do this”. There can not be This without That. This and That go together. What’s more important? This or That? Both? What’s the prioritization?This first, That second, isn’t it?

Friday, July 2, 2010

.Net App Crushes on Windows Server 2003? user-defined breakpoint?


are you in trouble?



some possible causes might be calling Debugger.Break();, clean them up.


Another case reported, here, no resolution though.

Another idea, catch(Exception) vs catch, more here, did not help for me.

Another fact, if you would debug this application remotely, this “user-defined breakpoint” symptom disappears. For remote debugging, see here.

In this particular case, the cause was the null references.

The hunt is still on on the real cause.

Wednesday, May 26, 2010

SelectedItem disables associated Buttons



Situation: There is a List, and some buttons that are ought to act on current selected item in the list. But if there are no items or no item is selected then you want these buttons to be disabled.

The idea: Having buttons disabled/enabled implicitly/automatically based on the currently selected item in the list.

  1. <Style x:Key="disableIfNoListItemSelected" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
  2.   <Style.Setters>
  3.     <Setter Property="UIElement.IsEnabled" Value="True" />
  4.   </Style.Setters>
  5.   <Style.Triggers>
  6.     <DataTrigger Binding="{Binding SelectedIndex}" Value="-1">
  7.       <Setter Property="UIElement.IsEnabled" Value="False" />
  8.     </DataTrigger>
  9.   </Style.Triggers>
  10. </Style>


  1. <Button Name="cmdShow"
  2.                     DataContext="{Binding ElementName=grdTemplates}"
  3.                     Style="{StaticResource disableIfNoListItemSelected}">
  4.                 </Button>

Notice in the usage, when applying a style to a button, it is required to assign a DataContext of this button to the List that is being watched.

Tuesday, May 18, 2010

Closing Modal Dialog Window in WPF


If it is a modal dialog box, then it most probably has OK, Cancel buttons. If it has OK, Cancel buttons, them most probably the “client initiator” wants to know if Ok was pressed or not.


Remember WinForms had DialogResult enumeration? It is a bit different with WPF, ShowDialog() returns bool?.

bool? result = form.ShowDialog();if (result.HasValue && result.Value){ DoMyThing();}

When will result.Value be false?  Make sure that you do this only for True/Ok case, the default is false:

private void Ok_Click(..){ this.Close(); this.DialogResult = true;}

and one more thing. To close dialog on Esc, you want this:


For OK button you want this:


This way, when user presses Enter, OK button is pressed.


Warning about IsCancel and Cancel button. There seems no way to Cancel the “Cancel event”. So if user clicks Cancel, windows is going to be closed. If you know a way for canceling the closure, please post.

Wednesday, May 12, 2010

Implicitly “degrading” ui controls


If this is valuable then mostly as an idea for now. Current implementation might be too limited and can be further enhanced.

The goal is to hide or disable ui controls if they do not show anything, or whatever they show is missing. Degrades=Hide or Disable.

In WPF terms and in this cut, I’ve made that ui control becomes hidden or disabled automatically if when DataContext becomes null. This implies that host has to be bound to something real, and presence of that real thing implicitly degrades(or not) the host.

Styles from Resources
  1. <Style x:Key="hideStackPanelIfNull" TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}">
  2.     <Style.Setters>
  3.       <Setter Property="UIElement.Visibility" Value="{x:Static Visibility.Visible}" />
  4.     </Style.Setters>
  5.     <Style.Triggers>
  6.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  7.         <Setter Property="UIElement.Visibility" Value="{x:Static Visibility.Hidden}" />
  8.       </DataTrigger>
  9.     </Style.Triggers>
  10.   </Style>
  12.   <Style x:Key="disableButtonIfNull" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
  13.     <Style.Setters>
  14.       <Setter Property="UIElement.IsEnabled" Value="True" />
  15.     </Style.Setters>
  16.     <Style.Triggers>
  17.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  18.         <Setter Property="UIElement.IsEnabled" Value="False" />
  19.       </DataTrigger>
  20.     </Style.Triggers>
  21.   </Style>
  23.   <Style x:Key="disableStackPanelIfNull" TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}">
  24.     <Style.Setters>
  25.       <Setter Property="UIElement.IsEnabled" Value="True" />
  26.     </Style.Setters>
  27.     <Style.Triggers>
  28.       <DataTrigger Binding="{Binding}" Value="{x:Null}">
  29.         <Setter Property="UIElement.IsEnabled" Value="False" />
  30.       </DataTrigger>
  31.     </Style.Triggers>
  32.   </Style>

Usage Example
  1. <StackPanel DataContext="{Binding ElementName=myList, Path=SelectedItem}"
  2.           VerticalAlignment="Center" Orientation="Horizontal"
  3.           Style="{StaticResource hideStackPanelIfNull}">
  4.     <TextBlock Text="Name:"></TextBlock>
  5.     <TextBlock Text="{Binding Path=Name}"></TextBlock>
  6. </StackPanel>


In this example StackPanel is bound to SelectedItem. If there is nothing in the list, SelectedItem becomes null and that degrades the controls that bear presented here styles, textblocks become disabled or hidden.

Some caveat. Obviously this requires to overwrite your style. It might conflict with your style requirements. In above shown example I am pointing to StackPanels which usually do not need style.



WPF binding binds one thing to another based on default conversion. For fancier conversion there is Converter. With Converter you can map more than one things to one thing.

User List in a Combo Box
  1.     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  2.     {
  3.         string name = string.Empty;
  4.         if (value is MyUser)
  5.         {
  6.             MyUser user = value as MyUser ;
  7.             name = string.Format("{0}{1}[{2}]", user.FirstName, user.LastName, user.ZipCode.ToString());
  8.         }
  9.         return name;
  10.     }… …<local:UserNameConverter x:Key="userNameConverter"/>
  11. <ComboBox>
  12.   <ComboBox.ItemTemplate>
  13.     <DataTemplate>
  14.       <StackPanel Orientation="Horizontal">
  15.         <TextBlock Text="{Binding Converter={StaticResource userNameConverter}}" />
  16.       </StackPanel>
  17.     </DataTemplate>
  18.   </ComboBox.ItemTemplate>
  19. </ComboBox>



Some Advanced Converters on is here.

Wednesday, May 5, 2010

Troubles with VS2008 WPF Designer Crushes


Event log:

.NET Runtime version 2.0.50727.3603 - Fatal Execution Engine Error (7A2E10D2) (0)

EventType clr20r3, P1 devenv.exe, P2 9.0.30729.1, P3 488f2b50, P4 NIL, P5 NIL, P6 NIL, P7 NIL, P8 NIL, P9 NIL, P10 NIL.

Faulting application devenv.exe, version 9.0.30729.1, stamp 488f2b50, faulting module kernel32.dll, version 5.1.2600.5781, stamp 49c4f482, debug? 0, fault address 0x00012afb.

Some relevant but not useful suggestions:

1, 2, 3, 4,  any other ones ?

Tuesday, May 4, 2010

Telerik vs. Xceed



See above for a bit of syntax. Preatty similar structure. But Telerik has TextAlignment, daaa, Xceed does not. 1:0.


On the left. Telerik lets you specify “Auto” or prioritize Column Widths, just like with standard Grid’s Rows/Columns. Xceed does not have this. Xceed will resize the column, but twice more space than needed, useless. 2:0, Telerik is winning.


One more thing, Xceed demands uniqueness for FieldNames. This limits columns that would rather accept “.” binding of item itself and bind deeper inside the template. This is not good, Telerik scores one more. to sum up: 3:0, Telerik wins in this context.

As you can see, this comparison is based on basic features.

Sunday, May 2, 2010



If you would try to visualize an architecture of the product, how would it look like ?


One of the course idea for architecture is an awareness of layers, one on another, looks like Pyramid. Each layer references next one. Layers do not jump over each other. Keeping a notion of Parent->Child relationship or Client-Server or Master-Slave(this term is not used anymore).

For every class there is a client, so Class is a “server” and most probably it references another one. So that class is a “server” and a client for another server.

so per this concept.

rule 1: parent can reference child and not the child’s child

rule 2: child does not tell parent what to do, maximum it tells parent what has happened in means of return values or events. Parent will decide on next actions.

Saturday, May 1, 2010

AssemblyDescription, marking with build type




It might a be a useful idea to mark your assemblies for Debug or Release modes. So that when looking in Windows Explorer, you could determine right away, what kind of dll/exe is this.



[assembly: AssemblyDescription("AS2-Debug")]
[assembly: AssemblyDescription("AS2-Release")]



Sunday, April 25, 2010

Showing a button in Xceed DataGridView column



Want to have a button in a Grid?

3 things are here:

  1. Grid definition
  2. column definition
  3. Template for button



1. Grid: <xcdg:DataGridControl x:Name="mGrid" />

2. Columns:

xcdg:Column FieldName="MyThing" Title="Things"
<xcdg:Column FieldName="." Title="Action" MinWidth="100" MaxWidth="200" CellContentTemplate="{StaticResource ActionButtons}"/>

3. and the actual template:<UserControl.Resources>

DataTemplate x:Key= "ActionButtons">

StackPanel Orientation="Horizontal">

Button Content="{BindingNextAction}" DataContext="{Binding}" IsEnabled="{Binding Enabled}"Click="NextAction_Click">





Wednesday, April 21, 2010

LINQ Examples


Some basic LINQ examples for queering into collections.LINQ extension here: msdn

var newThings = from thing in allThings
                 where thing.Stamp >= dateYesterday
                 select thing;

extracting different collection structure:

IEnumerable<string> ids = mUsers.Select(u => u.GUID);

getting unique ones:

IEnumerable<string> uniqueIds = ids.Distinct<string>();

finding one:

IEnumerable<User> users = mUsers.Where(u => u.GUID == thatGUID);

flattens the resulting sequences into one sequence

IEnumerable<Locations> places = mUsers.SelectMany(u => u.Locations);

Sunday, April 18, 2010

Flattening structure for Hierarchical display



I’ve been dealing before with HierarchicalDataTemplate where one Template references another one for 2 level hardcoded data structure. What about data that recursively references several types of “children”. Plus each type shows itself uniquely. How to visualize this ?

See tree screenshot as an example. In this example we have 3 data types: Drive, Folder, Files. Drive is a top level. Folder references Folder and Files.

Here is an overview of relationships between TreeView and Data Templates.

We need 2 things: DataTemplateSelector and “HierarchyConverter”.

HierarchyConverter is IValueConverter. HierarchyConverter parses through given object and returns “Children”, one level after another.

DataTemplateSelector returns a HierarchicalDataTemplate based on given object Type. Similar object types that were handled in HierarchyConverter. DataTemplateSelector is assigned to ItemTemplateSelector.

Each data type has an appropriate HierarchicalDataTemplate. Top level data template(Drive in our example) engages DataTemplateSelector. And all data types engage HierarchyConverter.

Top Level Template:

<HierarchicalDataTemplate x:Key="DriveTemplate"
ItemTemplateSelector="{StaticResource TreeTemplateSelector}"
ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}">

The rest of levels follow similar format:

<HierarchicalDataTemplate x:Key="FolderTemplate"  DataType="{x:Type Framework:Folder}"

                       ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}">

And to start it with your favorite Tree View:       <my:CustomTreeView Name="MyTree" ItemTemplate="{StaticResource DriveTemplate}"             

Let’s try to summarize data flow here. TreeView accepts data and streams to DriveTemplate. DriveTemplate sticks around until Folder in means of HierarchyConverter, while engaging TemplateSelector. At that time, different DataTemplates are activated which again engage recursive nature of HierarchyConverter.

Friday, April 16, 2010

WPF Threads: Dispatcher


Apparently WPF framework became a bit smarter in terms of threads comparing to Windows Forms.There is Dispatcher.

Now you might be forced to queue UI actions like this:

Dispatcher.Invoke(DispatcherPriority.Send, new ThreadStart(() =>
MyTree.SelectedItem = folderToEdit;

Another example for single no parameter function:

Dispatcher.BeginInvoke(new Action(() =>

Wednesday, April 14, 2010

WPF UI Automation


Some things to be aware of when engaging Microsoft Automation.

1. Run UI SPY to browse around your app structure.

2. Expand Controls that do not support UI Automation

3. Provide “good” AutomationProperties.AutomationId for controls.

Why would you expose UserControl for Automation? Some third party user controls do not support automation. Or you might want to expose custom UI structure that tailored towards desired Testing.

How to expose UserControl and see it in UI Spy ?

Something like that:



filling AutomationId
  1. <Style x:Key="AutomationEnabledRibbonGroup" TargetType="ribbon:Group">
  2.     <Style.Setters>
  3.       <Setter Property="AutomationProperties.AutomationId" Value="{Binding RelativeSource={RelativeSource Self}, Path=Label}" />
  4.     </Style.Setters>
  5.   </Style>
  7.     <Style x:Key="AutomationEnabledButton" TargetType="{x:Type Button}"BasedOn="{StaticResource {x:Type Button}}">
  8.     <Style.Setters>
  9.       <!-- Buttons without Name/x:Name have no AutomationId, this setter initializes id with the button's text  -->
  10.       <Setter Property="AutomationProperties.AutomationId" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
  11.     </Style.Setters>
  12.   </Style>
  14.   <Style x:Key="AutomationEnabledListBoxItem" TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
  15.     <Setter Property="AutomationProperties.AutomationId" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content}" />
  16.   </Style>

Thursday, April 8, 2010

Member Variables in XAML?



What ResourceDictionary is for ? It’s a descriptive way of defining “member variables” in XAML itself. Similar to member variables defined in good old Class definitions.

Define it in the XAML through means of Resources. Get it back in C# with FindResource.

WPF requires Data Structure


I’ve been working recently with some legacy architecture which is heavy xml based. There are several remotely distributed servers. Whole business model is exchanged in means of xml streams. No data structures. Now Go and visualize it in WPF UI. Nothing to bind to.

What I end up doing over and over again is creating Data Structures internally from xml streams(AltovaXML helps). This way UI can bind to something.

WPF loves Data Structure.

My selfish preferences: Create Classes for Data. Rely on them. Pass them in interfaces. Please no text/xml streams.

Tuesday, April 6, 2010

Creating MenuItems dynamically


image This approach is for creating context menu programmatically in .NET3.5/WPF. This is useful when menu structure is variable and dependable.

First there is “MyMenuItem” data structure. It maps to single imagemenu item. You create these objects, link together, and pass over to MenuManager. MenuManager would in turn convert them into real windows MenuItems.



Client Example:

List<MenuItem> menuItems = mMenuManager.Build(new List<MyMenuItem>() { 
new MyMenuItem() { Label = "1111"},
new MyMenuItem() { Label = "1111"},
new MyMenuItem() { Label = "1111"},

foreach (MenuItem menuItem in menuItems)

Download MenuManager.cs file here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

public class MyMenuItem
public string Label { get; set; }
public Image ImageIcon { get; set; }
public object Tag { get; set; }

public List<MyMenuItem> DeeperItems
get { return mDeeperItems; }
set { mDeeperItems = new List<MyMenuItem>(value); }

private List<MyMenuItem> mDeeperItems = new List<MyMenuItem>();

/// <summary>
/// Created by Sergey Malyan
/// </summary>
class MenuManager
#region events
public delegate void MenuClickedDel(MyMenuItem item);
public event MenuClickedDel MenuClicked;


public List<MenuItem> Build(List<MyMenuItem> itemsIn)
List<MenuItem> items = new List<MenuItem>();

foreach (MyMenuItem item in itemsIn)

return items;

private MenuItem Traverse(MyMenuItem item)
MenuItem menu = new MenuItem();
menu.Header = item.Label;

if (item.ImageIcon != null)
item.ImageIcon.Width = item.ImageIcon.Height = 16;
menu.Icon = item.ImageIcon;

foreach (MyMenuItem item2 in item.DeeperItems)

menu.Tag = item;

if (item.DeeperItems.Count == 0)
menu.Click += new System.Windows.RoutedEventHandler(menu_Click);

catch (Exception ex)

return menu;

private void menu_Click(object sender, System.Windows.RoutedEventArgs e)
MyMenuItem item = ((MenuItem)sender).Tag as MyMenuItem;

if (MenuClicked != null)


Thursday, April 1, 2010

how to instantiate a class from xml


also known as xml deserialzing a class from a file.



Feeded xml data has to match the fields. For reading in, see this post.

saving class instance to a file


also known as serializing a class to a file.


So. That’s it. Go check the file context for xml formatted data.

Monday, February 1, 2010

Best setup I Ever Encountered


Team Foundation Server





See full size imageCode Reviews




.Net Technologies





Technical Discussions




Seems these ingredients contribute to productivity and fun.

Friday, January 22, 2010

Controlling Fonts in App


You probably want to have a consistent settings for user controls in your WPF application, at least maybe a default set. Here is a basic example of how to keep Font, Size consistent for such basic controls as TextBlock and Label.


Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
Setter Property="TextBlock.FontFamily" Value="Calibri" />
Setter Property="TextBlock.FontSize" Value="11" />
Style>… …

That’s it. This style will jump up itself and initialize listed properties with values specified in this Application level resources. You can still overwrite them in the Forms xaml by explicitly defining them.