Google Search

Thursday, December 17, 2009

XAML exporter for Sketchup - Round 2

I just finished fixing some issues with the Google Sketchup Xaml Exporter.
The updated file can be downloaded here:

https://docs.google.com/leaf?id=0BxinGAr39Pd0ODQ2Y2IyZDUtZWNkYi00YTU2LTk3MmMtNDg4NmMzZDhlZjVh&hl=en

The new version fixes:
  • Different materials with the same base texture filename caused only one texture file to be created, thus wrong texture to appear.
  • Group transformations were ignored.
  • Back facing materials now supported.

Enjoy!


UPDATE:
I re-uploaded the file, this time under a bit different name. It seems that Vista shows me one version of the file, and even loads it correctly, while it shows a totally different file to the world.
I was told that the file I uploaded is not the correct file, and when checking locally, I saw that the size is really different. Strange, even rebooting didn't help. Oh well, saving as (and even copying!) to another local folder solved it, but I still don't understand why it happened.


Sunday, September 27, 2009

Google SketchUp Xaml exporter

I wanted to build a WPF 3D application, that will present models. I didn't want to include code that loads different formats and creates WPF models at runtime, and I wanted an easy-to-use, free modeler.
Blender is free, but I find it very cumbersome. Google SketchUp is very easy to use, but was lacking a way to export to XAML.
Fortunately, SketchUp has a very easy-to-use Ruby API that I could use to build an exporter.
It currently exports the meshes separated by materials, and grouped together in geometry groups according to the same hierarchy structure of the model. Materials include front faces only (i.e. no BackMaterials) and support solid color and textures. If no material is given, a solid white material is used.
While it's not perfect, it does a pretty good job. Feel free to use and please send feedback,
http://cid-8fbcae0caa96d592.skydrive.live.com/self.aspx/.Public/xamlExporter.rb

UPDATE:
I updated the plugin. Check out the follow-up post: XAML exporter for Sketchup - Round 2.

Friday, August 7, 2009

Writing Quality Software - Code

Coding is bringing the architecture and design to life. Making the idea work. Correct coding is more than just writing code that runs and do what it supposed to do. Correct coding is about making sure the architectural principles are applied, the code is readable and maintainable, self explanatory and self debuggable. Keep in mind that code is meant to be read much more than it is meant to be written.

Debuggable Code

What exactly is “debuggable code”? Well, I would say a debuggable code is a code that helps you find where the errors are as you run into them. This can be done by:
  • Emitting enough logs where applicable.
  • Not “swallowing” exceptions.
  • Placing a method result in a local variable and returning it, rather than return a computation.
  • Preferring a full if/else when needed for populating a variable over the shorter form of x?a:b.
  • Breaking lines between different statements, such as
    if (something) return;
    which is not debuggable, since you can’t place a breakpoint on the ‘return’.
Generally, if you try to debug a section in your code and think it is too hard to debug because the debugger is not enough feature rich, think again how you can change your code to fit the debugger limitations.

Correct Casting

Scott Peterson posted this post about casting best practices. There are several things I would like to add upon.
First, when you expect a specific object type, prefer static cast, even in the case of a publicly visible method. The reason is that you would like the CLR to check the type for you and throw the relevant exception. Why? The alternative is you doing it yourself and responding correctly. Most people would simply “swallow” that error, which will yield bizarre errors elsewhere (most common ones are a null reference exception much deeper in the code, and it would be a very tedious work figuring out what went wrong).

Readable Code

For each project, select a standard and stick with it. Keep in mind that in some cases you might need to read the code you’ve written outside the IDE. This means you won’t have all the cool features like tooltips specifying a member type, go to member, find member references, etc. You want to write code that will be easier to understand without jumping up and down the file.
While it sounds like the Hungarian Notation might sound like a good idea (you can know the type and scope just by looking at the member name), it is a very unreadable notation. I like the naming that adds “m_” and “s_” prefixes to class members and static members respectively, but I hate the addition of “p_” prefix to parameters as I’ve seen in several places. So basically, it is all about readability. Whatever you choose, make sure it is easy to read outside an IDE (using notepad is a good test case), and stick with it.
Another aspect of readable code relates to indentation. Indentation is not an option, my friends. It’s a must, and its better be done right. Select your favorite method of indentation (most common methods include 4 characters wide, 8 characters wide and “smart”), and make sure all indentations are using the same method (spaces or tabs). I personally believe that spaces are the best way to go (along with monospaced font), since the overall code “design” is kept in all editors. Liran Chen has a post about an indentation issue in Visual Studio (in Hebrew).

