Vasu Balakrishnan’s Blog

Archive for June 2009

WPF Trees

leave a comment »

WPF has the notion of Logical / Visual trees. The logical trees represents the control hierarchy as defined by the developer either via XAML or code. Just about every aspect of WPF (Properties, Events, Resources, etc) has behavior tied to the logical tree. Visual tree is an expansion of logical tree, in which nodes are broken down into their core visual components. The visual tree describes the structure of visuals (elements that inherit of Visual base class). Content elements (deriving from ContentElement) are not part of the Visual tree. Routed events travel along the visual tree and not the logical tree. Visual tree is of interest if you want low level control over drawing for performance / optimization. 

You should avoid writing code against the Visual tree as it breaks once of core principle of WPF – separation of look and logic. A Visual tree can change simply by a user switching to a different Windows theme. Visual tree is empty until the window undergoes layout at least once.

You can traverse Logical / Visual tree using LogicalTreeHelper / VisualTreeHelper classes.

Here is an article that goes further in explaining the trees.

Written by nbvasu

June 30, 2009 at 4:17 pm

Posted in WPF

XAML

leave a comment »

As I’m reading XAML Demystified chapter from book, few things caught my attention and I didn’t know about them before.

  • “XAML is a relatively simple and general purpose declarative programming language suitable for constructing and initializing .NET objects”. I’d thought XAML was built for WPF. The author say that it could be applied to any .NET technology like Workflow Foundation, etc. I then did a quick search for XAML usage and it led me to video where they talk about XAML in .NET 4.0. I’m excited about some of the upcoming features.
  • XAML specification defines rules that map .NET namespaces, types, properties, and events into XML namespaces, elements and attributes. XAML was designed to work with .NET type system, and can be used with just about any .NET object.
  • At runtime, event handlers are always attached before any properties are set declared in XAML (excluding Name property which is set immediately after object construction)
  • Property Elements – They always take form as TypeName.PropertyName, they are always contained within the TypeName object element and can never have attributes of their down. They can be used for simple properties as well.
  • Type Converters – They know how to convert the string representation to the desired data type.
  • Markup Extensions, like Type Converters, enable you to extend the expressibility of XAML. Both can evaluate string value at run-time and produce an appropriate object based on the string. Unlike Type Converters, Markup Extensions are invoked from XAML with explicit and consistent syntax. They support Positional / Named Parameters. Positional parameters are treated as string parameters to the extension class’s appropriate constructor.
  • An Object element can have three types of children – a value for content property, collection items or a value that can be type converted to its parent. To avoid ambiguity, the following rules are followed by XAML compiler when encountering / interpreting child elements

    • If type implements IList, call IList.Add for each child
    • If type implements IDictionary, call IDictionary.Add for each child, using Key attribute value for key and element for the value
    • If the parent supports Content property and the type of the child is compatible with that property, treat the child value as its value
    • If the child is plain text, and a type converter exists to transform the object into the parent type, treat the child as input into the converter and the use output as the parent object instance.
    • If none of the above applies, raise an error.
  • WPF’s runtime XAML parser is exposed as two class XamlReader / XamlWriter.
  • XAML language namespace has a Name keyword that enables you to give any element a name. x:Name syntax is used to name elements but that can be overridden to any other property using a custom attribute RuntimeNameProperty. You can use either mechanism but not both.
  • XAML compilation involves three things: converting a XAML file into a special binary format, embedding the converted content as a binary resource (BAML) in the assembly being built and performing the plumbing that connects XAML with procedural code automatically.  BAML stands for Binary Application Markup Language, is simply XAML that has been parsed, tokenized and converted into binary form. Its a compressed declarative format that is faster to load and parse. Its just an implementation detail of the XAML compilation process. This does not generate procedural source code. Some procedural code do get generated (if you use x:class) but its just some glue code written to load / parse a loose XAML file at runtime. They files are given .g.cs suffix. The glue code generates a partial class (specified by x:class), contains a field (private by default) for every named element in the XAML. It also has an InitializeComponent method that does the work of loading embedded BAML resource, assigning fields to appropriate instances originally declared in XAML and hooking up event handlers. BAML can be decompiled back to XAML using Application.LoadComponent.

The last item in the list, is something that I wasn’t aware of. I’ve seen the glue code few times as part of my debugging process, but didn’t pay attention to it. Now it makes it clear.

I’m moving on to next chapter…

Written by nbvasu

June 29, 2009 at 2:10 pm

Posted in WPF

WPF

leave a comment »

