Friday, October 03, 2008

MSDN Question on WPF: Refreshing Data Bound Items

A poster on MSDN Forums asked a question about data binding. I had the same issue later when I was working on my query base editing tool. The question goes something like this

There are two textboxes A, B and C. TextBox A and B are bound to some data source. TextBox C has value which is bound to a converter which sends the value based on the content inside A and B. The first time the form shows up, C looks fine. Now, I go ahead and edit the text in one of the A or B. The C does not get updated until I reload the section(form). C is basically data bound to A and B. So how do I update the databound value on C?

The question or scenario is not exactly as described above, but I hope it is simple enough to give a clear picture.

Let me try and explain what happens.

When the form is loaded, the data bound controls are updated. Then the changes made are not reflected onto the C, but the actual source is updated. So we need to add some framework that updates even C.

The Binding element has a property called "NotifyOnSourceUpdated". If you set this value on Binding to True and then handle the SourceUpdated event on that data bound element, you can track the changes made from the control. Doing so, we can then refresh the data binding on C. The Xaml for A, B and C can look something like this:

<
StackPanel DataContext={Binding MyStupidDataSource}>


<TextBox Name="A" Text={Binding TextAValue,NotifyOnSourceChanged=True}"
SourceUpdated="
RefreshContentsOfC"/>


<TextBox Name="B" Text={Binding TextBValue,NotifyOnSourceChanged=True}"
SourceUpdated="
RefreshContentsOfC"/>


<TextBox Name="C" Text={Binding Coverter=MyStupidConverter}"/>


</StackPanel>

Notice the NotifySourceChanged and SourceUpdated sections in the above XAML.
Now the RefreshContentsOfC is an event handler which refreshes the data binding on C. The code would look like.

public void RefreshContentsOfC(object sender, DataTransferEventArgs e){

//Refresh Data Binding -> Answer for the question

BindingOperations.GetBindingExpressionBase(C, TextBox.TextProperty).UpdateTarget();

}

Wednesday, October 01, 2008

MSDN Question on WPF: Label inside a Gridcolumn should determine the width of the column.

Given XAML.

<
Grid
>
    <
Grid.ColumnDefinitions
>
        <
ColumnDefinition
/>
        <
ColumnDefinition
/>
        <
ColumnDefinition
/>
        <
ColumnDefinition
/>
    </
Grid.ColumnDefinitions
>
    <
Grid.RowDefinitions
>
        <
RowDefinition
/>
    </
Grid.RowDefinitions
>
    <
Label Grid.Column="0" MinWidth="120" Width="200">Some caption</Label
>
    <
TextBox Grid.Column
="1" />
    <
Label Grid.Column="2" MinWidth="120" Width="200">Some other caption</Label
>
    <
TextBox Grid.Column
="3" />
</
Grid
> 

Rendering the xaml as it is in a XAML viewer like KaXaml or XamlPad or Visual Studio Xaml editor, shows that the labels get clipped if the text is too big. So how do you make the label text size determine the width of the column?

For this question, I have referred to Programming WPF by Chris Sells and updated my knowledge about Grid layout in WPF. Essentially, the Width of a column in a grid can be fixed (do not use unless you really want to), automatic and proportional(use "*"). So when a column takes * as width, it takes the space that is left after the fixed and auto width columns are rendered. So if you modify the above XAML with the information I just gave, it works out fine.

The modified XAML would be.

<
Grid
>
    <
Grid.ColumnDefinitions
>
        <
ColumnDefinition Width
="Auto"/>
        <
ColumnDefinition Width
="*"/>
        <
ColumnDefinition Width
="Auto"/>
        <
ColumnDefinition Width
="*"/>
    </
Grid.ColumnDefinitions
>
    <
Grid.RowDefinitions
>
        <
RowDefinition
/>
    </
Grid.RowDefinitions
>
    <
Label Grid.Column="0">Windows Presentation Foundation, Silverlight, Windows Communication Foundation, Windows Workflow Foundation</Label
>
    <
