Monday, July 30, 2007

Quick WPF tip: Alternative text for images

In HTML we have Alt tag, that provides alternative text for images (in case, that image is not exists), but what to do in XAML? Simple, use the power of DataTemplates and DataTriggers. In following example, I have data item with following properties Logo, which is Bitmap, Name and Description, that strings. I want to display Name text, in case, I have or want to disable no logo bitmap. Following code.


<DataTemplate x:Key="tmpProvider">


TextBlock TextBlock.FontWeight="Bold" Text="{Binding Path=Name}" Visibility="Collapsed" Name="AltText"/>

Image Stretch="UniformToFill" Source="{Binding Path=Logo}" Name="Image" TextSearch.Text="{Binding Path=Name, Mode=OneWay}"/>



TextBlock Text="{Binding Path=Name}"/>

TextBlock Text="{Binding Path=Description}"/>





DataTrigger Binding="{Binding Path=Logo}" Value="{x:Null}">

Setter TargetName="AltText" Property="Visibility" Value="Visible"/>



DataTemplate></PRE< P>


Simple, isn't it? Thank all, those where 10 seconds about another accessibility pattern in WPF

Saturday, July 28, 2007

Microsoft Expression Blend 2 August Preview is available

New refreshment of great XAML editing tool is available for download as Preview version. What's new? Silverlight (working with Silverlight 1.0 RC) and Visual Studio 2008 (Orcas) integration support, User controls authoring, XAML editor got some improvements, such as changing font sizes, word wrapping, etc. You can now target your build by using $(BuildingExpressionBlend) property. New storyboard picker replaces old Storyboard combobox and you can finally manipulate (scaling, resizing, etc) multiple objects.

We're looking forward for your feedbacks

Download Microsoft Expression Blend 2 August Preview

Friday, July 27, 2007

Vista Battery Saver - French version

Now you can get latest beta 2 of Vista Battery Saver in French. Great thanks to Vista french community (VistaRC) for this contribution.

If you want to use Vista Battery Saver in french, just download VistaBatterySaverSetup-MUI.msi from current release location and if your locale is FR, you'll get french UI for this application


Thursday, July 26, 2007

Microsoft is going Open Source

Oh, my godness... Microsoft implements O'Relly OSCON. This must be really fun, how far may it take...
Open Source software labs @ Microsoft, CodePlex (it's only because of Vista Power Saver, indeed), Microsoft Shared Source, Open Source ISV Forum... Sounds really fun, can we have the sources of the next Windows version? See yourself:


WPF Events and memory leaks

Today, we'll speak about RoutedEvent and possible memory leaks associated with them. If you ever use EventManager, that's really cool mechanism of external attached event handling, you'll notice about lack of ability to unsubscribe from event handlers. What to do? Is it bad design? Actually, yes. This is possible memory leak. So, what to do with it?

First of all, you can try to null handler.


if(em_handler == null)

em_handler =
new RoutedEventHandler(EM_HandlePreviewMouse);

EventManager.RegisterClassHandler(typeof(Button), TextBlock.PreviewMouseDownEvent, em_handler);


em_handler =




This will not work. Actually, the reference remains, event if handler is nulled. So, what can we do? We can use attached events. As well as we are able to attach to external event, we can unattach from it


if(re_handler == null)

re_handler =
new RoutedEventHandler(RE_HandlePreviewMouse);

this.AddHandler(Button.PreviewMouseDownEvent, re_handler);


this.RemoveHandler(Button.PreviewMouseDownEvent, re_handler)



So, this can give us possible solution, but what to do with really large objects? Unattaching from events will net destroy references to them. Actually, even in .NET 2.0 and 1.1, when we're using -= operator, we are not disposing handlers, we only disconnect from it.

In WPF where is new cool class, named WeakEventManager and it's implementation IWeakEventListener. But how to use them in our case? For real it's rather simple. Create new object, derrived from WeakEventManager for class you want to handle events. Just like this


public class WeakButtonEventManager:WeakEventManager


protected override void StartListening(object source)


Button b = source as Button;

if (b != null)


b.PreviewMouseDown +=
new MouseButtonEventHandler(OnPreviewMouseDown);



protected override void StopListening(object source)


Button b = source as Button;

if (b != null)


b.PreviewMouseDown -=
new MouseButtonEventHandler(OnPreviewMouseDown);



void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)


