dimanche 2 janvier 2011

SOS.DLL, object Address and Visual Studio debugger

Introduction

When we search leak memory in our application, we use SOS.dll in Windbg.exe or Visual studio IDE.

This tool is very very usefull but it is not easy to walk accross the references tree of object.

Visual Studio is more powerfull to do that. “Quick watch window” for example with its property explorator is perfect.

but “sos command’s” returns only addresses of objects …

Evaluate an object in VS from GCHandle address

!GCRoot give often this type of informations :

!GCRoot -nostacks 00c58918
DOMAIN(0015DF20):HANDLE(Strong):3011f8:Root:00c21b30(System.Threading.Thread)->
00c272b4(System.Object[][])->
00c272c8(System.Object[])->
00d0b0fc(System.Object[])->
00d0b0dc(System.EventHandler)->
...

If you evaluate this in VS debugger :

System.Runtime.InteropServices.GCHandle.FromIntPtr(new IntPtr(0x3011f8)).Target

You found the instance of System.Threading.Thread (address 00c21b30) !!

Find address object in Quick watch windows …

It is possible to fix the memory area of an object with System.Runtime.InteropServices.GCHandle object. When you create a GCHandle on a object with GCHandleType.Pinned option. GCHandle.AddrOfPinnedObject() return the memory location of it !

BUT it is possible to use internal method to give the current address of object even if this object is not pinned

If you evaluate this, in “Quick Watch window” of VS, or in “Immediat window” :

? string.Format("{0:x}",int.Parse(System.Runtime.InteropServices.GCHandle.InternalAddrOfPinnedObject(System.Runtime.InteropServices.GCHandle.Alloc(myObjectSomeWhere).GetHandleValue()).ToString())-4)

The result give the same address of myObjectSomeWhere in  SOS commands Like

  • !DumpObj
  • !GCRoot
  • !DumpHeap

If you know where the object is in your application, you can find the address of it, and compare with SOS Commands results.

Evaluate object in VS from directly address

It would be very usefull to evaluate, for example, 00d0b0dc EventHandler instance in VS debugger !