TextBox Grid.Column
="1" />
    <
Label Grid.Column="2">another long caption in here</Label
>
    <
TextBox Grid.Column
="3" />
</
Grid>

As you can see, I have just altered the Width property cleverly(theoretically, from the book) such that the label columns have width auto and the other labels have width *. So the columns whose width is Auto is rendered first and then the columns with proportionate width are rendered.

I like this little things on forums which gives us a lot of information. So, if you want to become a better developer you should:
1. Read Blogs, Write Blogs
2. Try and answer forum questions.

MSDN Question on WPF : Display Image XAML without copy/paste

As a part of personal development, I have once again started answering questions on forums. I was once a top contributor at dotnetforums.com but the site is no longer up. From what I learnt back then, I strongly believe that you get to learn more by answering people's questions online. As a part of it, I decided I would write a little about every answer that I give on windowsclient.net, if it is marked as answer. So, here comes the first post. One member had company logo exported as XAML. Now he wants the logo to show up inside an Image element, without having to paste the XAMl at all the places.

Question: Is there a way to display the contents of this file inside an <Image> element, therefore without copying/pasting the file content?

My suggestion (definitely not perfect):
Give the Image a name. Modify the XAML you got into a drawing image root and save it as a resource. Load the XAML at runtime from the resource and use XamlReader.Load("your xaml"). It now returns DrawingImage and set it to the source of the actual image. So, it would look something like this.

DrawingImage img = XamlReader.Load("mylogo.xaml") as DrawingImage;

Set this "img" as Source for the Image element.

where mylogo.xaml would be like:

<DrawingImage xmlns="wpf namespace...">

<!-- Xaml for your image, that fits in as a child for DrawingImage -->

</DrawingImage>

Does Multi-Threaded Winforms application really exist?

For my thesis, I wanted a powerful MDI application. By powerful, I mean which can process at least 100 child forms at a time. Each form does a bunch of background work and for this reason I wanted a truly multithreaded windows application. So I went ahead and spawned the child forms using ThreadPool.

The child form is pretty simple for this example, it does not do any major background work. It just has a browser control and when clicked on a menu item, it sleeps for 10 seconds and sets the text of the form to "Done". I have two menu options, one to do work in the background and one which does not do that work in the background. But when you launch a Multithreaded MDI, you expect the work to be done in the background, irrespective of the way you code it.

private void someWorkNotInBackgroundToolStripMenuItem_Click(object sender, EventArgs e)
{
Thread.Sleep(10000);
this.Text = "Done";
}
A true multithreaded application should not stuck up other child windows when it does the above shown work.


But that is not the case. So you have do something like shown below, for the application to be truly responsive irrespective of the background work it does.



private void someWorkInBackgroundToolStripMenuItem_Click(object sender, EventArgs e)
{
new MethodInvoker(() => Thread.Sleep(10000)).BeginInvoke(new AsyncCallback(it => this.Text = "Done"), null);
}

A delegate is used to asynchronously perform background jobs inside a windows form. Doing so does not stuck up the application unlike the first case.


Using ThreadPool to spawn threads



Well, if you want a truly multithreaded application, then you have do all tasks in background using BeginInvoke() as shown the previous code snippet. Spawning child threads to create MDI Children would not help. But anyway, in this section, I show you how to use ThreadPool and just because we are talking about Multithreaded Windows, I show the windows in the worker thread.



Firstly, in order to use thread pool, we need a worker item. For this worker item, it is recommended you create a class that represents this worker item. My worker item is shown below.