I’m currently reading Windows Presentation Foundation Unleashed book by Adam Nathan. I’ve just finished the introductory part. I just skimmed over Chapter 2 (XAML Demystified) and I’m going to read it again. The author has done a good job in going into the internals of XAML, even MSDN reference didn’t mention them in the documentation. So far I like this book. I’ll post my reviews / thoughts on the book in my following posts.

Written by nbvasu

June 29, 2009 at 10:36 am

Posted in WPF

F# |> operator

leave a comment »

 

As I was reading this blog, it made it clear to me the usefulness of currying, partial application forward pipe concepts of a functional program.

Look at the following lines of code in C#. If we don’t want to store intermediate results we have to write our algorithm in reverse order and with heavily use of brackets. The function we want to apply last has to be written first. This is not the way we think about it.

 
var list = new List<int> {4,2,6,5,9,3,8,1,3,0};
Console.WriteLine(Square(CalculateSum(FilterEven(list))));

 

The same can be written in F# as below. We describe the data flow in exactly the same order we talked about it.

 
let list = [4; 2; 6; 5; 9; 3; 8; 1; 3; 0] 
let square x = x * x
list 
    |> List.filter (fun x -> x % 2 = 0) // partial application 
    |> List.sum 
    |> square 
    |> printfn "%A" // partial application

 

Written by nbvasu

June 18, 2009 at 10:59 pm

Posted in F#

Multithreading

leave a comment »

Here is an excellent series of posts about Multithreading. I’ve just started reading the first post. This is a must read.