BUT I did not found a tips to do this … directly, sorry … :-(

This reference http://stackoverflow.com/questions/3141428/conversion-from-void-to-object-in-c asks the same question without answer …

If I would find it, I will be able to update this post !

References

dimanche 17 octobre 2010

Fast Property Accessor without dynamic IL

Abstract

I need to access property value on a object with Reflection API. It is very useful to create for example a generic Deep Clone API on POCO object.

BUT :

  • Sometimes, Setter method of the object is not public.
  • I need the very very high performance to do it.
  • It seems the better way to do is Deletage.CreateDelegate method but it is important to use Invoke() method on it. DynamicMethod is very poor performance approach.
  • I don’t want use IL approach because it is too hard to develop and maintains.

I propose helper based PropertyInfo, which support the interface IPropertyAccessor. This interface has a method GetValue and SetValue.

A solution

I create a small helper to encapsulate a delegate in generic decorator that’s support my own IPropertyAccessor interface :

IPropertyAccessor Interface is simple :

    public interface IPropertyAccessor
    {
        PropertyInfo PropertyInfo { get; }
        string Name { get; }
        object GetValue(object source)
        void SetValue(object source, object value); 
    }

An example :

// UneClasse : a simple class with an Int property PropertyA
var c = new UneClasse();
c.PropertyA= 12345;
PropertyInfo piA = typeof(UneClasse).GetProperty("PropertyA");
var paA = PropertyInfoHelper.GetFastAccessor(piA);
Assert.AreEqual(c.FieldA, 12345); // Ok !
Assert.AreEqual(piA.GetValue(c, null), 12345); // Ok !
Assert.AreEqual(paA.GetValue(c), 12345); // Ok !
paA.SetValue(c, 54321);
Assert.AreEqual(c.PropertyA, 54321); // Ok !
Assert.AreEqual(piA.GetValue(c, null), 54321); // Ok !
Assert.AreEqual(paA.GetValue(c), 54321); // Ok !

Performance

Some tests show importants differences between differences approachs.

NB : all duration is done with 100 000 call on my computer.

Direct call : ~4 ms.
PropertyInfo.SetValue on public setter ~300 ms.
PropertyInfo.SetValue on private setter ~1400 ms.
Stronged delegate on SetValue MethodInfo (Private or public) ~5 ms.
Delegate call with DynamicInvoke (Private or public) ~1500 ms.
IPropertyAccessor helper ~9 ms.
  • the better way, of course, is direct call : (4 ms)

myInstance.PropertyA = 1234;

  • Use SetValue method on PropertyInfo  (282 ms) (Setter is public)

PropertyInfo piA = typeof(UneClasse).GetProperty("PropertyA");

piA.SetValue(myInstance, 1234, null);

  • Use SetValue method on PropertyInfo  (1391 ms) (Setter is private)
  • Use strong typed Delegate created with Delegate.CreateDelegate() : 4 ms !! (same of direct call and even if Setter is private)

var setMethodA = piA.GetSetMethod(true);
var _setHandlerATyped = (SetValueHandler<UneClasse,int>)Delegate.CreateDelegate(typeof(SetValueHandler<UneClasse,int>),
    setMethodA);

_setHandlerATyped.Invoke(myInstance, 1234)

  • Use my helper : 9 ms !!

IPropertyAccessor paA = PropertyInfoHelper.GetFastAccessor(piA);

paA.SetValue(myInstance, 1234)

Compare “CreateDelegate” versus “dynamic IL”  during intialisation process

in System.Web.dll, you can find an internal class “System.Web.Util.FastPropertyAccessor”.This class use Emit functions to generate dynamic assembly and dynamic code.

I compare this approach (with little reflection to acces internal members) with CreateDelegate approach in console application and 5000 Test class with One property.

The result is :

  IL Approach (System.Web.Util
.FastPropertyAccessor)
CreateDelegate Approach
(IPropertyAccessor)
Duration 11920 ms. 1337 ms.
Memory delta ~32300 Ko ~6000 Ko

 

The code of the helper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Tools.Reflection
{
///
/// Représentation d'une propriété pour accélerer de maniére considérable les écritures/lectures par reflection
/// sur les propriétés d'un object
///

public interface IPropertyAccessor
{
///
/// La propriété concernée
///

PropertyInfo PropertyInfo { get; }
///
/// Le nom de cette propriété
///

string Name { get; }
///
/// Récupération de la valeur de la propriété
///

/// l'object concerné
/// valeur de la propriété
object GetValue(object source);

///
/// Mise en place d'une nouvelle valeur dans la propriété
///

/// l'object concerné
/// la nouvelle valeur pour la propriété
void SetValue(object source, object value);

}

///
/// Classe helper pour obtenir l'accesseur sur une propriété donnée
///

public static class PropertyInfoHelper
{
private static Dictionary _cache = new Dictionary();
///
/// Obtention du helper pour acceder au getter/setter de la propriété
///

///
///
public static IPropertyAccessor GetFastAccessor(PropertyInfo propertyInfo)
{
IPropertyAccessor result;
lock (_cache)
{
if (!_cache.TryGetValue(propertyInfo, out result))
{
result = CreateAccessor(propertyInfo);
_cache.Add(propertyInfo, result); ;
}
}
return result;
}

///
/// public pour les tests de performances
///

///
///
public static IPropertyAccessor CreateAccessor(PropertyInfo propertyInfo)
{
return (IPropertyAccessor)Activator.CreateInstance(
typeof(PropertyWrapper<,>).MakeGenericType
(propertyInfo.DeclaringType, propertyInfo.PropertyType), propertyInfo);
}
}

///
/// Classe concrete implémentant IPropertyAccessor
///

///
///
internal class PropertyWrapper : IPropertyAccessor
{
private PropertyInfo _propertyInfo;

private Func _getMethod;
private Action _setMethod;

///
/// Constructeur public
///

/// la propriété à encapsulé
public PropertyWrapper(PropertyInfo propertyInfo)
{
_propertyInfo = propertyInfo;

MethodInfo mGet = propertyInfo.GetGetMethod(true);
MethodInfo mSet = propertyInfo.GetSetMethod(true);

// Rq : on peut par se biais acceder aussi aux accesseur privé
// tous les aspects liés à la sécurité est donc pris en charge par CreateDelegate
// et non à chaque appel à GetMethod/SetMethod

_getMethod = (Func)Delegate.CreateDelegate
(typeof(Func), mGet);
_setMethod = (Action)Delegate.CreateDelegate
(typeof(Action), mSet);
}

object IPropertyAccessor.GetValue(object source)
{
return _getMethod((TObject)source);
}
void IPropertyAccessor.SetValue(object source, object value)
{
_setMethod((TObject)source, (TValue)value);
}

///
/// Voir
///

public string Name
{
get
{
return _propertyInfo.Name;
}
}

///
/// Voir
///

public PropertyInfo PropertyInfo
{
get
{
return _propertyInfo;
}
}

}

}


TODO List




  • test on real application : It is just a prototype !


  • improve with this[] property



References



dimanche 21 février 2010

Footer on WPF DataGrid: by use several synchronized datagrid

Introduction

Last year, I proposed a version of WPF DataGrid with Footer.

But this version can not apply on new WPF 4.0 Datagrid (because i was make too much changes in source code of the component)

With this new approach, I use several DataGrid in the same Window, and I synchronizes each one on :

  • Scrolling event (horizontal and vertical)
  • Drag and drop column header
  • Change width of column on main DataGrid

Even if it is more complex to apply for each Data window (It is necessary to instanciate several DataGrid, set relatation between each one, etc.) , It seems pretty good because :

  • It can apply on new version WPF 4.0 Datagrid
  • It can manage too the merge header of multiple column (cf demo)
  • It can use to do something like “Microsoft Excel" to freeze some column or row in a global Data grid !

Screenshot of the demo :

ScreenShot2

Download

Download v1.00 here

  • WPF 3.5 version (on Visual Studio 2008)
  • WPF 4.0 version (on Visual Studio 2010 Beta)

API :

To do this, It is necessary to :

  • Have the same number of column in each DataGrid (except if you merge header column with specific attached property)

<tk:DataGrid.Columns>
    <tk:DataGridTextColumn local:AssociatedDataGrid.ColumnSpan="2"
                           Binding="{Binding A}"/>

  • I use attached Dependency Property to set the link between main grid and another grid

<tk:DataGrid
             Name="xMain"
             Grid.Row="2"
             Grid.Column="2"
             ItemsSource="{Binding DataSource}"
             local:AssociatedDataGrid.Bottom="{Binding ElementName=xBottom}"
             local:AssociatedDataGrid.Top="{Binding ElementName=xTop}"
             local:AssociatedDataGrid.Right="{Binding ElementName=xRight}"
             local:AssociatedDataGrid.Left="{Binding ElementName=xLeft}"
             AutoGenerateColumns="False">

  • and it’s all !

My demo is a demo … I think lot of thing is not finished by main idea is in it !

Best regards

Thibaud

dimanche 29 novembre 2009

CollectionView.GetItemProperties : Great and good differences between WPF 3.5 and 4.0

WPF 3.5 algorithm

In WPF 3.5, when you bind your own Collection to a wpf control, "WPF framework" needs define the list of all allowed properties of the items of the collection.

To do this, "WPF Framework" tests if collection is a generic type, AND if the generic type contains only one sub-type : it is use to define the item type of collection, in other case, "WPF Framework" try to use the first item of the collection (if collection is not empty)

With Reflector, you can find a part of this algorithm in CollectionView.GetItemType() :

internal Type GetItemType(bool useRepresentativeItem)
{
Type type = this.SourceCollection.GetType();
if (type.IsGenericType)
{
Type[] genericArguments = type.GetGenericArguments();
if (
genericArguments.Length == 1)
{
return
genericArguments[0];
}
}

else if (useRepresentativeItem)
{
object representativeItem = this.GetRepresentativeItem();
if (representativeItem != null)
{
return representativeItem.GetType();
}
}
return null;
}

in WPF 4.0 beta 2, Algorithm is different !!!!


WPF 4.0 beta 2 algorithm

in WPF 4.0, framework test if original collection source support a generic IEnumerable type and If test is True, the type of this subtype of Generic IEnumerable !


the code of this version is :

internal Type GetItemType(bool useRepresentativeItem)
{
foreach (Type type2 in this.SourceCollection.GetType().GetInterfaces())
{
if (
type2.Name == IEnumerableT)
{
Type[] genericArguments = type2.GetGenericArguments();
if (
genericArguments.Length == 1)
{
return
genericArguments[0];
}
}
}

if (useRepresentativeItem)
{
object representativeItem = this.GetRepresentativeItem();
if (representativeItem != null)
{
return representativeItem.GetType();
}
}
return null;
}

Consequences :

It is a very important change if you develop your own collection. With the new approach, It is possible now to create generic collection with more than one sub type !


for example, in MVVM architecture, it would be very nice to create a ViewModel of collection to enumerate ViewModel of item with a specific contraint


Exemple :


public class  ViewModelCollectionBase<TViewModel, TModel> : IEnumerable<TViewModel>
where TViewModel : ViewModelBase<TModel>
{
…  
}


public class ViewModelBase<TModel> where TModel : class
{

}

lundi 30 mars 2009

Static event on ViewModel in MVVM : Helper that prevents Leak errors memory, and so more …

Abstract

Use static public event properties on ViewModel class for :

  • High level of API to mask the technical complexity of the problem
  • ensure communication between ViewModel and View part without leak memory AND with only one wired process on View part even if ViewModel contains lot of entities.
  • ensure communication between entities of ViewModel and ensure it in a graph of entities.
  • accept lot of quantity of ViewModel entities without overhead (memory or/and performance)
  • controls target’s type which is allowed to use on these events

Introduction

In MVVM architecture, I need create a graph of entities in ViewModel part with POCO objects. these entities must communicate with …

  • another instances of ViewModem
  • View part of the MVVM architecture

… without direct dependency between Sender to the targets : ViewModel has not dependency on "View Part" AND sometimes, entities of ViewModel  do not link directly all another entities of the model

A good technical approach to do this is used a static CLR Event on ViewModel class, static events are always accessibles even if ViewModel instance not yet exists

  • from another ViewModel class
  • from “View part“ of MVVM like a Window or UserControl.

BUT we need integrate these contraints :

  • a Simple static CLR Event keeps a reference on target’s instance : Garbage collector will never free target’s instance if this target will not remove its handler in the static CLR event.
  • If static CLR event is used by a lot of quantity of ViewModel instance. The performance must stay high.
  • If we create more than one instance of the ViewModel graph and use only static CLR Event : Each Invoke of static event must reach only the “good” instances of ViewModel (or View part) and not all referenced target.

“Good” instances seems only ViewModel entity that have relations with the invoker ViewModel OR View part that bind with ViewModel entity.

I proposed a main class : StaticEvent<> that can help us to do this !

How can I use it ?

Example of code to declare a new Event :

private static StaticEvent<MyEventArgs> _myEvent = 
  new  StaticEvent();
public static event EventHandler<MyEventArgs> MyEvent
{
  add
  {
    _myEvent.Add(value); 
  }
  remove
  {
    _myEvent.Remove(value);
  }
}

public static void OnMyEvent(MyEventArgs e)
{
  _myEvent.Invoke(e);
}

When developper uses the event : he works with it like a classic event with += / –= operator. The internal implementation is masked.

What can I wired on this type of Event ?

StaticEvent<> generic class is a base class to implement another type of it. In Diagram class below, and the prototype, I used a ModelViewEvent<>.

This event accepts 3 types of EventHandler :

  • EventHandler on a static method
  • EventHandler on an instance entity of ViewModel
  • EventHandler on an instance of FrameworkElement.

Entities of ViewModel must derivated from ViewModelBase<> class that implements required interface (IHandlersRepository)

The sequence of calls during “Invoke process”

The main concept is base on RoutedEvent of WPF framework. In the RoutedEvent design pattern : the “route” of calls is build BY the invoker !

I was reproduce the same approach in StaticEvent class !

If the invoker is a ViewModel Entity (supports IHandlersRepository), StaticEvent asks the invoker (by IHandlersRepository.GetHandlers) and invoker must give zero, one or more EventHandlers which will be called by StaticEvent.

So, ViewModelBase class visits each its owners and combines all handlers found during this visit.

 

 

For example, Demo application realize this sequence on an example graph

image

Using the approach of the RoutedEvent model of WPF FrameworkElement solves …

  • Communicate between ViewModel instances
  • have good performance event with a huge quantity of entities

I will use this approach in a MVVM Framework to send message between ViewModel instances : Example : When an ViewModel entity will be validated, and if this ViewModel is owned by another : It would be very useful that the owner ViewModel instance can stop or not the validation process of its own Son ViewModel instances !

I use it for Filter event of my own ICollectionView instance, very useful in this case !

With this approach, each instance of ViewModel (that supports IHandlerRepository) keeps references of its own EventHandler. So even if you have 1 000 000 instances of ViewModel object and just ONE static event that uses by this instances : Each instance keep one and only one EventHandler ! and moreover, StaticEvent is not a strong reference (by EventHandler) on these 1 000 000 ViewModel objects :  of course : it does not know these objects !!

Prevent against Leak memory issues : Using Life event cycle of FrameworkElement

Each FrameworkElement have Loaded, Unloaded and Initialize event. If you look inside the Demo, ViewEvent class creates an adapter on each FrameworkElement target. This adapter supports IHandlerRepository interface. This adapter is memorized by FrameworkElement instance (with an attached dependency property) and It uses these 3 events for accept or not a call process !

NB : WPF RoutedEvent mechanism used a roughly same approach to memorize EventHandlers (see System.Windows.UncommonField<T> internal class in WindowBase.dll and System.Windows.UIElement.AddHandler method :-)

TODO List …

  • Invoke’s strategy like Bubble, Direct, Tunnel strategy of RoutedEvent.

Class diagrams

  • StaticEvent class hierarchy : StaticEvent<> is the most important class : It have a dependancy on IHandlersRepository
      • by ProvideHandlersRepository method
      • if a handler’s target implements or not this interface (in Add(EventHandler) calls)
      • if a sender implements or not this interface (in Invoke calls)

Framework

  • ViewModel entity class hierarchy : Just a demo to use StaticEvent in ViewModel part of MVVM architecture : ViewModelEvent allows to wired a FrameworkElement instance without leak memory errors. It uses Loaded/UnLoaded event of FrameworkElement

Framework.Window

Download

Download v2.20 03/29/2009

References

previous article : http://thibaud60.blogspot.com/2009/03/helper-to-create-weak-event-with-strong.html

samedi 14 mars 2009

Helper to create a weak event with strong typed signature

Introduction

When you create an event like this

public event EventHandler<MyEventArgs> MyEvent;

and you use it like this :

{
var receiver = new MyReceiverClass();
this.MyEvent += receiver.ReceiveMethod;

}

Receiver instance will be never cleaned in memory by Garbage Collector while “this” is referenced by any another object and, if "this" is Singleton object … receiver will be never free !!!! Even if receiver is not referenced somewhere … simply because it is referenced by the event of the Singleton :-(

.Net Framework provides us with some tools to avoid this problem. You can see e.g. this reference. It is the WeakEvent patterns.

This pattern works fine but it is a little hard and complex to create an object which receives an event with out strong reference : we need to implement IWeakEventListener interface or/and use a WeakEventManager.

My helper approaches the problem in a different way:

  • It is easy to use += / –= operator to wire/unwire event with exactly the same approach of that of a classical event
  • helper does not give a strong reference on receiver event
  • helper allows additionnal functions on FrameworkElement receivers:
    -> an unloaded instance will not received event!
    -> capacity to filter Execute calls when the event is wired on different receiver (not tested …)

Example of usage

To declare an event, you need just this code :

private UIWeakEventHandler<MyEventArgs> _myEvent;
public event EventHandler<MyEventArgs> MyEvent
{
add
{
_myEvent += value; // UIWeakEventHandler is created by += operator if necessary
}
remove
{
_myEvent –= value;
}
}

public void OnMyEvent(MyEventArgs e)
{
if (_myEvent != null)
_myEvent.Invoke(e);
}

and It”s All Folks :-)

MyEvent is a public event and supports classic += / –= operator so Visual Studio offers the traditionnal helper like auto-created-code when the developper press "+=" key sequence.

Why do I want to use this?

I need to create some events in my application on singleton instance and sometimes these events could be wired on WPF Window. When using a simple event, it is always necessary to wire on Loaded event of my Window and not forget to unwire event in Unloaded event of the same Window: when forgetting them will lead to some Leak memory error and it could take ages to find the origin of the problem. I hope this type of technical approach helps me!

Download

Download v2.10 (29/03/2009)

image

  • Complete refactoring ! I will create another post in fews days to explain all news functionnalities
    • IHandlersRepository interface : new name of IModelViewEventSupports

public interface IHandlersRepository
{
    void AddHandler(ModelRoutedEvent modelRoutedEvent, Delegate handler);
    void RemoveHandler(ModelRoutedEvent modelRoutedEvent, Delegate handler);
    void GetHandlers(ModelRoutedEvent modelRoutedEvent, object sender, EventArgs e, ref List<Delegate> result);
}

    • new RoutedPropertyChangedEvent and RoutedPropertyChangingEvent
    • Create FrameworkElementHandlersRepository class to optimize memory perfomance on FrameworkElement target (Same internal approach of RoutedEvent of .Net WPF framework)
    • Example with TreeView and Recursive ModelView entity
    • Include {MethodBinding} approach in TreeView Exampleimage

Download v1.20 

  • new interface IStorableEventsObject / IModelViewEventSupports to implements a “routed event pattern”  on ModelView object

Download v1.10

image

  • the main window can open secondary window via “New Windows” button
  • “Fire static event” calls a static event and changes a Label in secondary Windows
  • “Show counter” gives you the quantity of Window2 class instance
  • “GC.Collect” executes a memory collection >> Clic on “Show counter” to see the consequences of this collection

I never used this prototype in real application and so comments will be very welcomed :-)