Spelling

Don’t underestimate correct spelling. And prefer English in your code and comments over any other language. This will be used as a standard that will ease the process of joining new developers to the project. Minimize the use abbreviations and slang. It doesn’t come out nice, and tend to look unprofessional.

These are my two cents of how to write better code, and there’s much more to write on that subject. Maybe in one of my next posts.

kick it on DotNetKicks.com

Update


Just found this post regarding programming:

http://sites.google.com/site/yacoset/Home/signs-that-you-re-a-bad-programmer

I find it true, helpful and funny.

Sunday, July 26, 2009

Writing Quality Software – Quality Assurance

One must not underestimate the necessity of the QA team.

Quality Assurance (QA), the guys that test the software designed by the engineers and written by the developers. Their mission is to make sure that the software does what it needs to do, and do it well. They are also the first users of the software so they have the best review and criticism about the visual design and usability.

A developer needs to learn to listen to the QA team notes. The QA team, on the other hand, must learn how to note.

In order to really understand this, lets check things more thoroughly:
First of all, the role of the QA team versus the role of the development team in terms of software operability:

No QA team – Bad software; No development team – No software.

That said, we now need understand that the two teams must work together in order to create good software.

Friday, July 10, 2009

Writing Quality Software - Architecture

Designing the architecture of software is very important phase in the software lifecycle.

Rules of thumb:

A good piece of software would follow several rules of thumb:
  • Reusability – The piece of software should be as reusable as possible (unless it is applicative), and reuse other components as much as possible.
  • Extensibility – The piece of software should be as extensible as possible – i.e. have enough places which other developers (or the original developer in a later time) can use to add more functionality.
  • Functionality – The piece of software should make the life of its user easier. The 80-20 rule would fit here (at least 80% of the time…)
  • Order – The piece of software should be organized for easy finding of each piece of code, and easy thinking of a good place for a new piece of code.
  • Traceability – The piece of software should log its actions in details, preferably in different levels of detail. Usage of extensible logging libraries (such as log4net) are welcome.
  • Security – The piece of software should not reveal security leaks, that would allow malicious code to abuse (I am talking about things like code injection, unauthorized privileges modification, system denial of service, etc.)
  • Portability – The piece of software should be as portable as possible. Not necessarily between operating systems, but generally between computers. Zero installation (aka -xcopy deployment) is always welcome.

Thursday, May 28, 2009

How can Wikipedia improve its content reliability

Wikipedia is a very common online encyclopedia, built and managed in the form of a wiki, which means anyone can modify its values.

While this promises many writers, editors and critics, thus up-to-date content all the time, it also introduces great unreliability, as you can’t trust anyone who had written anything.

While even “Wikipedia founder admits there are serious quality problems”, I figured something can be done to improved the reliability and quality of the content.

So here is my idea: Wikipedia should introduce a “Content Reliability Factor” that will be visible, sticking out on the top of each page. This factor will be on a scale (say, from 1 to 10), and will allow the reader to know how reliable the information on this page is.

In order to calculate the reliability factor, Wikipedia should introduce “Fact Markup”, to specify “Fact Fields”. Items that represent clear, hard facts, preferably numbers, will be marked using this markup.

There will be different types of fact fields: Absolute numeric fact fields (usually used for scientific articles), Usually climbing numeric fact fields (say, number of children of someone), Citations, etc.

Readers that come across  fact fields would then be able to rate the correctness of each fact field, and/or the entire article. Some users will be granted higher reliability factor for some values or categories, and their vote will have higher influence of the calculated result. (Of course, some articles will be blocked for such changes, for the same reasons some articles are blocked for public editing today).