As I’m reading these posts, I’m going to log my observations.

  • There are four main aspects to a multi threaded application – state, atomicity, serializability, linearizability
  • In Unix, process is the fundamental unit of concurrency, whereas in Windows its the threads. The post says Windows chose this approach because its “lighter” to create processes in Unix than in Windows. I’m not sure what “lighter” means. How Unix Process is architecturally different from a Windows Process?
  • A thread could be either a foreground / background thread and that a background thread doesn’t prevent a process from exiting.
  • ThreadPool provides the application with a pool of worker threads. They are background threads, use default stack size, runs at default priority and is in multithreaded apartment. There is only one thread pool per application.
  • A stack is a contiguous region of memory that grows downward and is used for several operations. The default stack size is 1MB. In C#, you can allocate a block of memory in stack using stackalloc. They are not subject to garbage collection and lifetime is limited to the method in which it is defined.
  • In using Stack as storage post, the author says if you’ve a static field marked as ThreadStatic, you should always check for lazy initialization. The initialization code will run only once, and if we didn’t have lazy initialization the second thread would throw an error. That’s why he has the field wrapped in a static property. Wow!!! I wouldn’t have guessed it.
  • In a multithreaded world, problems happen when you’ve several threads reading and writing or several threads writing to a shared memory location. The author says if we build immutable types, then we don’t need to synchronize access to these items. There are two types of immutable – shallow and deep. A type is shallow immutable if each field of an object never changes during its lifetime. The object is deeply immutable if each field references other objects which don’t change over time too. CLR supports limited immutability via read only fields. There is no CLR support for ensuring deep immutability.
  • Synchronization can be classified into two broad sub areas : data / control. The Data is more commonly used where we ensure that only one thread accesses data at each time. Control is used when one thread depends on other having executed some piece of code.
  • Data Synchronization relies on serializing access to shared state. This is done by creating Critical regions, which delimits several instructions that are executed by a specific thread in a serialized fashion. The usage pattern is simple – thread enters critical region, executes several instructions and leaves the critical region (assuming that there are no exceptions and thread isn’t aborted. I’ve to find out what happens in this scenario)
  • Control Synchronization is appropriate when you need to ensure collaboration between several threads. In this case, we will have threads that will need to wait while some condition isn’t true. There are several ways to implement wait logic
  • busy waiting – you’ll have an infinite cycle which will run until specific condition is true. This might be useful if the thread can do some useful work while waiting. Otherwise, its not a good approach to just keep spinning without any work.
  • real wait – In this case, OS puts the thread in a real wait state so that it wont consume processor time, but will incur thread context switch costs.
  • continuation passing – This relies on passing a closure for being executed when other specific action ends. This might be a good option where waiting is too expensive. Shared state is encapsulated in messages which are passed between threads. This topic is something that I’ve been trying to understand. I didn’t expect it to be used in this context.
  • Kernel objects – We can use kernel objects to achieve Data / Control Synchronization. There are several kernel objects. In traditional Win32, each kernel object is represented by a HANDLE, and can be in one of two states – signaled and non-signaled. Transition between the states depends on the type of kernel object we’re using. We are interested only in waiting on Synchronization kernel objects – mutexes, semaphore, event (auto/manual) and timers. The .NET framework introduces a base class (WaitHandle) on which we can wait, that is extended by mutexes, semaphore and events. AutoResetEvent / ManualResetEvent extends the EventWaitHandle. A thread gets blocked waiting for a kernel object to transition from non-signaled to signaled state, it might wake up without a corresponding transition. This happens if the thread performs so called “alertable wait”. He says in managed code, thread always performs alertable wait. I’m not really sure what they are and to me it seems to defeat the purpose of waiting on a kernel object.
  • Written by nbvasu

    June 12, 2009 at 2:36 pm

    Posted in C#

    Checked Exceptions in C#

    leave a comment »

    I was wondering why C# doesn’t have Checked Exceptions like Java. I’ve heard arguments about how Checked Exceptions makes it clear as to what exceptions you can expect from calling a code.

    I did a quick search over in Stackoverflow and people do have asked the same question. I then followed this link here, and after reading it makes sense why C# language designers opted out. Also there was article from Bruce Eckel about this too. Both are worth a read.

    Written by nbvasu

    June 12, 2009 at 11:25 am

    Posted in C#

    Learning F#

    leave a comment »

    Since I’ve started to use LINQ, I was interested to learn about Functional Programming. Its a programming paradigm that embraces functions as first class citizens, enables higher order functions, avoids mutable state, etc. The more I started to use in my projects, I began to appreciate the functional style of programming, and  that’s how I got me learn F#.

    We have built a statistical module in C# to calculate mean, standard deviation, etc. I wanted to try implementing them in F#.

    module stats =
    
        let sqr x = x * x
        let mean (data : vector)  = data |> Seq.average
        let max  (data : vector)  = data |> Seq.max
        let min  (data : vector)  = data |> Seq.min
        let range (data : vector) = max data - min data
    
        let avggain (data : vector) =
            data |> Seq.filter (fun x -> x > 0.0) |> Seq.average
    
        let avgloss (data : vector) =
            data |> Seq.filter (fun x -> x < 0.0) |> Seq.average
            
        let variance (data : vector) = 
            let mean = mean(data)
            (data |> Seq.sum_by(fun x -> sqr(x - mean))) / float (data.Length - 1)
    
        let stddev (data : vector) = sqrt(variance(data)) 
        let stddev3 (data : vector) = stddev(data) * sqrt(3.0)
        let stddev12 (data : vector) = stddev(data) * sqrt(12.0)
    
        let skew (data : vector) = 
            let mean = mean(data)
            let stddev = stddev(data)
            let sum = data |> Seq.sum_by(fun x -> ((x - mean) / stddev) ** 3.0)
            let fact = (float data.Length / float ((data.Length - 1) * (data.Length - 2)))
            sum * fact
    
        let kurtosis (data : vector) =
            let mean = data |> mean
            let stddev = data |> stddev
            let len = float data.Length
            let fact1 = len * (len + 1.0) / ((len - 1.0) * (len - 2.0) * (len - 3.0))
            let fact2 = 3.0 * Math.Pow((len - 1.0), 2.0) / ((len - 2.0) * (len - 3.0))
            let sum = data |> Seq.sum_by(fun x -> Math.Pow(((x - mean) / stddev), 4.0))
            sum * fact1 - fact2
    

     

    Here is how you use them.

        let data = vector [0.20; -2.70; 1.59; 0.74; 0.31; 1.87]
        printfn "Input Data\n %A"  (data)
        printfn "Mean - %A"  (stats.mean data)
        printfn "Max - %A" (stats.max data)
        printfn "Min - %A" (stats.min data)
        printfn "Range - %A" (stats.range data)
        printfn "AvgGain - %A" (stats.avggain data)
        printfn "AvgLoss - %A" (stats.avgloss data)
        printfn "Variance - %A" (stats.variance data)
        printfn "StdDev - %A" (stats.stddev data)
        printfn "StdDev3 - %A" (stats.stddev3 data)
        printfn "StdDev12 - %A" (stats.stddev12 data)
        printfn "Skew - %A" (stats.skew data)
        printfn "Kurtosis - %A" (stats.kurtosis data)
    
        
    

    Its pretty straight forward code. I could’ve done the same in C# and with LINQ it would be pretty much be the same number of Lines. The one thing I like in this implementation is pipe forwarding operator (|>) in F#. To me it makes it so much easier to read the code. I wish I could do that in C#.

     

    Written by nbvasu

    June 10, 2009 at 4:35 pm

    Posted in F#