Best regards

Class Diagram

WeakEventHandler

Todo list

  • I started to retro-analysis Routed event of WPF framework in order to understand the way is has been designed. For example, very good performances are certainly obtained by saving Event handler of a UIElement in the same UIElement (like Dependency proprerty mechanism): the static routed event instance is only an identifier of the event and does not memorises anything else.
    My own approach is different. I have a Weak-list of Event handler: when quantity of receiver instances is important (e.g. more than 10 000) >> will possibly result in having some performance problems during the invoking process.
    Routed approach will be possible only when invoker has a link with receiver. This link will be the Logical graph of user interface in "Routed Event and UIElement invoker". >> you can find a prototype of this approach in v1.20 version of download
  • I wish to interact between these static events and a graph of data object (ModelView part of Model - ModelView - View approach ) and when an instance of data object invokes a static event, My goal is that every ancestor (and only them) of this instance (in the graph) receives the event! >> you can find a prototype of this approach in v1.20 version of download

References

dimanche 1 février 2009

Convert "CLR method" to "ICommand" with just a XAML declaration

Introduction

When we develop an application in WPF, we want to separate

  • UI in XAML stream
  • Data (in POCO object for example)
  • Links between UI and Data, interaction logic, etc. ...

for example, The Model/ModelView/View approach try do this.