Now to the really good part: When ever someone that is not trusted in a certain value or category, changes a fact field, the reliability factor for that fact field decreases. The amount of decrease depends on the type of that fact field – say, for usually climbing numbers, a decrease of that number would result in a very large decrease of that field’s reliability factor, while an increase would result in a smaller decrease of that reliability factor.

In the article history, the reliability factor will be stated next to each version. In addition, the highest ever reliability factor will be stated next to the current reliability factor on the top of the page, and will link to the relevant version of the article.

So all in all, while this idea does not solve the problem completely, and surely does not free us from the need of human approval for the content, it will allow to make better decisions regarding the given content.

P.S., There are many other methods that can be integrated into such a system that will assist with its automation. Maybe I will discuss those some other time.

Tuesday, April 28, 2009

What can the government of Israel do to solve the water crisis

Israel suffers greatly from lack of water.

This is the case for many years now, and from one year to another the government is doing more and more to solve it. By "doing more and more" I mean pass on the blame and the responsibility to the citizens.

Now they have a big campaign featuring all greatest Israeli celebrities, telling us to save water; telling that we must stop watering our gardens; asking to shower less. Before we'll know it they'll limit our tap water drinking.

This is, of course, useless and idiotic. It won't help even a tiny bit. This is the same as doing micro-optimization to a monkey-sort algorithm. This is because the reason to this water crisis lies mainly on the fact that the population growing while the amount of water in our reservoirs stays the same (in the good case) or lowers (in the bad, current, case).

Saturday, April 25, 2009

BiDi – What is it, why we need it

BiDi stands for Bi-Directional text. Yes, specifically text. In some places (such as the Word text editor) this is referred to as Complex Scripts.

So what exactly is it? It is the case where several languages of different writing directions are mixed in a single sentence. More than that, in some cases, this is the case where a Right-To-Left language (Hebrew, Arabic and Persian) needs to be rendered to screen.

Why is this a problem? This is a problem because there is a dilemma of how to store textual data that contains both directions of writing; On the one hand, it can be stored visually, just like it appears on the screen. It will make it much easier to render, and save us from all the burden and improve performance of the rendering phase. On the other hand, however, it will make our writing phase much harder, and will require us to write some of the text reversed. Actually this is exactly what people where doing before the age of Logical Text and the BiDi algorithm.

The BiDi algorithm brought a new age of Logical Text, and by that we mean the way the text is stored in memory. Instead of storing it the way it is rendered, we store it the way it is being read and written. When we read text that contains several text directions (Hebrew and English mixed, for example), we change our reading direction every time the language is changed. When we write text that contains several directions, we still write the first letters first, and last letters last, even when the language changes. We don’t reverse the order of characters for that task.

A quick review of different UI frameworks