DeliverEvent(sender, e);


public static void AddListener(Button source, IWeakEventListener listener)


Manager.ProtectedAddListener(source, listener);


public static void RemoveListener(Button source, IWeakEventListener listener)


Manager.ProtectedRemoveListener(source, listener);


static WeakButtonEventManager Manager




Type t = typeof(WeakButtonEventManager);

WeakButtonEventManager m = WeakEventManager.GetCurrentManager(t) as WeakButtonEventManager;

if (m == null)


m =
new WeakButtonEventManager();

WeakEventManager.SetCurrentManager(t, m);


return m;



}</PRE< P>


Then, create it's weak event implementation


public class ExpensiveButton : DispatcherObject, IWeakEventListener


Button b;

public event MouseButtonEventHandler PreviewMouseDown;

public ExpensiveButton(Button source, bool isReallyExpensive)


b = source;


WeakButtonEventManager.AddListener(b, this);


b.PreviewMouseDown += new MouseButtonEventHandler(OnPreviewMouseDown);




this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate


//Clean up all resources

WeakButtonEventManager.RemoveListener(b, this);

b.PreviewMouseDown -=
new MouseButtonEventHandler(OnPreviewMouseDown);



void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)


if (PreviewMouseDown != null)

PreviewMouseDown(sender, e);


#region IWeakEventListener Members

public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)


if(managerType == typeof(WeakButtonEventManager))


OnPreviewMouseDown(sender, e
as MouseButtonEventArgs);

return true;


return false;



}</PRE< P>


Now, you can easily handle and unhandle this class event, by disposing the event itself, rather then leave it in stack.


ex_button = new ExpensiveButton(butt, true);

ex_button.PreviewMouseDown +=
new MouseButtonEventHandler(EX_HandleMouseDown);


ex_button.PreviewMouseDown -=

new MouseButtonEventHandler(EX_HandleMouseDown)



Happy programming

Source code for this article

Tuesday, July 24, 2007

Vista Battery Saver Beta 2 is available for download

New version of Vista Battery Saver (beta 2) is available for download from CodePlex. Except bug fixes, there is a new feature - automatic power plan change, depends on power source you are working with. I'm really wondering,  why this feature is not available in Windows Vista out-of-the-box? For example, if you are working on battery, you'd want to use Power Saver plan, however, if you are working on AC, you'd rather use Balanced or High Performance. So, Vista Battery Saver does it for you now. All you have to do is to run it and configure plan you want to use on battery and on AC.


In this version, I completely rewrite power aware routines, and now it's using only direct system API call, this way, I get rid over expensive timers. So, download it, use it and notice report all bugs discovered on CodePlex issues tracker and in comments.

Thank you. Remember, It still do not run itself after the installation. You should look into Start->Accessories menu to find and run it.

Download Vista Battery Saver Public Beta 2

Sunday, July 22, 2007

Hack read only properties and fields using reflection

Today I got really confusing question: "Is it possible to change readonly property?". The first question, I asked is: "Why to do it?". The next thought was: "This is dammed interesting, whether is possible". Let's see...

One thing is sure - we can not do it regular way, but we can do it for sure by using reflection. Let's create the class itself

class TestReadOnly  { 

public readonly int ReadOnlyField = 10;

readonly int m_readOnlyProperty = 20;

public int ReadOnlyProperty { get { return m_readOnlyProperty; } } }


Now, let's see what values we have

TestReadOnly tro1 = new TestReadOnly(); 

Console.WriteLine("Field value: {0}, Property value: {1}",tro1.ReadOnlyField, tro1.ReadOnlyProperty);


Well, the results are as expected: 10 and 20. The next step is to change them from external class. Is it possible? Yes, it is. The magic word is "reflection". We'll read the read only field by using reflection

Type t = typeof(TestReadOnly); 

FieldInfo fi = t.GetField("ReadOnlyField");


Now, we'll just set its value.

fi.SetValue(tro1, 50);


Well, well, well. It works. Just works. You can change field value by using reflection, even if the field is read only (actually, it is not a lot of sense to du such thing).