One of the technical problem of this type of architecture is "How can i launch code from UI on ModelView ?"

If I want to launch a simple public method on underneath ModelView by XAML Declaration. It is not very easy.

MethodBinding approach illustrated in this application help you to do this just with declaration syntax, no more code is necessary

Thibaud Bouquely, France, February 2009.

Demo

Demo application is Downloaded here.

in Demo tabItem, you can launch this window. It's illustrate different usage of MethodBinding XAML declaration.

=>

Tutorial

  • Create an object with a public method : the method must has no parameter or just one only

    Example :public void MyMethod(); on MyObject class
  • Push this object in DataContext of yours WPF controls

    Example :in Window's constructor : this.DataContext = new MyObject();
  • Declare link between a button and the previous public Method

    Example :<Button Command="{f:MethodBinding MyMethod}" >Clic on me
  • No more code :-)
    if you clic on the button, MyMethod() is launch on MyObject instance in DataContext of the button

Other functionality

  • If public target method has one parameter, CommandParameter on Button (or ICommandSource control) is too transfered
  • If Target object has a Read-only property named MyMethodCanExecute. It's return a boolean value, It used by MethodCommand to manage CanExecute aspect of ICommand system. (rq : target object must be a INotifyPropertyChanged or a DependencyObject/DependancyProperty to use correctly this fonctionnality)

TODO list :

  • Like BindingOperations static class of WPF, add Static method somewhere to create a MethodBinding by code
  • Improve the component ! I just try in this demos, not in real application