In this post I'll review several frameworks used for creating graphical user interfaces. I've decided to create such a review after noticing many programmers take a specific GUI framework for granted, as it is their automatic-choice-by-tool (i.e., they use what they're IDE let them, barely understanding the layers required to develop such a framework, and that there are alternatives they might have chosen if they had knew about).

I will review the following frameworks:

  • Windows.Forms
  • WPF (+Silverlight)
  • GTK
  • QT
  • wxWidgets
  • AWT
  • Swing
  • SWT
  • X/XT/Motif

Wednesday, April 15, 2009

Runtime testing and casting objects of generic types

How can you tell, in runtime, if an object you have is of a specific generic type? For instance, if it implements the generic interface ICollection ?

You might say, "lets get all interfaces implemented by that object, first by getting its type (using GetType()), then by calling GetInterface(string name), passing in the type name in its mangled form".
This will work, however, this yields to error prone, non-type-safe code, plus, making us required to know how to build the relevant mangled string.

We would like something better. We would like to be able to get the generic type itself. Fortunately this can be easily done the following way:
Type genericCollectionInterfaceType = typeof(ICollection<>);

This will return the generic collection interface type. Now, what can we do with it? We wanted to test if a certain object implements this interface. However, a list of, say, strings, will NOT implement that interface. It will implement the ICollection<String> interface, which is not the same as ICollection<>.

What can we do? We need to build, in runtime, a generic interface type that corresponds to the interface signature of our object:
Type testedObjectType = testedObject.GetType();
Type genericType = typeof(ICollection<>).MakeGenericType(testedObjectType.GetGenericArguments());

Then we can use that type to test for assignability:
collectionType.IsAssignableFrom(testedObjectType);

Calling MakeGenericType creates a new Type object that represents the type we are looking for. We pass it a list of types, in this case taken from the object itself (using GetGenericArguments). Then we can check for assignability between the two.

kick it on DotNetKicks.com

Saturday, April 11, 2009

Lasers and experiments

I tried to activate a laser diode today, that I disassembled from an old DVD player.
I used a cellphone recharger (outputs 5V) and connected the wires.
It worked for about half a second. I think it is now dead. R.I.P.
Anyone got old DVD/Bluray players they don't need?

The dead laser diode (on the right), and its original housing and controller.


The disassembled DVD player.

Thursday, April 9, 2009

Creating customizable WPF drop-down menus (7)


Step 7: Using the new binding correctly


Remember that we overridden OnDragEnter so the menu will open upon hovering? Well, we will have to make a slight change to that code, to (also) use our new property:

protected override void OnDragEnter(DragEventArgs e)
{
    IsSubmenuOpen = true;
    IsSubmenuOpenInternal = true;
    e.Handled = true;
}

Great! Except now the menu never closes. Well, the first occasion we want it to close is when we're done dropping. So we will add the following snippet to our OnDrop code, just before the e.Handle = true code:
if (parentMenuItem != null)
    parentMenuItem.IsSubmenuOpenInternal = false;

Another case when we want it to close is whenever a neighbor menu opens, or in case we stopped using the menu at all (like, clicking any other place). But the thing is, we really don't want to write such code, as it is already written. We need a way to find when the original property would change to false and do the same.
Luckily, there is a routed event just for that: SubmenuClosed.
We will register to that event, and change our new property to false likewise. Except, we do it with a minor change: we need to make sure we are not in the middle of a drag operation, or right in the drop handling code. We will register to that event in the constructor, and implement it:
public DraggableMenuItem()
{
    AllowDrop = true;
    SubmenuClosed += new RoutedEventHandler(DraggableMenuItem_SubmenuClosed);
}

void DraggableMenuItem_SubmenuClosed(object sender, RoutedEventArgs e)
{
    if (Mouse.LeftButton == MouseButtonState.Pressed || !IsDragging)
        IsSubmenuOpenInternal = false;
}

But now there is another problem - the menu doesn't open well, since we replaced the IsSubmenuOpen with IsSubmenuOpenInternal. So the same way, we need to handle the open event - SubmenuOpened:
public DraggableMenuItem()
{
    AllowDrop = true;
    SubmenuClosed += new RoutedEventHandler(DraggableMenuItem_SubmenuClosed);
    SubmenuOpened += new RoutedEventHandler(DraggableMenuItem_SubmenuOpened);
}

void DraggableMenuItem_SubmenuOpened(object sender, RoutedEventArgs e)
{
    IsSubmenuOpenInternal = true;
}

And that's it! The menu is now Drag-and-Drop customizable! Note that the code brought here in this article is for explanatory purposes only, and is far from perfect. Its goal is to explain the main issues and problems encountered while developing such a control, so use it as a reference only.

Hope you have found it useful, and please let me know if you did, and I'll be glad to hear about successful (preferably complete) implementations.

Creating customizable WPF drop-down menus (6)


Why dropping doesn't work on sub-menus?


This question is actually the heart of the entire process. All we did until now was quite straight-forward.
So, why doesn't it work? To solve that I tried several debugging methods, but the one that really got me somewhere was to enable Reference Code Debugging.
So I found myself debugging deep into the WPF code, finding that during the drop operation, the result of the hit-test being performed is actually 'null'(!). More than that, it seemed like the native window holding the sub-menu wasn't even there (!!). How can that be?
Well, I couldn't debug much deeper than that, but thinking about how drop-down menus work, and how drag-and-drop mechanisms work, I figured that the problem must be that the sub-menu popup was closing before the drop operation hit test takes place.

This means that if I want to be able to drop things on a sub-menu, I need to build a new mechanism that will keep it open until AFTER the drop.

Step 6: Keeping the sub-menu open


Now it is going to get clear why I insisted on inheriting MenuItem (and be sure it will get worse, as we will need to change the default control template).

We will need to introduce a new Dependency Property that will enable us to better control whenever the sub-menu is open. Let's call this property IsSubmenuOpenInternal:
public static readonly DependencyProperty IsSubmenuOpenInternalProperty =
   DependencyProperty.Register("IsSubmenuOpenInternal",
                               typeof(bool), typeof(DraggableMenuItem),
                               new FrameworkPropertyMetadata(false));

public bool IsSubmenuOpenInternal
{
   get { return(bool)GetValue(IsSubmenuOpenInternalProperty); }
   set { SetValue(IsSubmenuOpenInternalProperty, value); }
}

In the XAML code, we will change the default style (this can be easily done using "Expression Blend") so the sub-menu opening state will now bind to our new property, rather than the default one.

I will not place here the entire XAML for the new menu item class, since it is just too long.
What you will need to do is to use Expression Blend to copy the default MenuItem style, then make the following changes:
  • Change the TargetType attribute to our new class type. Remember to add the relevant namespace declaration in the XAML declaration.
  • Locate the Popup element block, and change its IsOpen binding from IsSubmenuOpen to our new IsSubmenuOpenInternal dependency property.



Important Note:
If I could, I would of course rather override the default IsSubmenuOpen property, leaving the XAML as it is. However, this is impossible (at least in accepted methods, without using reflection), so adding this property really seems like the only way to go.


Now that the new bindings are in place, we can move on to the next post :-)