Now, the next step of our challenge. Change the read only property. This might be tricky, 'cos actually, there is no setter at all in IL level. Let's try

PropertyInfo pi = t.GetProperty("ReadOnlyProperty"); 

Object[] arg = new Object[0];

pi.SetValue(tro1, 60, args);


Too bad, we caught ArgumentException. It's clear, 'cos there are actually no code we can execute this way. But, if we'll look into Reflector, we can find the private read only field and set it as we did in our previous example.

PropertyInfo pi = t.GetProperty("ReadOnlyProperty"); 

Object[] arg = new Object[0];

try { pi.SetValue(tro1, 60, args); }

catch (ArgumentException e) {

fi1 = t.GetField("m_readOnlyProperty",

BindingFlags.Instance | BindingFlags.NonPublic);

fi1.SetValue(tro1, 60);



Now it works. Cool, we changed read only property of managed object. And what's about unmanaged code? Let's try to do the same thing with Outlook Appointment.

To access System.__ComObject (the real object in underlying model), we can not use regular GetMember method (due to the fact, that, actually, there are no managed methods there). But, we can invoke methods (note, that property getters and setters are actually methods ued to set values). How to do it? Simple. First of all, let's create boring outlook stuff

Microsoft.Office.Interop.Outlook.Application applicationObject = new Microsoft.Office.Interop.Outlook.ApplicationClass(); 

MAPIFolder calendarFolder = applicationObject.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);

Items appointments = calendarFolder.Items;


Now, let's iterate appointments to get it's underlying objects. For each appointment we'll get read only LastModificationTime property

Microsoft.Office.Interop.Outlook.AppointmentItem appointment = (Microsoft.Office.Interop.Outlook.AppointmentItem)item; 

Console.WriteLine("COM Field: {0}", appointment.LastModificationTime);

//appointment.LastModificationTime is read only


Now, let's invoke it's setter (that, actually does not exists)


BindingFlags.Default | BindingFlags.SetProperty, null,

new object[]

DateTime.Now });


As expected, we got an exception. But this time, it's TargetInvokationException (we invoke it, remember). What to do? Not a lot. Look and seek OLEViewer to figure where set_LastModificationTime occurs and invoke it with new params. I have neither time, nor wish to do it, but you can. See the very beginning of this post. We should figure what actually happens in order to be able to change it. With unmanaged code it's much harder, that with managed. But it's possible.

Have a nice day.

Ah, don't you forgot to release all this stuff?

finally  { 

Console.WriteLine("COM Field: {0}", appointment.LastModificationTime);

//time to cleanup

Marshal.ReleaseComObject(appointment); }

//Just stop it from propagating

break; }

Marshal.ReleaseComObject(item); }





:) Good programming.

The Blue Monster in SAP

Ask Steve Clayton about who is the Blue Monster, that makes me happy. Recently, the new one has been discovered in Orlando as well as in downtown of Seattle and today he's already in SAP offices. Here the photo of the Blue Monster in SAP offices in Ra'anana. It's everywhere.

The Blue Monster in SAP in Tel-Aviv

Map image

Technorati Tags: , , ,

Channel 8 is on the air

We have old good Channel 9, as well we have Channel 10 and it's rather new one. Now we have Channel 8 as well - welcome, and good luck, channel 8 (nice graphite layout)


Saturday, July 21, 2007

Vista Battery Saver goes Open Source

Due to chronic lack of time, I decided to publish full source code of Vista Battery Saver on CodePlex. I believe, that only this way, I can assure this really useful and important software to live. All developers, what to take care together with me on this soft development are welcome to join this project.

Good luck and thank you. Vista Battery Saver @ CodePlex

Friday, July 20, 2007

Filtering hierarchical data and another TreeView bug

Well, well, well. Yet another TreeView bug discovered, while answering another WPF question. But, before it, let's answer it: "How to filter hierarchical data?"

What we have? We have treeview with XML data binded to it.
What we need? To filter it - for example filter out all odd nodes in any level.
How to do? Regular way, by using Predictate generic object.

Let's start. Light, motor, camera, Data

