<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>fikrim var netleştirelim &#187; M. Orçun Topdağı</title>
	<atom:link href="http://www.fikrimvar.net/lestirelim/?feed=rss2&#038;author=2" rel="self" type="application/rss+xml" />
	<link>http://www.fikrimvar.net/lestirelim</link>
	<description>idea: artifact of my sagacious serendipity</description>
	<lastBuildDate>Sun, 25 Oct 2009 14:42:23 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A in XAML: Ain&#8217;t for WPF/Silverlight</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=38</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=38#comments</comments>
		<pubDate>Sun, 25 Oct 2009 14:42:23 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=38</guid>
		<description><![CDATA[Even though XAML is officially the acronym of eXtensible Application Markup Language,- a generic term-, you can not usually separate it from UI frameworks, WPF and Silverlight. This creates some confusion, most people think of WPF as the declaration of UI with XML. Not that this is wrong, this explanation does not necessarily suggest decoupling [...]]]></description>
			<content:encoded><![CDATA[<p>Even though XAML is officially the acronym of eXtensible Application Markup Language,- a generic term-, you can not usually separate it from UI frameworks, WPF and Silverlight. This creates some confusion, most people think of WPF as the declaration of UI with XML. Not that this is wrong, this explanation does not necessarily suggest decoupling data, logic and user interaction. XAML only helps WPF to achieve it, there is definitely more in WPF. I admit, XAML originally stood for eXtensible Avalon (code-name for WPF) Markup Language. But hey, there is more in XAML, too.</p>
<p>Since the first day I learned about WPF, I almost never used a UI designer tool. Perhaps, that is why I started using XAML everywhere I could, one could say it was love at first sight. They say love lasts roughly 3 years and even though it has been a little bit longer than that for me, I still feel strong about it. Lucky for me, Microsoft does also. Together with the recent release of VS2010 Beta 2, XAML <a href="http://blogs.windowsclient.net/rob_relyea/archive/2009/10/19/xaml-news-net4-and-vs2010-beta2.aspx">finally has its own assembly</a>, System.Xaml.dll targeting .NET Framework 4 Beta 2. I have now plenty of projects which can loose their dependencies on PresentationCore.dll, PresentationFramework.dll and WindowsBase.dll. I hope to convert them all easily and start making more.</p>
<p>First one to go was my almost forgotten open-source <a href="http://geostructor.googlecode.com">project Geostructor</a>. I was expecting minor problems but I was wrong. I had <strong>none</strong> except the fact that, I had unconsciously created dependencies on WPF assemblies. After moving those dependent codes to where they really belong, I was ready to go with one little replacement. Replaced all class references of XamlReader and XamlWriter with the new XamlServices class. Not only everything worked as expected, some of my problems were gone too. This is what made me to write about the problem.</p>
<p>Back when I first encountered this problem, I was planning to post my solution here. Then, I heard about a new feature in the upcoming System.Xaml.dll and thought I should wait for it. In other words, I was lazy. So here it goes:</p>
<h5>Old Problem</h5>
<p>Here is a sample file saved by Geostructor v0.3, which targets .NET Framework 3.5 SP1:</p>
<pre>
<pre name="code" class="xml">

&lt;GObjectCollection xmlns=&quot;http://www.fikrimvar.net/lestirelim/?cat=10&quot;&gt;
  &lt;FreePoint Position=&quot;0,0&quot; Name=&quot;A&quot; /&gt;
  &lt;RelativePoint RelatedPoint=&quot;A&quot; Offset=&quot;20,10&quot; Name=&quot;B&quot; /&gt;
  &lt;RelativePoint RelatedPoint=&quot;B&quot; Offset=&quot;10,20&quot; Name=&quot;C&quot; /&gt;
&lt;/GObjectCollection&gt;
</pre>
</pre>
<p>Here, <em>RelatedPoint</em> property of <em>RelativePoint</em> is of type <em>IGPoint</em> which inherits <em>INotifyPropertyChanged</em> interface. <em>RelatedPoint</em> objects listen to the <em>PropertyChanged</em> events of the referenced objects. In order to keep these references after saving and loading back, I had to prevent XamlWriter from producing such result:</p>
<pre>
<pre name="code" class="xml">

&lt;GObjectCollection xmlns=&quot;http://www.fikrimvar.net/lestirelim/?cat=10&quot;&gt;
  &lt;FreePoint Position=&quot;0,0&quot; Name=&quot;A&quot; /&gt;
  &lt;RelativePoint Offset=&quot;20,10&quot; Name=&quot;B&quot;&gt;
    &lt;/RelativePoint.RelatedPoint&gt;
      &lt;FreePoint Position=&quot;0,0&quot; Name=&quot;A&quot; /&gt;
    &lt;/RelativePoint.RelatedPoint&gt;
  &lt;/RelativePoint&gt;
  ...
&lt;/GObjectCollection&gt;
</pre>
</pre>
<h5>Old Solution</h5>
<p><span id="more-38"></span><br />
First, I tried to extend the XamlReader and XamlWriter by providing custom services. However, I remember I was blocked by various finalized classes. The solution I came up with was to mark reference properties with attributes, converting these references to unique strings (by taking their <em>Name</em> property). Later, during XamlReader, again I had to convert these string values into place-holder objects. Remember, converters had no way of knowing the current context. When XamlReader is done and I have the collection, I had to go through the elements and replace the place-holders:</p>
<pre>
<pre name="code" class="c#">

foreach (var item in loaded)
{
    GObjectFactory.RecordName(item, item.Name);
    var refs = (from prop in item.GetType().GetProperties()
                let value = prop.GetValue(item, null) as PlaceHolder
                where value != null
                select new
                {
                    Name = value.ElementName,
                    Setter = new Action&lt;object&gt;(v =&gt;
                    {
                        prop.GetSetMethod().Invoke(item, new object[] { v });
                    })
                });
    foreach (var ph in refs)
    {
        ph.Setter(loaded.Where(o =&gt; ph.Name.Equals(o.Name)).First());
    }
    this.Graph.Add(item);
}
</pre>
</pre>
<h5>No Problem</h5>
<p>Here is the new saved file in Geostructor v0.4, which targets .NET Framework 4.0:</p>
<pre>
<pre name="code" class="xml">

&lt;GObjectCollection xmlns=&quot;http://www.fikrimvar.net/lestirelim/?cat=10&quot;
                   xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt;
  &lt;FreePoint Name=&quot;A&quot; Position=&quot;0,0&quot; /&gt;
  &lt;RelativePoint RelatedPoint=&quot;{x:Reference A}&quot; Name=&quot;B&quot; Offset=&quot;20,10&quot; /&gt;
  &lt;RelativePoint RelatedPoint=&quot;{x:Reference B}&quot; Name=&quot;C&quot; Offset=&quot;10,20&quot; /&gt;
&lt;/GObjectCollection&gt;
</pre>
</pre>
<p>In order to achieve this, you have to do nothing, thanks to <a href="http://msdn.microsoft.com/en-us/library/system.windows.markup.reference_members(VS.100).aspx">Reference Markup Extension</a> which actually utilize the <a href="http://msdn.microsoft.com/en-us/library/system.xaml.ixamlnameresolver(VS.100).aspx">IXamlNameResolver Interface</a>. It has been a long wait since <a href="http://windowsclient.net/blogs/rob_relyea/archive/2009/05/28/referencing-a-named-object-in-xaml2009.aspx"> Rob announced this feature</a>. Not that I am complaining, now I have to go through the code and remove the unnecessary attributes and converters. Also I should probably investigate possible usage of this new service in <a href="http://www.codeplex.com/wpfix">WPFix library</a>.</p>
<p>Hopefully, I will keep on posting more about what I have to remove from my code instead of adding. BTW, to most, this is probably one of the least awaited feature in VS2010, and they are right. Go check out the Beta 2, it is much better than Beta 1.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=38</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Expander inside ScrollViewers, a.k.a. when WPF power is out of control</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=35</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=35#comments</comments>
		<pubDate>Sat, 03 Jan 2009 11:11:06 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=35</guid>
		<description><![CDATA[Yesterday, I spent almost an hour on a small but annoying problem. I was working on a visual editor for an IDE, I develop for internal-use. Have I mentioned before that I started working (for more than  a couple of months now) in a company again? Clearly, I haven&#8217;t been blogging actively passed year. [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday, I spent almost an hour on a small but annoying problem. I was working on a visual editor for an IDE, I develop for internal-use. Have I mentioned before that I started working (for more than  a couple of months now) in a company again? Clearly, I haven&#8217;t been blogging actively passed year. Let&#8217;s see whether I will be able to change this in 2009 or not.<br />
Anyway, this visual editor is for a DSL, or should I say a XAML grammar? It was the perfect opportunity to show the power of WPF. However;<br />
<div id="attachment_36" class="wp-caption alignnone" style="width: 420px"><a href="http://www.pirelli.com/web/media/photogallery/default.page"><img src="http://www.fikrimvar.net/lestirelim/wp-content/uploads/smalladvcarllewis.jpg" alt="Power is nothing without control" title="Click to see the original at Pirelli Photo Gallery" width="410" height="331" class="size-full wp-image-36" /></a><p class="wp-caption-text">Power is nothing without control</p></div></p>
<h5>Problem:</h5>
<p>Visual editor&#8217;s job is to display the workflow in a tree view fashion. I chose displaying listboxes inside listboxes instead of a treeview. Each last node has an expander inside the listboxitem container. When user expands an item, containing listbox grows to display all of the items. I have no problem with that, in fact, that is exactly what I am grateful for. There is one catch, though. Expander controls not only expand but also shrink. When it does, listbox sits back and enjoys the void. A small sample to play with:</p>
<pre name="code" class="xml">

  &lt;StackPanel&gt;
    &lt;ListBox x:Name=&#039;xNoFlower&#039;
             Background=&#039;Fuchsia&#039;
             ScrollViewer.CanContentScroll=&#039;{Binding ElementName=xAgreed, Path=IsChecked}&#039;&gt;
      &lt;ListBoxItem Background=&#039;White&#039;&gt;
        &lt;Expander Header=&#039;Click me&#039;&gt;
          Again please
        &lt;/Expander&gt;
      &lt;/ListBoxItem&gt;
    &lt;/ListBox&gt;
    &lt;TextBlock Text=&#039;Check if you object&#039; /&gt;
    &lt;CheckBox x:Name=&#039;xAgreed&#039; IsChecked=&#039;True&#039;&gt;
      On a flower, every color is nice.
    &lt;/CheckBox&gt;
  &lt;/StackPanel&gt;
</pre>
<h5>Solution:</h5>
<p>You probably did know this. I did also, however when things are under multiple levels of ControlTemplates, DataTemplates and Styles, I was reluctant to go deep and investigate. Actually, I was reluctant to do anything at all. I had a great new years eve party and a greater headache. Luckily, WPF also provides an easy solution. Although, I spent a lot time to guess the problem.</p>
<pre name="code" class="xml">

    &lt;Style TargetType=&#039;{x:Type ListBox}&#039;&gt;
      &lt;Setter Property=&#039;ScrollViewer.CanContentScroll&#039;
              Value=&#039;False&#039; /&gt;
    &lt;/Style&gt;
</pre>
<p>Am I wrong to think that this was the default behavior when a control with a scrollviewer is not bounded? If I am, I can easily blame it on countless shots or hitting the floor so many times. Who else did work Friday, just to see &#8220;s?he&#8221; could not?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=35</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Riatalks, Snooker and Joker</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=30</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=30#comments</comments>
		<pubDate>Mon, 11 Aug 2008 12:29:30 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=30</guid>
		<description><![CDATA[I usually have a problem giving breaks. My body stopped sending signals to my brain long time ago, due to not getting back any. However I realized that I have limits too.
I was at the riatalks, a two day event at two separate conference halls. I worked out a plan and was going to be [...]]]></description>
			<content:encoded><![CDATA[<p>I usually have a problem giving breaks. My body stopped sending signals to my brain long time ago, due to not getting back any. However I realized that I have limits too.</p>
<p>I was at the <a href="http://www.riatalks.com">riatalks</a>, a two day event at two separate conference halls. I worked out a plan and was going to be able to attend all talks that interested me. However, I forgot one small thing, timing is not an <a href="http://en.wikipedia.org/wiki/Additive_function">additive function</a> around <a href="http://en.wikipedia.org/wiki/Istanbul">here</a>. At the first day, even though some presenters couldn&#8217;t make it, talks was not over when I had to leave.</p>
<p>At that time, my body had a few reservations already. Some of you might know, <a href="http://en.wikipedia.org/wiki/Snooker">snooker </a> is a demanding game, physically and mentally. So I had to shutdown the message queue completely. In contrast, I had my personal best after 5 hours and just before my last sip at 2 A.M. Snooker is sometimes called <em>chess with balls</em>, however chess is a rather simple game. Snooker is pretty much <em><a href="http://en.wikipedia.org/wiki/Go_(board_game)">Go</a> with sticks</em> to me.</p>
<p>Second day things got worse, time wise. I kept running between the halls, to see if any starts on time. Still I had the chance to chat with yesterdays last presenter, <a href="http://daron.yondem.com">Daron Yondem</a>. Daron and <a href="http://ferruh.mavituna.com/">Ferruh Mavituna (in Turkish)</a> had the best presentation skills at the talks. I am certainly not an authority but I can at least suggest everyone to read <a href="http://www.hanselman.com/blog/11TopTipsForASuccessfulTechnicalPresentation.aspx">scott&#8217;s tips</a>. Needless to say, I had to leave early for another round of snooker.</p>
<p>I closed the weekend with another physical challenge. We went to <a href="http://www.imdb.com/title/tt0468569/">&#8220;The Dark Knight&#8221;</a> at an IMAX theater, together with my snooker body. I heard the most stupid excuse to not giving a break, &#8220;&#8230; since this is an IMAX &#8230;&#8221;. Rest should be &#8221; and as technology advance, we go backwards &#8230;&#8221;.  I know intermissions are not common in most of the countries, but this movie&#8217;s length is not common either. I was cool with it but I saw people suffer.</p>
<p>Everyone suggests watching the movie in an IMAX theater however even 4K resolution is not enough at a big enough screen. Simple division that is, however if you had seen the movie, you might wanna <a href="http://weblog.fortnow.com/2008/07/movie-time.html">check out how</a> other math guys watched it, beware of the spoilers.</p>
<p>Today, I can tell by the mirror that breaks are necessary, so here is one.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=30</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Thinking in or out of programming languages</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=27</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=27#comments</comments>
		<pubDate>Wed, 30 Apr 2008 20:45:35 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=27</guid>
		<description><![CDATA[I remember the first time I took a look at C#. As a C++ programmer, I was impressed not by the language but by the IDE. I could do without multiple inheritance, but there were no templates either; case was closed, for good, I thought. Fortunately, many did not close the case. It did not [...]]]></description>
			<content:encoded><![CDATA[<p>I remember the first time I took a look at C#. As a C++ programmer, I was impressed not by the language but by the IDE. I could do without multiple inheritance, but there were no templates either; case was closed, for good, I thought. Fortunately, many did not close the case. It did not took long for Microsoft to release C# 2.0; however, to me, damage was done. I am not talking about the huge .NET libraries, for which generics could help a lot. Real victims were the developers; there are still programs being written <em>as if</em> in C# 1.0. I don&#8217;t want to go into details of this matter right now. If you want to discuss, please don&#8217;t hesitate to comment.</p>
<p>Anyway, I started to use C# and I was happy until 3.0. Wait, wait, I know what is going to happen if I don&#8217;t make myself clear. C# is my language of choice when I need UI; but, you can never stop programming in C++. If I happen to use both of them for a project, I constantly switch between C++, C++\CLI and C#. This is where the trouble begins. Before C# 3.0, I could say that my productivity was pretty much the same in each one of them. After 3.0, I caught myself trying to accomplish everything in C# as much as I could. Easiest way is not always the right way. Again, I have got to skip this if I want to finish this post. The point is, I use C# more and more everyday.</p>
<p>I have always had complaints about C# but a few days ago, I realized that some differences in programming languages are harder to overcome than I thought. I usually make a mistake, caused by experiences in another language, once or twice. What I have found out is that, if I can&#8217;t rationalize the difference, I make it all the time.</p>
<p>Suppose you wrote an interface which has a property with no setter. You also wrote lots of classes, implementing this interface. As long as these classes implement a public getter for the property, there is no problem, right? One day, you realize that number of these classes will increase and all will benefit from an abstract base class. (As a side note; there are no distinctions as interfaces or abstract classes in C++. There are classes without any implementation and partially implemented classes which could stand as counter-parts respectively. So, the following problems have no counter-part in C++) First of all, your new base class must declare (copy) all members of the interface as abstract members if there is no implementation. Is this really necessary? Secondly, you have to mark all of your previous implementations with override. I hear you saying, I can do all of these with a couple keyboard shortcuts, thanks to my refactoring tool. Last but not least, you can <em>not</em> do this all the time without changing your design of previously written classes. That&#8217;s right! Suppose one of your implementations also provide a public setter for our non-problematic-looking property, and another one with a private setter. Can you tell the problem?</p>
<p>Do you think in or out of your language?</p>
<p>P.S. This post is a side product of a project, I promised earlier, <a href="http://geostructor.googlecode.com">GeoStructor</a>. Its code does not contain a solution to the problem above, so has lots of repetition. Actually, code requires lots of changes. When that happens, I will probably write another WPF related article which will include some techniques (regarding XamlReader/XamlWriter, Dragging, etc.) I used.</p>
<p><ins datetime="2008-05-01T15:43:06+00:00"><br />
P.P.S. Initially, I tried to explain a problem without codes in order to provoke thinking. However, discussions will be healthier with a sample. Please expand to see the code. Sorry about the naming.<br />
</ins></p>
<pre name="code" class="csharp:collapse">

namespace abstractobstruction

{

interface IInterface

{

int GetMe { get; }

}

class Class1 : IInterface

{

public int GetMe

{

get;

private set;

}

}

class Class2 : IInterface

{

public int GetMe

{

get;

set;

}

}

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=27</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How many blograms of inventure have I got?</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=26</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=26#comments</comments>
		<pubDate>Thu, 20 Mar 2008 22:01:21 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=26</guid>
		<description><![CDATA[It has been a while since my last post.  I am not sure why.  My intention was to keep it rolling at least once a week.  It was not a bad start either.  I guess, I thought that a series of articles would help me focus.  Since  articles were [...]]]></description>
			<content:encoded><![CDATA[<p>It has been a while since my last post.  I am not sure why.  My intention was to keep it rolling at least once a week.  It was not a bad start either.  I guess, I thought that a series of articles would help me focus.  Since  articles were technical,  I gained a bit of  recognition. So, why not continue? I was really busy at work, but knowing that is never an excuse for me, I kept looking.</p>
<p>Now, I realize that I felt obliged to keep the style.  I didn&#8217;t want to steal readers&#8217;  time with my personal ramblings.   Each time I started writing a new post, I found a different reason not to.  Sometimes, I wasn&#8217;t happy with the quality.  Some were a lot more time consuming than it should be, especially C++ ones.  I wanted to write articles which were original if not extra-ordinary.  Well, I couldn&#8217;t be more wrong. I have got to make mistakes and make them soon. Not only that, I know why I want to make mistakes. Here is the story.</p>
<p>Last month, I made a few important decisions about my life. Maybe the most important of all was to quit my job. It was a sudden decision. After a couple of though weeks, I managed to clean up my ongoing tasks and proved my sketches to my ex-co-workers.  I had no plans, whatsoever.  Initial reactions were like &#8220;- Where is your new workplace ? &#8212; There isn&#8217;t any &#8220;. Only a few close friends did not act as if I had lost my mind. Without a regret, I gave myself a few weeks of rest. A sabbatical year is not common among programmers, I suppose. I don&#8217;t want to be an exception either. Still, I couldn&#8217;t decide what to do. I&#8217;ve had times, considering opportunities abroad. Although, most suitable jobs for me are located in the States, family stuff keeps me in İstanbul. To keep a long story short, I want to target software developers and the reason of this alone requires a new post.</p>
<p>Yesterday, when I started my computer, I had over 500 unread  posts on my reader.  I read reluctantly until <a href="http://www.codinghorror.com/blog/archives/001074.html" target="_blank">an inspiring post</a> by <a href="http://www.codinghorror.com/blog/" target="_blank">Jeff Atwood</a>.  In my case, I feel like closing without a bookmark and going to open a random page. I want to keep reading this programming book and wish, I could read it all. It&#8217;s just that, I suspect a lifetime is not enough. There were still over 500 posts, waiting for me to read, but I decided to add one for you. For now, it looks like my <em>adventures</em> on <em>inventing</em> new ways to program will continue on this <em>blog</em>. I can wait a couple of more years. In the mean time, I hope this blog will gain <em>weight</em> and help me along. By the way, for a retirement plan, I imagine myself as a <a href="http://en.citizendium.org/wiki/Benevolent_Dictator_for_Life" target="_blank">benevolent dictator</a> of a new programming language ( a country would  also do ) and bashing the young guys, who never stops coming with all kinds of strange ideas!</p>
<p>P.S. If you were expecting a WPF related article, soon I will write another post about an open source project of mine.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=26</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>WPFix Part 3 (Extension Methods)</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=23</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=23#comments</comments>
		<pubDate>Sun, 25 Nov 2007 17:03:40 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=23</guid>
		<description><![CDATA[One of the new features, a.k.a. syntactic sugars, in C# 3.0 is extension methods.  At first, it looks like compiler magic and it is no big deal.  But isn&#8217;t it the same about class method?  When a function argument is hidden, suddenly whole world changes.  Clearly, OOP is not just a [...]]]></description>
			<content:encoded><![CDATA[<p>One of the new features, a.k.a. syntactic sugars, in C# 3.0 is extension methods.  At first, it looks like compiler magic and it is no big deal.  But isn&#8217;t it the same about class method?  When a function argument is hidden, suddenly whole world changes.  Clearly, OOP is not just a hidden this pointer, but we can think of extension methods as class methods that will only access the public fields.  This may look like a step backwards but we are not living in an ideal world, in fact not even close to ideal.  This is more like a side-step that will provide new ways forward.  One of these new ways is LINQ, language integrated query.  However, it is hard to come up with another as useful as LINQ.  Is there a way to utilize extension methods in WPF as we did lambda expressions?</p>
<p>While <a href="http://www.fikrimvar.net/lestirelim/?p=15">introducing the lambda converters</a>, I said that implementing IValueConverter or IMultiValueConverter is not a complete waste of time.  There were two reasons behind this statement and hence two problems ahead of lambda converter with dreams of being the ultimate binding converter.</p>
<h5>Problem 1</h5>
<p>One of them was  code maintainability in large projects, where a converter can be used more than once.  Typing the same expression again and again is not an option.</p>
<h5>Solution 1</h5>
<p>Idea occurred to me, while reading <a href="http://kentb.blogspot.com/">Kent Bogaart</a>&#8217;s article on <a href="http://www.codeproject.com/WPF/WPF_Converters.asp">WPF converters</a> and <a href="http://joshsmithonwpf.wordpress.com/">Josh Smith</a>&#8217;s article on <a href="http://www.codeproject.com/WPF/PipingValueConverters_WPF.asp">piping value converters</a>.  They have both suggested a way to reuse and combine converters.  Then, I had one of those, wait a minute, moments.  This is where extension methods kick in.  We could write our Convert method in an extension method and use them inside the expressions.  Not only, maintaining these converters will be easier, but also they will be combinable by nature.</p>
<pre>
<pre name="code" class="xml">

&lt;TextBlock Text=&#039;{Binding Source={x:Static s:DateTime.Now},
	Converter={fix:Lambda &quot;dt=&gt;dt.ToOurFormat().ToUpper().InsideParenthesis()&quot;}}&#039;/&gt;
</pre>
</pre>
<p><span id="more-23"></span><br />
Again, we had to make a few changes to the Dynamic Expression API.  Looking for extension methods will be a last resort in a function call.  We have the type of the instance, but unfortunately extension methods won&#8217;t show up in the type&#8217;s methods.  These methods are defined in a seperate <em>static class</em>, but they are instance methods.  Is there a contradiction here?  No, static keyword&#8217;s original meaning is that the following function&#8217;s address will be constant.  It does not mean that function belongs to a class rather than an instance.  Here, static denotes that all elements inside the class will be static methods.  Extension method calls does not provide the these extension types, so we have to find out all of the static classes before making a decision.</p>
<p>You can skip this paragraph if you are not interested in the details.  If you take a look at these classes by reflection, you will notice that they are nothing but abstract sealed classes.  At the first call to our new <em>GetExtensionMethod</em> method, we will query these kind of types and put their suitable public static methods in to a lookup table.  These methods must have a return value and at least one parameter. If two extension methods with same name and suitable parameters are ambiguous according to the current implementation.  Implementation is not hard but I had to take a look into the standards.  Please, feel free to ask for an implementation if you ever need one, or better you could provide your suggestion if you are not lazy as I am right now.  Thanks to LINQ, this addition took less than half an hour.  I am thinking of a series dedicated to LINQ.  Again, I surrounded the necessary changes to dynamic.cs by WPFix regions.</p>
<h5>Problem 2</h5>
<p>The other one was the ConvertBack method, which had no counter-part in a lambda converter.  Now that lambda converters are suitable for multiple uses, the need for a backward conversion is higher.</p>
<h5>Solution 2</h5>
<p>We will simply provide a second expression as a parameter to our markup extension class, LambdaExtension.  I was going to simply use another constructor with two parameters, but I guess things are different now that the VS 2008 is released.  We have to use the name/value syntax to support backward conversion.</p>
<pre>
<pre name="code" class="xml">

&lt;TextBox Text=&#039;{Binding ElementName=panel, Path=Background,
		UpdateSourceTrigger=PropertyChanged,
		Converter={fix:Lambda
			Forward=&quot;c=&gt;c.ToColor().ToFriendlyName()&quot;,
			Backward=&quot;t=&gt;t.ToColor().ToBrush()&quot;}}&#039;/&gt;
</pre>
</pre>
<p>I&#8217;m still not sure about multibinding and backward conversion.  I did write the required changes, however I didn&#8217;t even test it once.  I will if I have such a need.  Can you point out such a case?</p>
<h5>Conclusion</h5>
<p>Although it is not production quality code, you can download <a href="http://www.fikrimvar.net/lestirelim/wp-content/uploads/2007/11/wpfix3.zip" title="WPFix3 Solution">WPFix3 Solution</a> (VS 2008) and take a look.  Don&#8217;t you wish your RTM had something like hot this?  Now, if only intelli-sense was extensible enough.</p>
<p>With this post, I am putting a break on WPFix series.  In the future, I will continue the series, with hopefully something different than binding and converting.  Until then, I will continue updating codes according to your feed-backs.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=23</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>WPFix Part 2 (Binding Extension)</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=18</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=18#comments</comments>
		<pubDate>Tue, 20 Nov 2007 22:36:40 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=18</guid>
		<description><![CDATA[This time, I will skip the introduction and jump right into technical stuff.
In the previous post, I tried to reduce XAML&#8217;s dependency to code files for even the simplest operations.  There were a lot of ways other than my lambda converter.  We could write a custom binding which could save a lot more [...]]]></description>
			<content:encoded><![CDATA[<p>This time, I will skip the introduction and jump right into technical stuff.</p>
<p>In the previous post, I tried to reduce XAML&#8217;s dependency to code files for even the simplest operations.  There were a lot of ways other than my lambda converter.  We could write a custom binding which could save a lot more of typing.  However, my intention is not to type less, but to keep relevant parts together.  Still typing less does not hurt, as long as it is clear.  We will come back to this, but before that &#8230;</p>
<h5>Problem 1</h5>
<p>Suppose we have an adjustable background color. Don&#8217;t worry, I am not going to write another custom color picker for WPF. I will try to use the lambda converter.</p>
<pre>
<pre name="code" class="xml">

&lt;StackPanel&gt;
	&lt;Slider x:Name=&quot;Red&quot; Value=&quot;255&quot;  Minimum=&quot;0&quot; Maximum=&quot;255&quot;/&gt;
	&lt;Slider x:Name=&quot;Green&quot; Value=&quot;255&quot; Minimum=&quot;0&quot; Maximum=&quot;255&quot;/&gt;
	&lt;Slider x:Name=&quot;Blue&quot; Value=&quot;255&quot; Minimum=&quot;0&quot; Maximum=&quot;255&quot;/&gt;
	&lt;StackPanel.Background&gt;
		&lt;MultiBinding Converter=&#039;{fix:Lambda
			&quot;r,g,b=&gt;SolidColorBrush(Color.FromScRgb(1,r/255,g/255,b/255))&quot;}&#039;&gt;
			&lt;Binding ElementName=&quot;Red&quot; Path=&quot;Value&quot;/&gt;
			&lt;Binding ElementName=&quot;Green&quot; Path=&quot;Value&quot;/&gt;
			&lt;Binding ElementName=&quot;Blue&quot; Path=&quot;Value&quot;/&gt;
		&lt;/MultiBinding&gt;
	&lt;/StackPanel.Background&gt;
&lt;/StackPanel&gt;
</pre>
</pre>
<p>Parsing this lambda expression looks a bit harder.  Multiple parameters are not a problem but SolidColorBrush and Color classes are.</p>
<h5>Solution 1</h5>
<p><span id="more-18"></span><br />
Without any modification, Dynamic Expression API will throw an exception in this case.  Luckily it is possible to construct predefined System types ( such as DateTime) with the API, and we already have a way to convert strings to types. IXamlTypeResolver is one of the two services provided by WPF at the ProvideValue method of any Markup Extension. All I had to do was to use this service and act as a last resort to the parser.  You will be able to find the required changes to dynamic.cs at the new zipped solution.  I surrounded the changes with regions named WPFix.</p>
<p>Now, the above code is working smoothly.  If you had the opportunity to look into the dynamic.cs, you know that there are a lot ways to improve it.  First thing that pops up is that the above expression is not even a valid lambda expression.  There should be a new keyword before SolidColorBrush, but such conformance required more changes and does not bother me at all.</p>
<h5>Problem 2</h5>
<p>The amount of typing increased by a considerable margin (let me repeat that my intention is not to type less). This increase does not come along with clarity, also.  In fact, we now have to keep bindings and parameters ordered.</p>
<h5>Solution 2</h5>
<p>Lets also provide an alternative to MultiBinding class which does not have a corresponding Markup Extension.</p>
<pre>
<pre name="code" class="xml">

...
&lt;TextBlock Text=&#039;Negative&#039; Foreground=&#039;{fix:Binding
	r={fix:Element Red.Value}, g={fix:Element Green.Value}, b={fix:Element Blue.Value},
	Expression=&quot;SolidColorBrush(Color.FromScRgb(1,1-r/255,1-g/255,1-b/255))&quot;}&#039;/&gt;
</pre>
</pre>
<p>There are a few points to remark in the above code.  The least interesting part is the Element Markup Extension.  Please note that, this is not a complete alternative to a normal Binding with an ElementName.  Path property of a Binding is not a simple string, and the code below does not treat it the way it should.  Code speaks better sometimes.</p>
<pre>
<pre name="code" class="c#">

public class ElementExtension : MarkupExtension
{
	public ElementExtension(string nameAndSimplePath)
        {
		this.Binding = new Binding();
		int pi = nameAndSimplePath.IndexOf(&#039;.&#039;);
		this.Binding.ElementName = nameAndSimplePath.Substring(0, pi);
		this.Binding.Path = new System.Windows.PropertyPath(
			nameAndSimplePath.Substring(pi + 1, nameAndSimplePath.Length - pi - 1));
	}

	public override object ProvideValue(IServiceProvider serviceProvider)
	{
		return this.Binding.ProvideValue(serviceProvider);
	}

	private Binding Binding;
}
</pre>
</pre>
<p>Notice that I do not expect a IMultiValueConverter as a converter.  The rationale is that, specified bindings are associated with parameter names and they belong to a lambda expression.</p>
<p>What gives us the ability to set r, g and b as properties, is that they really are properties of BindingExtension! Eventually, so are the other characters in the alphabet.  Even the possibility of this idea was intriguing at first, but when I think about it, it looks like a natural way.  We just want to associate a binding with a short literal that we can use in an expression, possibly many times.</p>
<p>Suggestions are welcome.  Tell me what do you think about this approach?<br />
<a href="http://www.fikrimvar.net/lestirelim/wp-content/uploads/2007/11/wpfix2.zip" class="zip" title="WPFix2 Solution">WPFix2 Solution</a> (VS2008 Beta 2)<br />
<ins datetime="2007-11-23T06:49:40+00:00">Solution file is updated, thanks to the feed-back. I have to admit, I am surprised by the interest shown, at the very beginning at least .</ins></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=18</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WPFix Part 1 (Lambda Converter Extension)</title>
		<link>http://www.fikrimvar.net/lestirelim/?p=15</link>
		<comments>http://www.fikrimvar.net/lestirelim/?p=15#comments</comments>
		<pubDate>Sun, 11 Nov 2007 13:51:02 +0000</pubDate>
		<dc:creator>M. Orçun Topdağı</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.fikrimvar.net/lestirelim/?p=15</guid>
		<description><![CDATA[As a mathematician, I always had a fondness for languages. As a programmer, this fondness became a devotion. Some might think that language is just a part of implementation which follows analysis and modeling. I agree that implementation is the least important one. I agree that it is like a tool for implementation, you can [...]]]></description>
			<content:encoded><![CDATA[<p>As a mathematician, I always had a fondness for languages. As a programmer, this fondness became a devotion. Some might think that language is just a part of implementation which follows analysis and modeling. I agree that implementation is the least important one. I agree that it is like a tool for implementation, you can choose one or the other. I agree that a separate article, -which does not contain WPF in its header-, is more appropriate for this kind of topic. However, I also believe that programming languages have a much broader effect which includes modeling and even   analysis. Our process of thinking is effected by our ways of communication.</p>
<p><del datetime="2007-11-19T20:28:18+00:00">Eventually, I will connect this to WPF, somehow in the future.</del> <ins datetime="2007-11-19T22:21:55+00:00">In the last few years, I suppose the number of new programming languages has an exponential growth if we also include the new versions.  Some believe that domain specific languages will reproduce asexually, some believe that languages converge to one as they copy their best parts.  Even if there is a convergence,  there is long way on which we speed up.  My guess is that the hypothetical unified programming language, which will be the base of many domain specific languages and will act as a connection between them, will be the way to go.  While waiting, I suggest we learn a few of these doomed languages.  I hope, we will together witness how less these paths are traveled.  I promise that following this post, my technical and theoretical musings will also travel separately. But now, lets start by a few technical ones.  C# 3.0 and XAML are two new languages in two different paths.  Lets get them together!</ins></p>
<p>I always try to defend WPF in discussions with my colleagues. However, I will try to criticize WPF in this series of articles, namely WPFix. Visual Studio 2008 is to be released by the end of this month but I think, WPF and XAML still have a long way to go. Don&#8217;t get me wrong, I am just as glad as you are. I only wish, there was a better way than lengthening the evaluation period to spread the ideas. I will try to keep my critiques precise and search for practical solutions. Hopefully, I will also provide introductory links.</p>
<h5>Problem</h5>
<p>Data binding is pretty much the heart of WPF. We can think of WPF as a pretty complicated converter which consists of little converters for simple data types. However, these converters in the XAML may appear smaller than they are.</p>
<pre>
<pre name="code" class="xml">

&lt;!-- *.xaml--&gt;
&lt;l:ShortTimeConverter x:Key=&quot;ShortTimeConverter&quot;/&gt;
...
&lt;TextBlock Text=&#039;{Binding Source={x:Static s:DateTime.Now},
	Converter={StaticResource ShortTimeConverter}}&#039;/&gt;
</pre>
</pre>
<pre>
<pre name="code" class="c#">

// *.xaml.cs
public class ShortTimeConverter : IValueConverter
{
	public object Convert(object value, Type targetType,
		object parameter, CultureInfo culture)
	{
		DateTime dt = (DateTime)value;
		return dt.ToShortTimeString();
	}

	public object ConvertBack(object value, Type targetType,
		object parameter, CultureInfo culture)
	{
		throw new NotImplementedException();
	}
}
</pre>
</pre>
<p>This may not be a complete waste of time from code maintenance perspective. But we, mortals, sometimes need a more practical method.</p>
<h5>Solution</h5>
<p>A similar problem in C# has been resolved lately by lambdas. You are no longer have to declare your method which won&#8217;t be used anywhere else. Here comes another future article name to my mind, maintenance is overrated. Personal Note: Use more controversial article names than WPFix Part 1. Back to our problem, we need a way to express ourselves in XAML. By express, I mean code. Hence lambda expressions.<br />
<span id="more-15"></span></p>
<pre>
<pre name="code" class="xml">

&lt;TextBlock Text=&#039;{Binding Source={x:Static s:DateTime.Now},
	Converter={fix:Lambda &quot;dt=&gt;dt.ToShortTimeString()&quot;}}&#039;&gt;
</pre>
</pre>
<p>Is this too much to ask?  Well, this article already took more time than to make the above code work.  All I had to do was to put together some existing parts.  First of all, we need a markup extension that will construct the converter.</p>
<pre>
<pre name="code" class="c#">

public class LambdaExtension : MarkupExtension
{
	public string Code { get; private set; }

	public LambdaExtension(string _code)
	{
		this.Code = _code;
	}

	public override object ProvideValue(IServiceProvider isp)
	{
		IProvideValueTarget tp = isp.GetService(
			typeof(IProvideValueTarget)) as IProvideValueTarget;
		if (tp.TargetObject is Binding)
			return new SingleConverter(this.Code);
		if (tp.TargetObject is MultiBindingExtension)
			return new MultiConverter(this.Code);
		return null;
	}
}
</pre>
</pre>
<p>Now, we have a string to parse.  Don&#8217;t worry, we also have a parser, provided by microsoft.  I guess, WPF team and LINQ team do not see each other very much. Take a look at the Dynamic Expression API, which can be found under the samples directory of your VS2008 Beta2 installation.  You can also download these samples from <a href="http://msdn2.microsoft.com/en-us/bb330936.aspx">this msdn page</a> by following the LINQ samples link.  The treasure is inside <em>dynamic.cs</em> source file which also has a nice documentation.  <ins datetime="2007-11-19T20:28:18+00:00">Serendipity never leaves me alone.</ins></p>
<pre>
<pre name="code" class="c#">

class SingleConverter : IValueConverter
{
	public Delegate Operation { get; private set; }
	public string Code { get; private set; }

	public SingleConverter(string _code)
	{
		this.Code = _code;
	}

	public object Convert(object value, Type targetType,
		object parameter, System.Globalization.CultureInfo culture)
	{
		if (this.Operation == null)
		{
			ConstructOperation(value, targetType);
		}
		return this.Operation.DynamicInvoke(value);
	}

	public object ConvertBack(object value, Type targetType,
		object parameter, System.Globalization.CultureInfo culture)
	{
		throw new NotImplementedException();
	}

	private void ConstructOperation(object value, Type targetType)
	{
		int opi = this.Code.IndexOf(&quot;=&gt;&quot;);
		if (opi &lt; 0) throw new Exception(&quot;No lambda operator =&gt;&quot;);
		string param = this.Code.Substring(0, opi);
		string body = this.Code.Substring(opi + 2);
		ParameterExpression p = Expression.Parameter(
			value.GetType(), param);
		LambdaExpression lambda = DynamicExpression.ParseLambda(
			new ParameterExpression[] {p}, targetType, body, value);
		this.Operation = lambda.Compile();
	}
}
</pre>
</pre>
<p>You can download <a class="zip" title="WPFix1 Solution" href="http://www.fikrimvar.net/lestirelim/wp-content/uploads/2007/11/wpfix1.zip">WPFix1 Solution</a> (VS2008 Beta 2) and start playing.  How much longer would you wait, if you knew a similar but standardized way of writing code in XAML will be available with the release?  By the way, welcome to my web log.<br />
<ins datetime="2008-10-02T06:48:46+00:00">This download is now outdated. Solution files are updated on the following parts of this series. I know you want to get your hands dirty, but please keep reading. Thanks to chaiguy1337 for reminding.</ins></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fikrimvar.net/lestirelim/?feed=rss2&amp;p=15</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