Monday, April 6, 2009

Creating customizable WPF drop-down menus (4,5)


Step 4: Responding to drag hovering


Important Note:
In this part of the tutorial, we implement the draggable menu items that are static, and still in the menu, rather then the one being dragged. Keep that in mind, this is important.

We want our menus open whenever an item is dragged over them. The simplest solution would be to override the OnDragEnter method, and set the IsSubmenuOpen property to true.
This will work for now, but we will have to change that later, when we get to the drop-handling part.
Anyway, for now:
protected override void OnDragEnter(DragEventArgs e)
{
    IsSubmenuOpen = true;
    e.Handled = true;
}

Step 5: Handling drops


First we must accept drops. Lets implement the constructor:
public DraggableMenuItem()
{
    AllowDrop = true;
}

This code snippet set our draggable menu item to accept drops. Without this, it wouldn't be possible to drop anything on it, so we wouldn't be able to customize our menu.
Next we need to catch the drop operation, and perform the item movement logic. Of course we shall override and implement OnDrop. Note that we will need to extract the item being dragged from the DragEventArgs, and if it is a DraggableMenuItem, remove it from its current position, and place it just before the drop target:
protected override void OnDrop(DragEventArgs e)
{
    DraggableMenuItem draggedItem = (DraggableMenuItem)e.Data.GetData(typeof(DraggableMenuItem));
    DraggableMenuItem parentMenuItem = Parent as DraggableMenuItem;
    Menu parentMenu = Parent as Menu;
    ItemsControl itemsControl = Parent as ItemsControl;
    if (draggedItem != null && (parentMenuItem != null || parentMenu != null)) 
    {
        int i = itemsControl.Items.IndexOf(this);
        ItemsControl draggedItemParent = draggedItem.Parent as ItemsControl;
        if (draggedItemParent != null) 
        {
            draggedItemParent.Items.Remove(draggedItem);
        }
        itemsControl.Items.Insert(i, draggedItem);
        e.Handled = true;
    }
    base.OnDrop(e);
}

First attempt to test it all