<root> <leaf id="1" name="leaf1"> <group id="1" name="group1"> <item name="item1" id="1"> <subitem id="1">test 1</subitem> <subitem id="5">test 2</subitem> <subitem id="5">test 3</subitem> <subitem id="5">test 4</subitem> <subitem id="5">test 5</subitem> </item> <item name="item2" id="2"> <subitem id="1">test 1</subitem> <subitem id="5">test 2</subitem> <subitem id="5">test 3</subitem> <subitem id="5">test 4</subitem> <subitem id="5">test 5</subitem> </item> 


Data template (hierarchical of cause)

<HierarchicalDataTemplate DataType="leaf" ItemsSource ="{Binding XPath=*}"> <TextBlock Text="{Binding XPath=@name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="group" ItemsSource ="{Binding XPath=*}"> <TextBlock Text="{Binding XPath=@name}" Foreground="Blue" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="item" ItemsSource ="{Binding XPath=*}"> <TextBlock Text="{Binding XPath=@name}" Foreground="Red"/> </HierarchicalDataTemplate> 


Data provider and control to host our data

<XmlDataProvider Source="XMLFile1.xml" x:Key="mydata" XPath="*"/> 

<TreeView Name="myTree" ItemsSource="{Binding Source={StaticResource mydata}, XPath=*}"/>  


Now let's add checkbox to switch filtering on and off

<CheckBox Name="predCheck" Checked="onPredChecked" Unchecked="onPredUnchecked">Filter by predicate object</CheckBox>


And now, take care on those routed events...

void onPredChecked(object sender, RoutedEventArgs e) { ICollectionView view = CollectionViewSource.GetDefaultView(myTree.ItemsSource); view.Filter = new Predicate<object>(FilterOdds); } void onPredUnchecked(object sender, RoutedEventArgs e) { ICollectionView view = CollectionViewSource.GetDefaultView(myTree.ItemsSource); view.Filter = null; } 


How to filter (FilterOdds method)?

bool FilterOdds(object item) { XmlElement elem = item as XmlElement; bool res = false; if (elem != null) { res = int.Parse(elem.SelectSingleNode("@id").InnerText) % 2 == 1; } return res; } 


Now, let's filter each node, while it's expanding.