class ThreadPoolWorkerItem
{
/// <summary>
///
The tracker supposedly keeps track of the worker item status.
///
Though in this example, it does not work. Usually in the work method,
///
you do a Set() on this tracker which signals the WaitHandle.
/// </summary>
private ManualResetEvent tracker;

/// <summary>
///
Initializes a new instance of the <see cref="ThreadPoolWorkerItem"/>
class.
/// </summary>
/// <param name="tracker">
The tracker.</param>
14:
public ThreadPoolWorkerItem(ManualResetEvent tracker)
{
this.tracker = tracker;
}

/// <summary>
///
Performs the work done by the current ThreadPool Worker Item.
/// </summary>
/// <param name="threadState">
State of the thread.
</param>
public void work(object threadState)
{
ChildForm cf = threadState as ChildForm;
//cf.Show() is invalid. It throws an InvalidOperationException, since cf was not created in this thread.
cf.Invoke(new MethodInvoker(() => cf.Show()));
cf.FormClosed += new FormClosedEventHandler(cf_FormClosed);
//The two statements below simulate a job that takes 1 second to work and then it notifies using the tracker.
//That is the way usually ThreadPool worker items should work.
//Thread.Sleep(1000);
//tracker.Set();
}

/// <summary>
///
Handles the FormClosed event of the cf control.
///
In this event, we supposedly inform the waiting thread about the current worker item's job done.
///
It does not work in this example.
/// </summary>
/// <param name="sender">
The source of the event.
</param>
/// <param name="e">
The <see cref="System.Windows.Forms.FormClosedEventArgs"/> instance containing the event data.
</param>
void cf_FormClosed(object sender, FormClosedEventArgs e)
{
tracker.Set();
}
}

The code explains how threadpool worker items should be created.