Generally, while things don't look as nice as they can be, and might still be somewhat buggy, it looks like things should work.
Testing it reveals that dropping items on the menu bar level does work. However, dropping things on open sub-menus doesn't!
I will review the reason for that on the next post.

Creating customizable WPF drop-down menus (3)


Step 3: Dragging items around


Once we have figured out how to detect the drag, we need to perform the actual dragging. Moreover, we want the menu to respond while we move around - hovering over a menu should cause it sub menu (if any) to open.

We will use the System.Windows.DragDrop helper class to perform the actual dragging.
The main method in the DragDrop class is DoDragDrop. This method is used to initialize a drag-and-drop session, perform the actual drag-and-drop operations, and returns the effect.

Initializing a drag-and-drop session


The DoDragDrop method takes 3 parameters:
  • A drag source (which will be our draggable menu item),
  • A data object, and
  • The allowed effects.

So as I mentioned, the drag source will be our draggable menu item. Since the code will be written as part of that menu item, we will just place there 'this'.
Our data source, while can be anything at all (as it is of type object), should be of type System.Windows.IDataObject, since otherwise it will be wrapped with a DataObject.
The best thing to do in this case would be to create a DataObject, and give it a unique name (or type), and the data itself. In our case, the data is the draggable menu item we'll be dragging, so the best unique id would be its type.
The only allowed effect, in our case, is the move effect, as this is what we want to do (at least for now) - move menu items from one place to another.

So if we implement the DoDragging method we left empty before:
private void DoDragging()
{
    IsDragging = true;
    DataObject dataObj = new DataObject(typeof(DraggableMenuItem), this);
    DragDrop.DoDragDrop(this, dataObj, DragDropEffects.Move);
    IsDragging = false;
}

Note that I raise the IsDragging flag before the dragging process begins, and lower it immediately afterwards. One reason for that is to prevent dragging to begin on other draggable menu items. Other reasons will become clear in the following posts.

Creating customizable WPF drop-down menus (2)


Step 2: Detecting drag


Drag will start when the user had pressed the mouse button on an item and moved it enough distance in pixels while being pressed.
So, we need to know where the mouse was pressed, then track it all time it is pressed until it moves far enough:
public class DraggableMenuItem : MenuItem
{
    private Point m_dragStartPoint;

    public static  bool IsDragging { get; set; }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        m_dragStartPoint = e.GetPosition(this);
        base.OnMouseLeftButtonDown(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (e.LeftButton != MouseButtonState.Pressed || IsDragging)
            return;

        Point p = e.GetPosition(this);
        if (Point.Subtract(m_dragStartPoint, p).LengthSquared < 16)
        {
            e.Handled = true;
            return;
        }

        DoDragging();
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        IsDragging = false;
        base.OnMouseLeftButtonUp(e);
    }

    private void DoDragging()
    {
    }
}
Note that the IsDragging flag is a static flag, thus shared among all instances of the DraggableMenuItem. In the code sample above we do not yet assign it. This will be done in the next steps, in addition to some other places we will need to use its value to achieve the correct behavior.

Thursday, April 2, 2009

Code Snippets (2)