void onExpanded(object sender, RoutedEventArgs e) { TreeViewItem item = sender as TreeViewItem; if (item != null) { ICollectionView view = CollectionViewSource.GetDefaultView(item.ItemsSource); if (view != null) { if ((bool)predCheck.IsChecked) { view.Filter = new Predicate<object>(FilterOdds); } else  { //Remove comment to stop expanding level 3  //view.Filter = null;  } } } //debug  Console.WriteLine("Item {0} on container {1}", myTree.ItemContainerGenerator.IndexFromContainer(item), ItemsControl.ItemsControlFromItemContainer(item).Name); } 


Cool everything should work, isn't it? Yes, except the weird bug of treeview, that preventing it from expanding 3rd level node, if filter applied. Try to compile and run it. If the check box unchecked (no filtering) we can easily expand each node on every level. See yourself


But if we'll check the checkbox, 3rd level will be inaccessible for us (as well as all deeper levels) See...


If you'll try to expand it, focus will move one level up and node remains collapsed. Pretty bad, huh... Good unbugged programming...

Source code for this article

Wednesday, July 18, 2007

Family Show 2.0

Tim Sneath released new version of Family Show demo application. All those, who were in my presentations, saw this outstanding example of WPF usage for multimedia fun application creation. Now it's not only with full source, but also in CodePlex source control system.

Sunday, July 15, 2007

WorldMate for Nokia 60 is free now

The new version of one of my favorite mobile applications from great developers from Lod is completely free now. Previously this great software was only available for Nokia owners. Now, the new updated version is free for all S60 devices. Download now.


Friday, July 13, 2007

Justifying of Expander's header button

From internal discussion list:

From: MS employee
Subject: Expander arrow button placement


I have an Expander that expands in the Down direction. How do I make the Expander button be justified to the right, rather than the left which is the default?

From: Another helpful MS employee
Subject: RE: Expander arrow button placement

There is no easy way as I know, you have to restyle the Expander to achieve it.

From: Myself
Subject: RE: Expander arrow button placement

The easiest way to achieve the right justification of Expander header is by using following “double – transformation”. Actually, you are flipping the expander and then flipping back it’s header text. You’ll have to flip it’s content as well.

This way is quick and dirty, however the best way to do it is by creating custom template for header.

<Expander RenderTransformOrigin="0.5,0.5">


TextBlock Margin="30,0,30,0" VerticalAlignment="Top" Text="Test">



ScaleTransform ScaleX="-1" ScaleY="1"/>







ScaleTransform ScaleX="-1" ScaleY="1"/>




   Have a nice day.

Tuesday, July 10, 2007

WPF controls library, WPF bloggers give away, Silverlight as Forms examples, Virtualization and WPC

Mike Swanson keeps up-to-day his list of WPF Tools and Controls. Absolutely useful page.

Charles Petzold, the author of great WPF books, asks WPF bloggers to send him their blog and postal address, 'cos he think, that those, who write about this amazing technology might receive a copy of his new book.

There are a couple of outstanding Silverlight examples can be found at NETiKA's website.

Jeff Woolsey, SPM at MS opened new blog about virtualization technologies.

Microsoft announced Next-Generation Business Opportunities for Partners. It's all about Microsoft Dynamics Live CRM. See keynotes at Worldwide Partner Conference site. They speak about Windows Server 2008, Windows Vista SP1, Visual Studio 2008 and SQL Server 2008. Very interesting.

More to come. Stay tuned...

Friday, July 06, 2007

Visual Studio "Orcas" June 2007 CTP is available

After a limited beta Visual Studio 2008 ("Orcas") June CTP VPC is available to wide public. A lot of bugs fixed (thank you all those who tested it), some new features added. Nice work!

Download VS2008 June 2007 CTP VPC

Accessibility lesson (video)

You are not sure about what is accessibility at general. Please see following video to understand.

Thursday, July 05, 2007

Internet Explorer 8 alpha screenshots

Three of IE 8 alpha screenshots leaked to internet in one of those strange forums. Here they come. It's not looks like fake, but who knows...





via Tech Today

Guess the gadget (video)

Well, it was really easy for you to guess the direction of the bus. But what's about it? What is it in following video and what's for it might be used?

Flame (joke)

- I want to buy a XBox for my husband's birthday.
- Do you have a good sex life?
- Yes...
- Don't do it!

What does it mean Certified for Windows Vista? (Video)

Ben Reed from Windows Vista Blog record his presentation where he's explaining what does it mean "Certified for Windows Vista". Great video. See yourself

"Acropolis" July CTP available now

July is the best CTP time ever (a lot of sun in Redmond)

Katy Kam from Acropolis team announced that Acropolis July CTP is release and can be downloaded here

New features:

  • Transition Animation improvements - you can now add transitions when changing page in TabLayoutPanes
  • Better design time support - you can now use Application designer to select themes
  • Better Custom theming support - instead of copy-past some framework code, you can register and override XAML styles
  • A lot of bug fixed (thanks to community)

Great work!

Wednesday, July 04, 2007

Orcas June CTP for limited beta is available

After releasing June CTP of .NET framework 3.5, June CTP bits of Visual Studio 2008 (Team Suite and Visual Web Developer) are also ready for limited beta as Layout or VPC image. If you want to test it, please let me know via comments or by contacting me directly.

Creating, exposing and signing ActiveX control built with C#

Well, this is really old stuff, but since Silverlight got more and more attention, there are a lot of questions about how to make your ActiveX to be exposed by JavaScript and how to deploy such stuff. You ask why? Well, I can not explain you... yet...

Let's start. Create regular dll in VS2005 and create UserControl there. Then expose the interface of the control by creating regular properties, you want to access from outside. (note: I do not like to do it directly updates something, due to security reasons, but for this example it will fine). So you have a public property, but in order to make it visible to COM world, you should create an interface and make your control to inherit from it. This interface will tell COM/COM+ that there are public properties in this AX.

Now we'll have our AX ready and, actually, you can use it already by settings classid attribute of Object in HTML page to something like YouAssemblyName.dll#YourNamespaceInClass.YouControl. You can also generate GUID for it to assure future compatibility. You can set variables and invoke methods of your control by calling TheNameOfObjectInHTML.PropertyOrMEthodExposedByTheInterface . If you want to use GUID as AX identification, just add [Guid("YOUR-GUID-HERE")] attribute above the class definition in code. Well. run it - see nothing? Of cause. You should give your ActiveX Full Trust permissions.

How to do it? Use CasPol.exe utility from SDK. Run CasPol -m -ag 1.2 -hash SHA1 -file MyFile.exe FullTrust. What, actually we have here?

  • -m is modifying machine level policy (this set in some cases to user level)
  • -ag 1.2 is adding a code group under LocalInternet (in default machine policy)
  • -file / -url is membership conditions for new group
  • FullTrust is FullTrust :)

Now you can copy (in some cases merge) your config into web or machine application config. If something goes wrong use CasPol -all -reset to restore all defaults.

Still problems? Sign your assembly. use "signtool signwizard" from VS command prompt to invoke certificate sign dialog. If you have code certificate you paid for to one of well known authority, you'll be able to install your AX with yellow strip only in client's machine from internet zone, if your certificate is personal or not trusted in some cases you'll get red bar, in order cases the installation will be terminated.

If you have more then one assembly, you want to deploy, use CAB tools from VS (Setup and Deployment) and don't forget to create INF file for your cab project. Then in HTML Object use codebase attribute to point to your cab. You can also point it to use specific version by using,b,c,d instead of just cab. It's recommended to delay sign your assemblies to be enable easy updates in the future.

That's all, we done. Have a nice day :)

Tuesday, July 03, 2007

FeedBurner becomes free

FeedBurner is really great free service. It has a lot of cool features and some of them, for example advanced statistics is not free. Google acquired FeedBurner about three months ago and today they make FeedBurner completely free. Now you can use advanced item view, link click-through, enclosure downloads statistics without paying a penny. Just login into your FrreBurner account and check all boxes, marked as "pro". The other new feature provided is FeedBurner MyBrand. This means, that you can control the URL of feeds and point it to your own domain. This is one of those features, that force a lot of bloggers not to use FeedBurner. Now it's absolutely free. Use it. Thank's Google.

BTW, don't you already subscribed to my RSS feed via FeedBurner?

via TechCrunch

Blogging rule #1

About seven years ago, I began to recognize what does is mean "blogging". Then I applied some of rules acquired from my favorite Dale Carnegie's book "How to Win Friends and Influence People" to digital life, especially to blogging and today, I want to begin sharing those rules with you. The trigger for this becomes my thoughts about Blogference... So, let's begin:

Real life: Any fool can criticize, condemn, and complain - and most fools do
Blog life: Replying comments, just keep the dialog running, even if you completely can not agree with the commentator. It's better you to try make the replier to accept your position.

What do you think about it?

Hardware acceleration on layered window on XP and 2003

New hotfix enables HW acceleration on WPF applications running on Windows XP and 2003 via seemar

You can contact your local Microsoft representative to get it

Monday, July 02, 2007

Shame, shame you, Microsoft

I came to the Blogference, for Microsoft (especially for yosit)  only and what I got? Two video recording sessions, two photo shots, one simple pen with old (white) Live logo, one Google t-short and non of Microsoft's... Yossit promised me a t-shirt with my blog address for each tag I put in my blog and funky trousers for each post, everyone got, but me. What's the shame! I told, them, that I do not want to write anymore and 'll going to work for Google, not because I was bribed by them, but because they black t-shorts much more stylish, that whites of Microsoft. The only thing can change my mind is giving me all possible types of MS t-shirts.

The only good thing happened there is a conversation with Om Malik about how to feed money from all my blogs. The answer was, that I cannot, but who cares?


Now if you have read all of this evil stuff, only you love me. Thus, please, tell me what you want to see in this blog (only in case, that MS will give me all things required). What topics are more interesting for you and what are less.Thank you for your participation in my troubles...

Sunday, July 01, 2007

Job issues...

It's really hard to work in technical support. But it's so good to leave under fanfares...

"Alas, poor Yorick! I knew him, Horatio: a fellow
of infinite jest, of most excellent fancy: he hath
borne me on his back a thousand times; and now, how
abhorred in my imagination it is! my gorge rims at