The code for adding worker items to the ThreadPool is shown below.





   1: /// <summary>


   2: /// Does the work.It creates ThreadPoolWorkerItems and adds it to the ThreadPool.


   3: /// </summary>


   4: private void DoWork()


   5: {


   6:     ThreadPool.SetMaxThreads(2, 2);


   7:     ManualResetEvent[] trackers = new ManualResetEvent[Maxthreads];


   8:     for (int i = 0; i < Maxthreads; i++)


   9:     {


  10:         trackers[i] = new ManualResetEvent(true);


  11:         ThreadPoolWorkerItem item = new ThreadPoolWorkerItem(trackers[i]);


  12:         this.Invoke(new MethodInvoker(() =>{                                                  {


  13:                      ThreadPool.QueueUserWorkItem(item.work, new ChildForm("http://google.com") { MdiParent = this });


  14:                 }));


  15:     }


  16:     WaitAll(trackers);


  17: }




The code explains how you actually create and add worker items to  thread pool. In this case using a "ThreadPool.QueueUserWorkItem(item.work,new ChildForm("http://google.com"){MdiParent = this});" would give a ThreadStateException (for other cases, you might see a InvalidOperationException). For that reason, a this.Invoke() is used to create the child form and spawn it.



So you schedule some jobs in the ThreadPool and you should wait for them to complete. So how do you wait? We use WaitHandle.WaitAll(trackers); which suspends the current thread until all the spawned worker items in the ThreadPool are completed, whose manual reset events are the "trackers".



But in our case, it does not work. So I thought, it has some issues and researched online. I found an alternative WaitAll() to be used in Windows Forms.





   1: /// <summary>


   2: /// Waits on all the wait handles to complete execution.


   3: /// The WaitHandle in this case is a manual reset event.


   4: /// </summary>


   5: /// <param name="waitHandles">The wait handles.</param>


   6: private void WaitAll(ManualResetEvent[] waitHandles)


   7: {


   8:     foreach (WaitHandle myWaitHandle in waitHandles)


   9:         WaitHandle.WaitAny(new WaitHandle[] { myWaitHandle });


  10: }




The WaitAll() to be used in Windows Forms. Note that none of the concepts explained would really create a multi-threaded windows forms applications where each child form run in its own thread. But the information I obtained is shared here.



Using Threads without ThreadPool



Threads could directly be created and spawned which shows the Child Forms. Something like that could be done as shown.





   1: for (int i = 0; i < Maxthreads; i++)


   2: {


   3:         new Thread(() =>{


   4:            this.Invoke(new MethodInvoker(() => 


   5:                 new ChildForm("http://google.com") { MdiParent = this }.Show()));


   6:                          }).Start();


   7: }




We create a thread which again delegates its job of creating a child window the the parent form. So is this going to be helpful? So can you create a truly multithreaded MDI application?



Again, I repeat, from what I know and from what I researched, you cannot create Child forms in an MDI application where each Child runs in its own thread. The form UI thread has to be spawned from the parent MDI form itself, thereby making it impossible for the thread to survive. As soon as the Show() is done, the thread dies, because it has nothing else to do!



Using Application.Run() to create child MDI forms



First of all, this is something I found out just now. So it has to be lame and you should probably not use this at any cost. But anyway here the code is.





   1: /// <summary>


   2: /// Handles the Click event of the launchUsingApplicationRunToolStripMenuItem control.


   3: /// It launches the Child windows using Application.Run().


   4: /// For it work, you should set the AparmentState of the thread to STA. Right now, I use a depricated way


   5: /// to do that. Optionally you can add a method with attribute set to STAThread, like in the Program.cs Main()


   6: /// </summary>


   7: /// <param name="sender">The source of the event.</param>


   8: /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>


   9: private void launchUsingApplicationRunToolStripMenuItem_Click(object sender, EventArgs e)


  10: {


  11:     for (int i = 0; i < 10; i++)


  12:     {


  13:         new Thread(() =>


  14:                        {


  15:                            ChildForm cf = new ChildForm("http://google.com") { };


  16:                            this.Invoke(new MethodInvoker(() => cf.MdiParent = this));


  17:                            Application.Run(cf);


  18:                        }) { ApartmentState = ApartmentState.STA }.Start();


  19:     }


  20: }




Do no use this. It just shows how retard I am.



Finally, how to make Multithreaded MDI?



From what I know, you cannot make a child form run in its own thread. But you can make the work it performs using asynchronous calls or threads.



So for every heavy job your child form does, you have spawn a thread or use asynchronous calls, iff you want your application to be responsive.



Disclaimer: I am no guru either in WinForms or Multi-threading. But I tried to share what I learnt writing applications for my thesis and job.

Thursday, September 25, 2008

Learn growth strategies from Google

I strongly believe that its the idea that makes or breaks a successful business. There are plenty of examples to prove that. Most of the startups have one idea and the business person who would be the founder would recruit technical geeks who implement their idea. And if the idea is appreciated by many people, the business clicks and at end of the day, the founder makes money. And what happens to the technical guy? Well, in the best case he ends up becoming a CTO. And in the worst case? He moves on to a different firm. Anyway the point here is that IDEA is worth billions. The search engine  idea was the greatest and few firms failed miserably to implement it in the right way. Then comes Google and with its uber-cool implementation and simplicity, it won the hearts of millions and for many people internet is Google. Upto this point it is fine. Then Google decides to buy any business that potentially makes money out of web. So it acquired bunch of startups. And it still makes more money than any other internet firm. Ok, let me not cry over Google profits. I really don't care what it makes or what it earns. But Google somehow believes strongly that "everything it does is the best". So it tries to monopolise every sector - baby-sitting, browser(I am writing this post from Chrome browser and I like it), and mobile phones. I am pretty sure, people at google believe they would release an OS which is way better than any OS released till date (I think only the Mainframes deserve to be called "the best"). But hey, it knows it cannot capture the market ruled by Microsoft since the birth of PC. So it is running short of ideas to make more money.

It has reached a saturation point where it makes steady income, it earns X $ more every year but growth rate is where X$ more every year is 0% growth. So how do you grow? Implement new ideas, right? But people these days are smart enough that they want to make millions themselves. So they start their own firms with their own idea. But there are billions of internet users and even if 1/1000th of them have some ideas, then it is worth billions of $. so now google launches a 10 power 100 ideas scheme, saying "we want to help people" (you want to help people? Invest in electric cars research and then save the planet) so we want your ideas. We buy ideas from great minds for $10 mi. and we will help people (and at the sametime help ourselves by making few $billions more). So who wins at the end of the day?

And Google gives every software for free. Yeah, it does not make money right? What about the share price of Google? Does it not grow everytime it does something? hey, but still the software is free. So lets talk about the popular software that google offers free.
1. Chrome - Everyone is right now talking about Chrome. But would you buy a browser when IE, Firefox and Opera (also Safari) are out there - free (and kind of better in many ways).
2. Search - Ok, it is a great software. I have no complaints.
3. Gmail - Come on! I can give you loads of websites that offer free email.
4. Google toolbar? I really hate toolbars and google search engine after using the single-sign-on keeps track of my browsing history. It should be off by default. I do not want anyone to keep track of what I browse. Some might find it useful, but trust me, many does not. I keep my browser on in my laptop, leave it open or ask my brother to use it. Later I log into my google account and guess what I can see what websites I browsed.(actually what my brother browsed). That really sucks.
5. Google Analytics - again, we are submitting ourselves to Google. Come, rip my information off and give it back to me free. Do you know, you could gather all the data by yourself and use Excel to project many different charts. As long as scum-CEO who does not know ABC of web would not want to invest in a developer and instead invests in G . A.

Anyway, the point is just because Google Search is the best, it does not mean every fart that google leaves is great. And hey, do not think google would ever beat Apple IPhone (their phone sucks and would suck). Google Docs, by the way suck too. I prefer to buy a 79$ Microsoft license for 3 pc than to work with Web docs. Do not let firms rip your ideas off. You can be another google, if you work hard and if you are confident.

Wednesday, July 30, 2008

Windows Presentation Foundation, Logical and Visual Trees

In this post, we look at the element trees that are generated at runtime in a WPF application known as the Logical Trees and Visual Trees. For a detailed and accurate content, refer to this MSDN Link.

WPF uses several tree structure metaphors to define relationship between program elements. These structures help developers directly manipulate the elements after the tree is rendered. The documentation talks about trees as

   1: The primary tree structure in WPF is the element tree. 


   2: If you create an application page in XAML, then the tree structure is created based on the nesting relationships of the elements in the markup. 


   3: If you create an application in code, then the tree structure is created based on how you assign property values for properties that implement the content model for a given element. 


   4: In Windows Presentation Foundation (WPF), there are really two ways that the element tree is processed and conceptualized: as the logical tree and as the visual tree.




The logical tree exists so that the content models can readily iterate over their possible child elements which makes the content models extensible. Anyway, the logical tree can be viewed as tree representation of the elements that are created just when the application starts. It is like a Tree-ized version of the XAML document(if there is one that is used). Resources are resolved using logical trees by first looking for a resource specified in the requesting element and then the parent elements.



The Visual Tree describes the structure of the visuals represented by the Visual class. A template for a control defines the visual for that control and this is included in the Visual Tree. It also includes the object that are added at runtime. The visual tree gives control over low-level drawing in case it is required for optimization purposes.



In the subsequent sections, we look at how both Logical Tree and Visual Tree are binded to TreeView control in the WPF. So to get started, first lets look at the XAML for the Tree control we are using for the Visual Tree.





   1: <TreeView Name="VisualTree" Grid.Column="1" Grid.Row="0" Background="AliceBlue">


   2:                 <TreeView.ItemTemplate>


   3:                     <HierarchicalDataTemplate ItemsSource="{Binding Children}">


   4:                         <ContentPresenter Content="{Binding Name}"/>


   5:                     </HierarchicalDataTemplate>


   6:                 </TreeView.ItemTemplate>


   7: </TreeView>




TreeView has an ItemTemplate property which can be customized to define the appearance of the elements in a tree. We must add a DataTemplate to this ItemTemplate property. We chose the HierarchicalDataTemplate in this case where define how each element in the hierarchy should be displayed. More about hierarchical data templates would be presented in the later posts. This also covers the data binding expressions in WPF. In line 3, when we said ItemsSource = {Binding Children}, the framework looks for Children (which is a collection) in the DataContext of the TreeView or its parent. So if treeview's Datacontext property is set to "X", then ItemsSource would be X.Children. For each child in the Children, it is rendered using ContentPresenter where the content is taken from the child's Name property.



So this treeview code should be something like this :





   1: var some_tree; //some_Tree has children property


   2: visualTree.DataContext = some_tree;




The actual code we used in the BuddiPad is shown below.





   1: private void DumpVisualTree ( DependencyObject p )


   2: {


   3:             VisualTree.ItemsSource = new VisualTreeItem ( p ).Children;


   4: }




Notice that we used ItemsSource property instead of DataContext property. So what is the difference between these two? The details would be covered in the Data Binding segment of the talk. Note that VisualTree.DataContext would not work in this case.



The code for the VisualTreeItem class is shown below. It is very simple, recursive and straightforward.





   1: /// <summary>


   2:     /// When we build a Visual Tree to be displayed in a TreeView, this class forms the basis of the TreeViewItems.


   3:     /// </summary>


   4:     public class VisualTreeItem


   5:     {


   6:         /// <summary>


   7:         /// The _element is the Dependency Object whose treeview data item is this instance.


   8:         /// </summary>


   9:         private DependencyObject _element;


  10:  


  11:         /// <summary>


  12:         /// This is the list of children that the _element has.


  13:         /// </summary>


  14:         private List<VisualTreeItem> _children;


  15:  


  16:  


  17:  


  18:         /// <summary>


  19:         /// Initializes a new instance of the <see cref="VisualTreeItem"/> class.


  20:         /// </summary>


  21:         /// <param name="dop">The Dependency Object/UI element</param>


  22:         public VisualTreeItem ( DependencyObject dop )


  23:         {


  24:             _element = dop;


  25:         }


  26:  


  27:         /// <summary>


  28:         /// Gets the children.


  29:         /// </summary>


  30:         /// <value>The children.</value>


  31:         public List<VisualTreeItem> Children


  32:         {


  33:             get


  34:             {


  35:                 if (_children == null)


  36:                 {


  37:                     //initialize the list with capacity expected as the number of children


  38:                     _children = new List<VisualTreeItem> ( VisualTreeHelper.GetChildrenCount ( _element ) );


  39:                     for (int i = 0; i < VisualTreeHelper.GetChildrenCount ( _element ); i++)


  40:                     { //for each children in the VisualTree for that dep object where each child is a Dep Object.


  41:                         _children.Add ( new VisualTreeItem ( VisualTreeHelper.GetChild ( _element, i ) ) );


  42:                     }


  43:                 }


  44:                 return _children;


  45:             }


  46:         }


  47:  


  48:         public string Name


  49:         {


  50:             get


  51:             {


  52:                 FrameworkElement fe = _element as FrameworkElement;


  53:                 if (fe != null && !String.IsNullOrEmpty ( fe.Name ))


  54:                 {


  55:                     return Type + ":" + fe.Name;


  56:                 }


  57:                 else


  58:                 {


  59:                     return Type;


  60:                 }


  61:             }


  62:         }


  63:  


  64:         public string Type


  65:         {


  66:             get


  67:             {


  68:                 return _element.GetType ( ).Name;


  69:             }


  70:         }


  71:  


  72:  


  73:     }




The code is heavily adapted from Kevin Moore Bag-o-Tricks but its the same tree code that I have written numerous times for different projects. The heart of this implementation is usage of VisualTreeHelper class. The recursive part of it is in the Children property. The Logical Tree could be dumped in a similar fashion but using LogicalTreeHelper class.



So far, most of the work involved in getting the BuddiPad running has been covered. Now in the next part, we look at other WPF topics that are scheduled for the talk. In the next post, we compare WinForms with WPF in detail.