After I couldn't find a decent way to implement nice, colorful code snippets inside blogger (which holds me back from posing code related articles) as I mentioned in my last post, and after checking "CopySourceAsHtml" as suggested by Asher in his comment to my last post (and didn't like it - it creates HTML I really don't want to use), I decided to go on with writing my own converter.
I used the GOLD parsing system, along with the Calitha gold parser engine to parse source code of a given grammar (grammars for GOLD can be found here), added some metadata to that grammar (currently I've only done a proof-of-concept, so everything is hard-coded) that defines how to indent and colorize (HTMLize) it, and wrote this application:

(click to enlarge)

Next will probably be adding another language (C# - currently only tried it with XML), extracting metadata to external files (should see if I can merge it with the GOLD parser grammar files, and read it from there somehow), and making things look nicer, for starters.

The code is currently not available for download, but I'll probably start a project on sourceforge for that soon. I'll post an update when I will.

Sunday, March 29, 2009

Code Snippets

It seems like blogger does not support code snippets, and that its not as easy as I thought it will be to find some converters that will be able to convert my code into nice, colorful HTML syntax I can paste.

Time to write something that does just that, I guess.

Will probably build something generic, and base on the GOLD parser. It have good base code generators for various languages, including C#, so it seems like a good place to start.

Creating customizable WPF drop-down menus (1)

In this series of articles I'll explain the process of creating a drop-down menu that can be customized using drag-and-drop.



Enough preface, now on to the job!


Step 1: A simple drop-down menu

A simple drop down menu can be built in WPF using the Menu and MenuItem classes. This can be done is XAML of course, and would look like this:
<Menu>
    <MenuItem Header = "MenuItem1">
        <MenuItem Header = "MenuItem1.1"/>
        <MenuItem Header = "MenuItem1.2"/>
        <Separator Margin = "0,0,0,0" Height = "Auto"/>
        <MenuItem Header = "MenuItem1.3">
            <MenuItem Header = "MenuItem1.3.1"/>
        </MenuItem>
        <MenuItem Header = "MenuItem1.4">
            <MenuItem Header = "MenuItem1.4.1"/>
        </MenuItem>
    </MenuItem>
    <MenuItem Header = "MenuItem2"/>
    <MenuItem Header = "MenuItem3" HorizontalAlignment = "Right">
        <MenuItem Header = "MenuItem3.1"/>
        <MenuItem Header = "MenuItem3.2"/>
        <Separator Margin = "0,0,0,0"/>
        <MenuItem Header = "MenuItem3.3">
            <MenuItem Header = "MenuItem3.3.1"/>
        </MenuItem>
    </MenuItem>
</Menu>
This menu, however, cannot be customized using Drag-and-Drop by the end-user at runtime. In order to do that, we need to implement a dragging mechanism.

Fortunately, WPF has a built-in Drag-and-Drop assistance class, that does the hard parts for us. All we need to do is to detect when we want to begin dragging, then pass it on to the Drag-and-Drop helper. Oh, and we also need to handle the drop :-)

Important Note:
The MenuItem class is limited in its behavior. In order to prepare to some of the more advanced steps, I'll need to inherit MenuItem to my own class, that will allow me to do the needed operations.
I'll call this class DraggableMenuItem, and let it implement internally everything the draggable menu items does.

Thursday, March 26, 2009

Floating Point

A friend asked me today why a cast from double to int in C# would take a whole microsecond.
To answer that, we have to understand how cast between those two primitive types work, and how each of them is represented in memory.

So, how an integer is represented in memory? Quite straight forwards: simple run of bits (8, 16, 32 or 64, depending on the actual type - byte, short, int and long respectively)

The single and double data types are more complex. These are floating point types, and as such, they represent a number which decimal point isn't in a fixed position, but may change according to the represented number.
This leads to a situation where we can represent either really small and very accurate numbers, or very large and inaccurate numbers.

How is this done? By separating the given memory to 3: one bit for sign, 11 bits for exponent, and the rest 52 bits for the mantissa (the significant value, representing a fraction or an integer depending on the interpretation of the exponent).

This structure also allows to define values that are not numbers, such as NaNs (Not a Number, which is returned when you try to divide a double by a zero double), Infinity (positive and negative), and denormal numbers.

As I mentioned before, the integer data type simply store bits, straight forwards. So, simply renaming the type won't work. A computation need to be performed to resolve the represented value from the floating point number, then round the result to the nearest whole number. In addition, several tests need to be performed to handle NaNs, denormal numbers and infinities correctly. All of those operations take quite some time, so no wonder this simple, so common cast, takes a whole microsecond.

So if you have a tidious, tight loop that performs thousands of double-to-int casts, try to avoid casting. It might help improve performance.

Wednesday, March 25, 2009

Grid Computing and Charity

I bought my quad-core computer about a year ago, since I planned to use it for massive programming and/or editing (video/image) work.
However, I started to work in a 2 hours distance from home (at least with public transportation), so for a long time the computer was simply shut-down, collecting dust.
Until I decided that if I spent so much money to buy such a strong computer, at least let it do something useful. I didn't have anything useful for it, so I decided to find something online.
I remembered SETI@Home was a good way to share my computer free cycles to do something useful, but Searching for Extra Terrestrial Intelligence really didn't sound like something worth investing in.
So I looked for similar programs that I can relate to, and found World Community Grid, which is a project dealing with finding cures for cancer and AIDS, helping solve hunger problems by finding more nutritious foods, finding cleaner energy sources, etc.


Another thing I have found was, that the entire grid computing for science and personal usage subject was reformed, and the main computation management client software used is BOINC.
With BOINC you can connect to your favorite grid computing project and share your computer resources. BOINC will download work parts to run on your computer, then upload the results when they are ready. The project server than add them to one large computational task until a result is achieved. Some servers grant points for time spent on computing and results that are returned, making things a bit more competitive.

Anyone can use BOINC to perform very long computations. Scientists can apply to volunteer computing, while companies can set up a BOINC server to run grid computing within the organization.

I, anyway, is using my BOINC client at home and at work, giving all those unused cycles to help solve those important issues. The next time I'll read in the newspaper that scientists has found a new cure, and used grid computing technology, I'll know I gave my share :-)

Milk

In the last couple of days we were out of milk at home. I forgot to buy some last time I went shopping for groceries, and the milk we still had left was running out.
This of course caused a severe inconvenience as I had to choose between having a bowl of cereals or saving some milk for tomorrow morning's coffee.

Since dinners for me are usually based on cereals as I am usually too tired (lazy?) to make something decent to eat (like a fried egg with some toasted bread and some salad), having to choose between cereals and coffee is really inconvenient. Problem gets worst when I don't have to choose anymore when there is not enough milk for a bowl of cereals :-S



So, the conclusion is not to forget the milk next time. And always buy enough. Not sure it's good for me, but hey, it makes my life easier :-)

Tuesday, March 24, 2009

Broken Glasses

My glasses got broken the other day, while I was cleaning them.
The part that holds the little plastic thingies that holds the glasses on the nose got detached.
Luckily I have a relatively low glasses number, so I can see fine without them for short distance (especially the screen), but driving is more problematic.
Anyways, I made a quick temporary fix using sellotape until I get them fixed or replaced.


The blurry thing on the bridge between the lenses is the sellotape.

Multitouch Tables


I've been messing around on and off in the past year or so, learning about multipoint input techniques, and trying to implement some in .Net.
Aspired by Microsoft Surface and NUI Group, I tried to build my own test-bed. So far, the success is, to say the least, limited :-)

It is made of a carton box used to accommodate my vacuum cleaner, a 5mm clear perspex board I bought for too much money (these things really are expensive), a web camera I once bought (I tend to buy a new one for experiments every few months or so, usually in the local supermarket) and a 48 LEDs infrared projector I bought on eBay.

Problem was I could never set it up right, although I had some success doing fiducial recognition and tracking completely in .Net. The only problem was performance, mainly of the filters: I tired to implement a Constant Time Median Filter, but even though this is the most efficient method to implement Median Filter, it still runs too slow (about 1 FPS), even on my computer (Intel QuadCore Q6600).
Then I tried to change the implementation to use Mono SIMD, but the camera code (COM) didn't work and the program didn't run, and then I put it aside.

Funny thing is, that the thing I really want to do is to develop controls and infrastructure for such a device, but I don't want not to be able to experiment with it myself, so I just don't get there.
I did write some demos to see I can get the basics to work (two markers that I can drag around with the mouse, representing two fingers), and using touchlib I also managed to play around with some more complex techniques, and finally got a nice picture scaling and rotating on screen. But setting up the environment was such a pain, plus I wanted to see if I can do it all purely in .Net.

To sum things up - I do think it is possible, but it will require some more work. I would either get the camera working in mono one day, or maybe microsoft will release a service pack for .net that implements SIMD, I'll learn to use my GPU for that task (CUDA vision, perhaps?), or try to do all that magic directly on Linux.