DCSIMG
Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

A UniformGrid for Silverlight/Windows Phone

Published at Feb 07 2012, 10:00 PM by pavely

The UniformGrid panel in WPF has some useful features, especially as an items panel in an ItemsControl. I blogged about the usefulness of the UniformGrid here. But what about Silverlight? It has no UniformGrid, but we can create one as a custom panel. This would be usable in Silverlight for the desktop and for Windows Phone, and would be a simple enough example to show in one post.

The layout process

In WPF/Silverlight, layout is a two step process. The first step is Measure: the panel asks each child it’s hosting what size it would like to be, given the available space for the panel. The second and final step is Arrange: the panel tells every child where it’s hosted and the final size it’s given; this is not debatable. The child element has to cope.

Creating a custom panel

A custom panel is created in much the same way in Silverlight as it is in WPF. There are two methods that we must override: MeasureOverride and ArrangeOverride (yes, I know, the names suck):

  1. public class UniformGrid : Panel {
  2.     protected override Size MeasureOverride(Size availableSize) {
  3.         return base.MeasureOverride(availableSize);
  4.     }
  5.  
  6.     protected override Size ArrangeOverride(Size finalSize) {
  7.         return base.ArrangeOverride(finalSize);
  8.     }
  9. }

 

Properties

Before we get to the overriding part, let’s add some properties. We want a Rows and a Columns property, which should be simple enough. We’ll use the “propdp” Visual Studio code snippet to generate the boilerplate code for registering a dependency property and just replace UIPropertyMetadata with PropertyMetadata, as the former exists in WPF only. This is how it would look:

  1. public int Columns {
  2.     get { return (int)GetValue(ColumnsProperty); }
  3.     set { SetValue(ColumnsProperty, value); }
  4. }
  5.  
  6. public int Rows {
  7.     get { return (int)GetValue(RowsProperty); }
  8.     set { SetValue(RowsProperty, value); }
  9. }
  10.  
  11. public static readonly DependencyProperty ColumnsProperty =
  12.      DependencyProperty.Register("Columns", typeof(int), typeof(UniformGrid), new PropertyMetadata(1, OnColumnsChanged));
  13.  
  14.  
  15. public static readonly DependencyProperty RowsProperty =
  16.      DependencyProperty.Register("Rows", typeof(int), typeof(UniformGrid), new PropertyMetadata(1, OnRowsChanged));

The OnColumnsChanged and OnRowsChanged are just there to make sure the properties have the value greater than zero:

  1. static void OnColumnsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) {
  2.     int cols = (int)e.NewValue;
  3.     if(cols < 1)
  4.         ((UniformGrid)obj).Columns = 1;
  5. }
  6.  
  7. static void OnRowsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) {
  8.     int rows = (int)e.NewValue;
  9.     if(rows < 1)
  10.         ((UniformGrid)obj).Rows = 1;
  11. }

 

MeasureOverride

This method accepts the available space from the panel’s parent. It’s actually possible to get double.PositiveInfinity for the Width and/or Height of the received size. This would mean the panel can have as much space as it wants (a classic example of this is if the panel is hosted in a ScrollViewer, which usually gives infinite space to its child – I say usually, because it depends on the Horizontal/VerticalScrollBarVisibility properties… but that’s a topic for another post).

The method must call the Measure method on each child. This is required, because the child may depend on it. In our case, we don’t really care, because every child is going to get equal space – still, we must call Measure.

We have to return the size we’re actually going to use, and it must not be double.PositiveInfinity in the Width or Height. Here’s a simple implementation:

  1. protected override Size MeasureOverride(Size availableSize) {
  2.     foreach(UIElement child in Children)
  3.         child.Measure(availableSize);
  4.  
  5.     return new Size(double.IsPositiveInfinity(availableSize.Width) ? 0 : availableSize.Width,
  6.         double.IsPositiveInfinity(availableSize.Height) ? 0 : availableSize.Height);
  7. }

We probably don’t need much more than that for the UniformGrid. Note that WPF’s UniformGrid has another property, FirstColumn, that we won’t implement.

ArrangeOverride

In this phase, the panel tells the children what they get. Here’s a possible implementation:

  1. protected override Size ArrangeOverride(Size finalSize) {
  2.     Size cellSize = new Size(finalSize.Width / Columns, finalSize.Height / Rows);
  3.     int row = 0, col = 0;
  4.     foreach(UIElement child in Children) {
  5.         child.Arrange(new Rect(new Point(cellSize.Width * col, cellSize.Height * row), cellSize));
  6.         if(++col == Columns) {
  7.             row++;
  8.             col = 0;
  9.         }
  10.     }
  11.     return finalSize;
  12. }

We calculate the size of each “cell” and tell each child its exact position and size by calling the UIElement.Arrange method, passing in a Rect structure.

And we’re basically done. Note that the implementation is not foolproof: if an element has a Collapsed Visibility, we still give it space. We should really skip it. I’ll leave that as an exercise to the motivated reader.

Testing

Let’s use this in a Silverlight Windows Phone application that would show the user’s pictures library in an ItemsControl that uses our UniformGrid. (I know, we can use a WrapPanel from the Windows Phone toolkit to get a similar effect if we’re careful).

Here’s the basic XAML:

  1. <ItemsControl x:Name="_pics">
  2.     <ItemsControl.ItemsPanel>
  3.         <ItemsPanelTemplate>
  4.             <local:UniformGrid Rows="5" Columns="4" />
  5.         </ItemsPanelTemplate>
  6.     </ItemsControl.ItemsPanel>
  7.     <ItemsControl.ItemTemplate>
  8.         <DataTemplate>
  9.             <Grid Margin="4">
  10.                 <Image Source="{Binding Image}" />
  11.                 <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"
  12.                            Text="{Binding Name}" FontSize="16" />
  13.             </Grid>
  14.         </DataTemplate>
  15.     </ItemsControl.ItemTemplate>
  16. </ItemsControl>

I’m assuming we’ll bind to a collection that has a Name and Image properties. The ItemsPanel property is using our UniformGrid. “local” is the XML namespace prefix I selected.

All that’s left now is get the pictures and bind. We’ll do that in the MainPage constructor:

  1. public partial class MainPage : PhoneApplicationPage {
  2.     public class PictureInfo {
  3.         public string Name { get; set; }
  4.         public ImageSource Image { get; set; }
  5.     }
  6.  
  7.     public MainPage() {
  8.         InitializeComponent();
  9.  
  10.         var library = new MediaLibrary();
  11.         var pictures = library.Pictures;
  12.         var display = from p in pictures
  13.                           select new PictureInfo {
  14.                               Name = p.Name,
  15.                               Image = GetImage(p)
  16.                           };
  17.         _pics.ItemsSource = display;
  18.     }
  19.  
  20.     private ImageSource GetImage(Picture p) {
  21.         var bmp = new BitmapImage();
  22.         bmp.SetSource(p.GetThumbnail());
  23.         return bmp;
  24.     }
  25. }

This is the entire MainPage code behind. We use the MediaLibrary class (from Microsoft.Xna.Framework) to get the pictures using the Pictures property. We can’t bind directly to this collection, because the images are not supplied as properties of type ImageSource; in fact, they’re methods. So, we need a little bit of LINQ projection to transform this collection to a new one with properties, suitable for binding. That’s where the GetImage method comes in. It calls Picture.GetThumbnail() and builds a BitmapImage to hold the result (an ImageSource derivative).

The PictureInfo class is our little helper to hold the data. If you wander why an anonymous type wasn’t used, that’s because Silverlight doesn’t like using internal types (which anonymous types always are) when data binding. So, I had to create a new public type.

Running this in the emulator results in something like this (thanks to some default pictures the emulator comes with):

image

A New Android Game in Town (by my brother)

Published at Feb 05 2012, 10:36 PM by pavely

Anyone who has ever written a game knows it’s hard to get it done from start to finish. Sure, I can put on a demo of some game I’ve created in several hours. But creating all the graphics, sound, animation, levels, transitions, scoring, etc, from start to finish is quite a challenge, especially for a single developer.

That’s why I’m very proud of my young brother, Yaniv, that has worked hard for the past 10 months (while maintaining a proper day job!) on an awesome  fun game called Micro Wars, targeted for the Android platform. This game plays especially well on tablets, with their bigger screen and powerful processors.

Here’s the trailer on you tube:

 

The demo version (free) can be downloaded from here: https://market.android.com/details?id=com.psychocat.microwars.demo

The paid version is here: https://market.android.com/details?id=com.psychocat.microwars

There’s also a facebook page: http://www.facebook.com/pages/Micro-Wars-HD/326100820757989

Great job, Yaniv!

Next Windows Devices User Group Meeting

Published at Feb 05 2012, 10:19 PM by pavely

The second meeting of the Windows Devices User Group will be held on February 28th, at 17:00, Microsoft Offices in Ra’anana. The registration link and detailed agenda is here: http://windowsphonenavandlifecycle.eventbrite.com/

In this meeting we’ll talk about page navigation and the application lifecycle, which got a bit more complicated (but performs better) in the “Mango” release. We’ll also hear a “real life story” of porting an application to Windows Phone.

See you there!

WPF Tip: Displaying Images in different Pixel formats

Published at Jan 30 2012, 12:25 AM by pavely

If we want to show an image in WPF, we typically use an Image element and connect its Source property to some image resource within our project:

  1. <Image Source="Penguins.jpg" />

The Source property is not a string, it’s an ImageSource – an abstract type with several concrete implementations that provide a “real” image source. The above markup works thanks to the help of a type converter, that makes the source a BitmapImage – one of the simplest sources, that presents the image as is.

What if we wanted to show the original image in a different pixel format, such as a gray scale image?

The typical (and powerful) approach would be to use a pixel shader. What is a pixel shader? Briefly, it’s a little program that executes on the graphic card (GPU), that can transform an incoming pixel to a different color, based on some algorithm. There are other kinds of shaders, but we won’t discuss those here, as they are not relevant to WPF.

These shaders are not written in C#, mind you – I wish that would be possible (maybe in the future). They are typically written in a Domain Specific Language (DSL) called High Level Shader Language (HLSL), that was created for DirectX (and used by XNA as well). This language syntax is based on C, with added features relevant to shaders. Writing shaders is well beyond the scope of this post, but let’s see a simple gray scale shader at work:

  1. sampler2D implicitInput : register(s0);
  2.  
  3. float4 MainPS(float2 uv : TEXCOORD) : COLOR
  4. {
  5.     float4 src = tex2D(implicitInput, uv);
  6.  
  7.     float4 dst;
  8.     dst.rgb = dot(src.rgb, float3(0.3, 0.59, 0.11));
  9.     dst.a = src.a;
  10.     
  11.     return dst;
  12. }

What this basically says, is that given an input 2D coordinate (uv), we need to return a COLOR for that coordinate. The color (dst) is comprised of a dot product between the source color (src.rgb) and a weighted vector, that is typically used to convert to gray scale (0.3, 0.59, 0.11). The computation (in an easier form, removing the “dot” notation) is:

gray level = red * 0.3 + green * 0.59 + blue * 0.11

This value is fed into the destination R,G and B components (when R=G=B we see gray), and the alpha component is copied as is.

What do we do with this file? Typically this is saved with a “.fx” extension, and then it needs to be compiled into binary form, suitable for execution on the GPU using the effects compiler (fxc.exe) that is part of the DirectX SDK. The command line for this looks something like this:

fxc /T ps_2_0 /E MainPS /Fo gray.ps gray.fx

This says that we want to use pixel shader level 2.0 (there are others, an fxc.exe also compiles other shaders, such as vertex shaders), the main function is called MainPS and our output should be gray.ps. The input is the last argument, gray.fx.

In the sample project, I’ve already compiled the file. The result is typically named with a “.ps” extension. This PS file is then added as a resource to the project.

We’re not done, yet…

The next thing to do is create a wrapper class, deriving from ShaderEffect, that loads the shader and initializes it. This new class can then be used as the value of the UIElement.Effect property. Here’s what the class looks like:

  1. class GrayscaleEffect : ShaderEffect {
  2.     public GrayscaleEffect() {
  3.         PixelShader = new PixelShader();
  4.         PixelShader.UriSource = new Uri("/Effects/Gray.ps", UriKind.Relative);
  5.         UpdateShaderValue(InputProperty);
  6.     }
  7.  
  8.     public static readonly DependencyProperty InputProperty =
  9.         ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(GrayscaleEffect), 0);
  10.  
  11.     public Brush Input {
  12.         get { return (Brush)GetValue(InputProperty); }
  13.         set { SetValue(InputProperty, value); }
  14.     }
  15. }

I will not get into a full explanation regarding the Input property and its use here. The pixel shader is initialized from the PS file resource. Now we can apply it to any element (not just an image):

  1. <Image Source="Penguins.jpg">
  2.     <Image.Effect>
  3.         <local:GrayscaleEffect />
  4.     </Image.Effect>
  5. </Image>

This works well (and actually works in Silverlight as well), but for a gray scale effect, there is an easier way in WPF: use the FormatConvertedBitmap class as the ImageSource and set the desired pixel format (using the DestinationFormat property) – we can select one from the PixelFormats class that exposes a set of static properties as PixelFormat objects.

Here’s a roughly equivalent way to get a gray scale image:

  1. <Image>
  2.     <Image.Source>
  3.         <FormatConvertedBitmap Source="Penguins.jpg" DestinationFormat="Gray8" />
  4.     </Image.Source>
  5. </Image>

The attached sample shows the penguins image in four ways: the original, with the gray scale shader, with a black & white pixel format and a gray8 pixel format as above. This is the result:

image

Using FormatConvertedBitmap is certainly easier (but a lot less flexible) in these scenarios.

From Enumerable to Observable

Published at Jan 18 2012, 12:56 PM by pavely

The IEnumerable<T> interface represents a collection of objects of type T, and is used heavily thanks to the C# foreach construct. Better yet, in the LINQ world, this is the interface that is “extended” via extension methods by the System.Linq.Enumerable class. This makes IEnumerable<T> both easy to use as well as powerful. But is it the best interface for getting data out of a possible collection?

Recap: what is IEnumerable<T>?

IEnumerable<T> has only one method: GetEnumerator(), that returns an enumerator (what else?), sometimes called an iterator.

IEnumerable<T>
  1. public interface IEnumerable<out T> : IEnumerable {
  2.     new IEnumerator<T> GetEnumerator();
  3. }

This enumerator implements the IEnumerator<T> interface. This one inherits from the old .NET 1.x IEnumerator interface, like so:

  1. public interface IEnumerator {
  2.     bool MoveNext();
  3.     void Reset();
  4.     object Current { get; }
  5. }
  6.  
  7. public interface IEnumerator<out T> : IDisposable, IEnumerator {
  8.     new T Current { get; }
  9. }

Disregard the “new” and “out”, as they are not important for this discussion.

So what does foreach do? It calls MoveNext() in a while loop as long as it returns true, and uses the Current property as the value used with the loop body. This is a pull model, each call to MoveNext() “pulls” the next data item, to be available via the Current property.

(the Reset() method is not typically used, so we’ll skip that one).

So what’s wrong with this model? It turns out this is a great model, as long as we don’t have to wait significantly for the next item to arrive. If it may take a while, or even if there never is a next item, we’re in trouble. MoveNext() will block. For many scenarios this is unacceptable, or at least undesirable.

Let’s turn things around

If this is a pull model, why don’t we try a push model? A client says to a provider of data: call me when you have something; otherwise, don’t bother me. if there is never a new item, nothing is wasted and no blocking is necessary. Effectively, we’re working asynchronously, or at least we can have the opportunity to do so.

Let’s try to reverse both interfaces, from a pull to a push model. First is IEnumerator<T>: We need to “reverse” MoveNext() and Current.

MoveNext() returns bool, so its reverse would be a method that accepts a bool.

Current is a read only property, so its “reverse” would be a write only property.

Let’s build our new interface (let’s call it IPusher<T> for now):

  1. public interface IPusher<T> {
  2.     void MoveNext(bool ok);
  3.     T Current { set; }
  4. }

MoveNext here seems redundant – it has no added value. It’s used to indicate completion in IEnumerator<T>, but it really isn’t appropriate here. We need another method to signal that there is no more data:

  1. public interface IPusher<T> {
  2.     void OnCompleted();
  3.     T Current { set; }
  4. }

Write only properties are usually frowned upon, so let’s turn this into a method called OnNext:

  1. public interface IPusher<T> {
  2.     void OnCompleted();
  3.     void OnNext(T value);
  4. }

How would we be notified of an error condition? With IEnumerator<T>, MoveNext() can throw an exception. In the push model, we need a method to indicate that:

  1. public interface IPusher<T> {
  2.     void OnCompleted();
  3.     void OnNext(T value);
  4.     void OnError(Exception error);
  5. }

Great! We have a client interface that can be notified when data is available, when it’s all done and if there is any error. This interface, in fact, exists in .NET 4, called IObserver<T>:

  1. public interface IObserver<in T> {
  2.     void OnCompleted();
  3.     void OnNext(T value);
  4.     void OnError(Exception error);
  5. }

 

What now?

We have an observer; now we need something to observe; something that provides data. This is exactly what IEnumerable<T> signifies in the pull model. Now we need to build its twin in the observer world – an observable.

For all of you design patterns buffs – this is the famous “observer” pattern classically defined by the “Gang of Four” (GoF) in their 1994 famous book. In that pattern, there is a Subject that is the source of the data, on which a pair of methods, Attach and Detach are defined, allowing an observer to subscribe and unsubscribe. We need something similar in our definition of the IObservable<T> interface:

  1. public interface IObservable<T> {
  2.     void Attach(IObserver<T> observer);
  3.     void Detach(IObserver<T> observer);
  4. }

This is certainly possible, but maybe we can remove the Detach method, by returning something from Attach that can be used to unsubscribe:

  1. public interface ICookie {
  2.     void Detach();
  3. }
  4.  
  5. public interface IObservable<T> {
  6.     ICookie Attach(IObserver<T> observer);
  7. }

We just need a detach, perhaps we can leverage something already existing in .NET and not invent yet another interface. Hint: IDisposable.

Here’s the final version, renaming Attach with Subscribe, and using IDisposable.Dispose to unsubscribe:

  1. public interface IObservable<T> {
  2.     IDisposable Subscribe(IObserver<T> observer);
  3. }

This is exactly how the real IObservable<T> is defined in .NET 4.

Again, what now?

Now we have a generic mechanism to get data out of some provider via push. We subscribe to the provider with an implementation of IObserver<T> and will get data when it’s available.

.NET 4 has no implementations for IObservable<T> nor IObserver<T> – but the relatively recently released (well, actually, a first service pack has already been released) of the Reactive Extensions (Rx) provides various implementations for both interfaces. Coupled with LINQ support, this is one powerful library.

Hopefully I will discuss Rx in future posts. For now, you can go ahead and download it, look at samples, docs, etc.

First Meeting of the Windows Devices Israel User Group

Published at Jan 17 2012, 10:21 AM by pavely

Yesterday evening we’ve held the first meeting of the new Windows Devices user group at Microsoft offices in Ra’anana. This first meeting was dedicated to Windows Phone 7. Elad and I had a lot of fun and we hope you guys had fun as well and learned something along the way. What we’ve done is talk about the Windows Phone platform in general, its capabilities, the tools used to write applications and games, while showing a few demos. We tried to answer as many general questions as we could, and those questions are definitely a basis for future meetings.

I’ve attached my basic presentation. The source code for the XNA game I demoed in the session can be found in these blog posts(part 1, part 2, part 3). You can find our announcements, and hopefully discussions at the new Windows Devices Israel User Group on linkedin. Feel free to register, so you’d be notified of new meetings and other such stuff.

As a reminder, and for those who didn’t attend the meeting, we announced a competition, for which a Windows Phone device is the first prize, to write and publish 3 applications that would pass 3000 downloads (total). The first person to achieve this – wins the phone.

Lastly, if anyone wants to be a presenter in such a meeting, or knows someone who does, please contact Elad or myself via email (our emails is on the first slide of the attached slide deck) or the group in linkedin.

Good luck, and more importantly, have fun!

Slides

Chinese Hotel with no Tea?

Published at Jan 13 2012, 09:25 PM by pavely

I was in Shanghai, China this past week, teaching an advanced .NET class at a John Bryce customer’s site. The training went well, and is not the topic of this post.

I was in China once before, some 7+ years ago for a non-work related activity – learning Tai Chi Chuan (old Chen style) for a few weeks with a well known master (Master Ma-Hong, 78 years old at the time, if that means anything to anyone. He learned the style from the 5th generation member of the Chen family that invented the style – no small accomplishment; but that’s a story for another post…).

One of the well known China marks is the tea. Tea is everywhere (there are many many kinds, mind you). As soon as you step to some restaurant (no matter how simple or how fancy), you’re automatically offered tea, always free (as far as I could determine). This is one of those things I like very much (I’m a tea buff; I don’t drink coffee. Yes, I know, pretty strange…).

I was staying at the ZTE hotel in Shanghai, that is a real contradiction. The lobby is impressive and your expectations automatically climb a notch. The room looks pleasant enough as well.

There are some peculiarities within the hotel (e.g. no room service, no room mini-bar, a gym that has no training equipment except 2 benches on which you can’t do much but sit, although there is a table tennis room… but I digress).

The biggest peculiarity is the absence of coffee or tea or any kind of fruit juice at breakfast. It may not seem like a big deal, but it was a big deal for me. All there was to drink was milk (arrggghh) and something a waiter managed to call “bean juice”, by which he probably meant some soy drink or something like that, judging from the color. There was no way to get tea. Tea! The hallmark of China. Nowhere to be found. Here’s a picture to clarify:

WP_000352

This is it. White stuff; no tea (or coffee or orange juice) at all.

No more ZTE for me!

Using the Async CTP With Windows Phone

Published at Jan 07 2012, 12:05 PM by pavely

The Async CTP that exposes C# 5.0 features to be used with asynchronous programming is not just for the full .NET Framework. There are versions for Silverlight (4 and 5) and even Windows Phone (which can be viewed as Silverlight 4, but has a separate supporting assembly).

To demonstrate, I’ve adapted my sample of the Mandelbrot set to Windows Phone, while taking advantage of the async features to keep the UI responsive.

After creating the initial Silverlight for Windows Phone project, I’ve added a reference to the async CTP library, which can be found under {MyDocuments}\Microsoft Visual Studio Async CTP\Samples:

image

You can see the other versions for Silverlight (4 with no suffix, and 5) and of course, the desktop one (without any suffix).

The calculation and rendering loop looks like this:

async void RunMandelbrotAsync(Complex from, Complex to, CancellationToken ct) {
	int width = _bmp.PixelWidth, height = _bmp.PixelHeight;
	double deltax = (to.Real - from.Real) / _bmp.PixelWidth;
	double deltay = (to.Imaginary - from.Imaginary) / _bmp.PixelHeight;
	try {
		int[] pixels = new int[width];
		for(int y = 0; y < height; y++) {
			if(ct.IsCancellationRequested)
				break;
			await TaskEx.Run(() => {
				for(int x = 0; x < width; x++) {
					pixels[x] = MandelbrotColor(from + new Complex(x * deltax, y * deltay));
				}
			}, ct);
			if(!ct.IsCancellationRequested) {
				Array.Copy(pixels, 0, _bmp.Pixels, y * width, pixels.Length);
				_bmp.Invalidate();
			}
		}
	}
	catch(TaskCanceledException) {
	}
}

The code is somewhat different than the original version. First, the Parallel class does not exist (yet…) in the Windows Phone API, so I replaced it with a regular for loop. The asynchrony is achieved by running the inner loop using a separate Task and “awaiting” it. Another twist added in this version is the ability to cancel the operation.

The TaskEx.Run is a kind of shorthand to creating a Task, calling Start and returning that Task (in the final version it would be part of the Task class).

Other differences in the code result from more API differences between Silverlight and WPF, such as the WriteableBitmap class. No pixel format can be specified in Silverlight (including WP7), and is always ARGB, so I had to change the MandelbrotColor method to return a matching pixel format:

int MandelbrotColor(Complex c) { int color = 255; Complex z = Complex.Zero; while(color > 0 && z.Real + z.Imaginary < 4) { z = z * z + c; color--; } return (int)((255 << 24) | (color << 16) | (color << 8) | color); }

Note also the Complex type. This does not (yet…) exist in Silverlight! I’ve actually duplicated the code in the .NET 4 Complex type by dumping it as source using Reflector, and then removing the unsupported stuff (Serializable and and some other unsupported attributes, as well as a conversion from a BigInteger). This is possible because a Complex is basically a mathematical entity, and does not use the framework in any special way.

You can run the application on the emulator or a real device. Doing a double-tap (double click in the emulator) causes the resolution to increase (building slower). To get a double tap, I’ve used the new DoubleTap event introduced in Windows Phone 7.1 (“Mango”).

This is how it looks initially (the emulator is rotated):

image

Tapping and dragging a rectangle allows zooming in on a specific area. The resolution is reset, so more double taps are required to increase the resolution again. Here’s how it looks after double-tapping twice:

image

This is while selecting a zoom rectangle:

image

And the result (after 2 more double taps):

image

The laptop’s new life with SSD

Published at Jan 05 2012, 06:37 PM by pavely

A few days ago I upgraded my hard drives in my laptop to SSD (Solid State Drive). This is one of those things that once you do it – there’s no turning back; you’ll never consider using a “regular” spinning hard disk.

Hard disk speed is crucial to a developer – Visual Studio 2010 is a hungry I/O beast, and when various extensions are installed, things get worse.

My laptop is no woos - it’s an Alienware m17x-R2, equipped with a Core-i7 processor, 8GB of RAM and an ATI Radeon 5870 card (DirectX 11 capable). This may not seem too much now (there are by now stronger Alienware machines…), still it’s a formidable machine (being not so young - about 18 months old.

Previously, my Windows Experience Index was 5.9 (due to the disks…) Now (after a dual raid-0 300GBx2 SSD Intel drives) it looks like this:

image

It seems the disks have the highest score! The CPU has now the lowest score. (Maybe it’s time to upgrade that as well?…)

These are not just numbers. The feeling and reality is much much improved!

That’s it. I’m done with those spinning thingies. Long live SSD!

Calculating PI in .NET

Published at Dec 30 2011, 10:31 PM by pavely

I always loved mathematics. Although I’m certainly not a mathematician by profession, I’m always intrigued and inspired by math’s pureness and cleverness. One of the simplest and fascinating aspects of math is the number PI. Described simply as the ratio of a circle’s circumference to its diameter, it’s a constant with infinite digits after the decimal point and most importantly, non repeating (at least as far as I know).

There are many ways to calculate PI, as evident within the PI Wikipedia link. I wanted to see how I can get a large number of digits of PI with a C# program.

As every high school kid knows, PI in radians is equal to 180 degrees, or half a circle. And since the tangent of 45 (PI/4) degrees is 1, PI can be calculated like so:

PI/4 = arctan(1) or PI = 4 * arctan(1)

This looks simple enough. Just need to calculate the arc (inverse) tangent of 1. Of course, a method like Math.ATan is out of the question. It (and its kind) work with doubles, which gives a fixed 15 digit precision, while we want arbitrary precision.

How should we calculate the arc tangent of 1? One option is to use the Taylor series expansion (valid for |x|<= 1):

arctan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9 –…

The ^ sign indicates “to the power of”. If x is 1 (as is in our case), the series is simplified:

arctan(1) = 1 – 1/3 + 1/5 – 1/7 + 1/9 –…

Nothing to it, right?

But how do we calculate that? Again, using just doubles will get us nowhere better than Math.PI. We need an arbitrary sized floating point number. This does not exist in .NET (at least not yet). So, we’ll take the next best thing: the BigInteger type introduced in .NET 4. This is an arbitrarily large integer; all we have to do is use the above formula, but multiply everything by some large BigInteger, such as 10 to the 100th power, and interpret the final result as being larger by that factor. Let’s write a PI calculating method based on this series:

arctan(1)*4 as PI
  1. private static BigInteger CalculatePiSlow(int iterations, int digits) {
  2.     var mag = BigInteger.Pow(10, digits);
  3.     var sum1 = Enumerable.Range(0, iterations / 2).Select(i => i * 4 + 1).Aggregate(BigInteger.Zero, (sum, i) => sum += mag / i);
  4.     var sum2 = Enumerable.Range(0, iterations / 2).Select(i => i * 4 + 3).Aggregate(BigInteger.Zero, (sum, i) => sum += mag / i);
  5.     return 4 * (sum1 - sum2);
  6. }

If you’re not familiar with the LINQ Aggregate operator, here’s a brief explanation: it’s the generic way operators like Sum and Average work: we use an “accumulator”, starting at BigInteger.Zero, and decide with the second argument (a delegate) what to do with the incoming number. The Sum operator does not work here because there is no overload that takes a BigInteger (although it would be simple enough to add such an extension method. I’ll leave it as an exercise for the interested reader).

iterations indicates the number of terms we wish to take into account and digits indicates the maximum digits we wish to calculate. Calling this method with 1000 iterations and just 20 digits yields the following:

image

I’ve printed Math.PI as a basic comparison. The result is disappointing – the fourth digit is wrong (“0” instead of “1”). Let’s bump up the iterations to 2000:

image

No significant change. That same digit is still wrong. How about 10000 iterations?

image

This is better. The fourth digit is correct, but the fifth is not. Let’s get crazy and go for a million iterations:

image

Better still, but we’re not even at Math.PI. Ok, let’s go super-crazy and try 100 million iterations:

image

This actually took a fair amount of time, but the result is still disappointing. Clearly, something must change.

The problem with this series is that it converges slowly for large x (close to 1). In fact, for very small x values, it converges pretty fast. We need a new formula.

In 1706, John Machin found this formula to calculate PI:

image

At first, this may seem worse: now we have to calculate two arctangents! But, as the numbers are much smaller than one, we should get a better rate of convergence.

First, we’ll have to write a general arc tangent function, as none exists in BigInteger. This is a simple variant of the above calculation that needs to raise to the appropriate power – a simple enough job as BigInteger natively supports it:

Arc Tangent for BigInteger
  1. static BigInteger ArcTan(int oneOverX, int iterations, int digits) {
  2.     var mag = BigInteger.Pow(10, digits);
  3.     var sum1 = Enumerable.Range(0, iterations / 2).Select(i => i * 4 + 1).Aggregate(BigInteger.Zero, (sum, i) => sum += mag / (i * BigInteger.Pow(oneOverX, i)));
  4.     var sum2 = Enumerable.Range(0, iterations / 2).Select(i => i * 4 + 3).Aggregate(BigInteger.Zero, (sum, i) => sum += mag / (i * BigInteger.Pow(oneOverX, i)));
  5.     return sum1 - sum2;
  6. }

The last part uses the BigInteger.Pow method to raise to the appropriate power. Now we can write the new PI calculation method like so:

Faster PI calculation
  1. private static BigInteger CalculatePiQuick(int n, int digits) {
  2.     return 4 * (4 * ArcTan(5, n, digits) - ArcTan(239, n, digits));
  3. }

Running this with 20 iterations and 20 digits yields:

image

The result already surpasses Math.PI, and is calculated in a fraction of a second. We can try 1000 for the iterations and digits and get the first 1000 digits (or so) of PI pretty quickly (less than half a second without any optimizations):

image

The last 6 digits are in fact wrong (we need a few more iterations to get them right).

Now here’s a challenge for you: memorize as many digits as you can…

Getting Device Information in Windows Phone 7

Published at Dec 19 2011, 06:30 PM by pavely

Windows Phone 7 mandates a set of minimum requirements from devices it runs on, such as camera resolution, hardware graphics support, the existence of sensors such as microphone, GPS, touch, etc. However, sometimes it’s useful to know the exact specifications of a particular device the application is running on, so the application can optimize. As a simple example, running on the emulator or a real device can make a huge difference – maybe the application has a way of doing things differently when running on the emulator for testing purposes.

The device information is exposed primarily through the Microsoft.Phone.Info.DeviceStatus static class, where various properties provide some useful (and some not so useful) information. One oddity is that the device type (emulator or real device) is exposed through a different static property, Microsoft.Devices.Environment.DeviceType.

For demo purposes, I’ve created a simple class that wraps some of these properties in a type suitable for data binding (no {x:Static} on WP7 yet Sad smile):

  1. public class AppDeviceState {
  2.     public DeviceType DeviceType {
  3.         get {
  4.             return Microsoft.Devices.Environment.DeviceType;
  5.         }
  6.     }
  7.  
  8.     public string DeviceName {
  9.         get { return DeviceStatus.DeviceName; }
  10.     }
  11.  
  12.     public long TotalMemory {
  13.         get { return DeviceStatus.DeviceTotalMemory >> 20; }
  14.     }
  15.  
  16.     public PowerSource PowerSource {
  17.         get { return DeviceStatus.PowerSource; }
  18.     }
  19.  
  20.     public string DeviceManufacturer {
  21.         get { return DeviceStatus.DeviceManufacturer; }
  22.     }
  23. }

TotalMemory returns the result in megabytes, which is easier to use than the size in bytes.

Here’s a simple Grid that hosts some TextBlocks that bind to these properties:

  1. <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
  2.     <Grid.Resources>
  3.         <Style TargetType="TextBlock">
  4.             <Setter Property="FontSize" Value="24" />
  5.         </Style>
  6.     </Grid.Resources>
  7.     <Grid.RowDefinitions>
  8.         <RowDefinition Height="Auto" />
  9.         <RowDefinition Height="Auto" />
  10.         <RowDefinition Height="Auto" />
  11.         <RowDefinition Height="Auto" />
  12.         <RowDefinition Height="Auto" />
  13.     </Grid.RowDefinitions>
  14.     <Grid.ColumnDefinitions>
  15.         <ColumnDefinition Width="Auto" />
  16.         <ColumnDefinition Width="20" />
  17.         <ColumnDefinition />
  18.     </Grid.ColumnDefinitions>
  19.     <TextBlock Text="Device Name:" />
  20.     <TextBlock Grid.Column="2" Text="{Binding DeviceName}"/>
  21.     <TextBlock Grid.Row="1" Text="Device Type:" />
  22.     <TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding DeviceType}"/>
  23.     <TextBlock Grid.Row="2" Text="Total Memory (MB):" />
  24.     <TextBlock Grid.Row="2" Grid.Column="2" Text="{Binding TotalMemory}"/>
  25.     <TextBlock Grid.Row="3" Text="Power Source:" />
  26.     <TextBlock Grid.Row="3" Grid.Column="2" Text="{Binding PowerSource}" />
  27.     <TextBlock Grid.Row="4" Text="Manufacturer:" />
  28.     <TextBlock Grid.Row="4" Grid.Column="2" Text="{Binding DeviceManufacturer}" />
  29. </Grid>

In the page constructor, the binding source is set through a DataContext:

  1. public MainPage() {
  2.     InitializeComponent();
  3.  
  4.     DataContext = new AppDeviceState();
  5. }

This is the result on the emulator:

image

And this is the result on my actual device:

image

The demo project is attached.

My Sessions at the MobiWeb Conference

Published at Dec 16 2011, 12:21 PM by pavely

The MobiWeb Conference is scheduled for the 15-17 of January in the Daniel Hotel in Hertzliya (Israel). The sessions in the conference are “one day seminars”, each seminar covering some topic related to web development, mobile development, or both.

I’ll be presenting two seminars at the conference. The fist, “Building Windows Phone 7 Apps with Silverlight” (on the 16th) will cover the development for the (relatively new) Windows Phone platform using Silverlight (and maybe some XNA if we have time). Anyone looking into developing applications for this exciting and capable platform should get a good head start by attending this seminar. Basic familiarity with Silverlight will be beneficial, although I’ll go over the basics fairly quickly.

The second seminar I’ll be presenting is “Silverlight 5.0 Workshop” (on the 17th). This seminar will cover Silverlight development, from the basics, quickly moving to more advanced topics. It is intended for those who don’t know Silverlight, or have some basic familiarity with it. This can serve as a basis for general Silverlight development, or more specifically, for Windows Phone (it might make more sense to switch the seminar dates, so someone without any background in Silverlight or Windows Phone could follow up from Silverlight to Windows Phone sequentially; I’m looking into it). The seminar will also discuss some of the new features introduced in Silverlight 5.

Register here by leaving your details.

Maybe I’ll see you there!

Announcing the Israeli Windows Phone User Group

Published at Dec 08 2011, 07:44 PM by pavely

Although Windows Phone is not yet officially launched in Israel, it’s time for Israeli developers to start developing for the Windows Phone platform, even if most don’t have an actual device at hand.

A new user group dedicated to development for Windows Phone has been created, managed by Tomer Shamam and yours truly. The first meeting will be held on December 27th at the Microsoft Offices in Ra’anana. Please use this link to register and view the agenda: http://introwindowsphone.eventbrite.com

In this first meeting, Tomer and I will talk about the Windows Phone ecosystem, where to get tools and other resources, and then dive in to discuss application development using Silverlight.

Note that we plan to distribute 2 actual Windows Phone devices to participants in the meeting, so that at least some of you can test applications on an actual device!

We hope to see you there!

WPF Tip: Binding to the Selected Item in a Master-Details View

Published at Dec 06 2011, 04:00 PM by pavely

Master-details is a common way to display data. A master view provides minimal data for a collection of objects (e.g. book names), and when selecting one such item, a details view provides more information for the selected item (e.g. a book’s name, author, publication date, etc.).

In WPF, data binding (in XAML) is typically used to achieve the connection between an object and its details without using any code. Let’s see how we can achieve this.

Let’s say we want to show a list of book names, and when a book is selected, we want to show its details. The complete application might look like so:

image

The windows contains a Grid with two rows. The top row hosts a ListBox, while the bottom row hosts a StackPanel with a bunch of simple TextBlocks inside. Here’s the basic ListBox markup:

  1. <ListBox ItemsSource="{Binding}" HorizontalContentAlignment="Stretch">
  2.     <ListBox.ItemTemplate>
  3.         <DataTemplate>
  4.             <Border BorderBrush="Blue" BorderThickness="2" Margin="0" Padding="4" CornerRadius="4" x:Name="border">
  5.                 <TextBlock TextAlignment="Center" Text="{Binding Name}" Foreground="Black" FontWeight="Bold" FontSize="16" x:Name="text"/>
  6.             </Border>
  7.             <DataTemplate.Triggers>
  8.                 <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBoxItem}}" Value="True">
  9.                     <Setter Property="Background" Value="Yellow" TargetName="border" />
  10.                 </DataTrigger>
  11.             </DataTemplate.Triggers>
  12.         </DataTemplate>
  13.     </ListBox.ItemTemplate>
  14. </ListBox>

The data trigger is of no significance as it just sets the selected item’s background as yellow.

The ItemsSource property is bound to the nearest DataContext up the visual tree. We’ll set that context in code (for simplicity) in the Window’s constructor:

  1. var books = new ObservableCollection<Book> {
  2.     new Book { Name = "Windows Internals", Author = "Mark Russinovich", Published = new DateTime(2009, 6, 17) },
  3.     new Book { Name = "Essential COM", Author = "Don Box", Published = new DateTime(1998, 1, 1) },
  4.     new Book { Name = "Programming Windows with MFC", Author = "Jeff Prosise", Published = new DateTime(1999, 5, 13) },
  5.     new Book { Name = "Astrology of Fate", Author = "Liz Greene", Published = new DateTime(1984, 11, 1) },
  6.     new Book { Name = "Windows via C/C++", Author = "Jeffrey Richter", Published = new DateTime(2007, 12, 12) },
  7.     new Book { Name = "CLR Via C#", Author = "Jeffrey Richter", Published = new DateTime(2010, 2, 11) },
  8.     new Book { Name = "Pro WPF in C# 2010", Author = "Matthew Macdonald", Published = new DateTime(2009, 12, 23) },
  9. };
  10.  
  11. DataContext = books;

Now for the details part. How can we bind the TextBlocks Text property to the currently selected item in the ListBox? Here’s one way to do it:

  1. <StackPanel Grid.Row="1" TextBlock.FontSize="16" DataContext="{Binding SelectedItem, ElementName=_list}">
  2.     <TextBlock Margin="4" Text="{Binding Name, StringFormat=Name: {0}}" />
  3.     <TextBlock Margin="4" Text="{Binding Author, StringFormat=Author: {0}}" />
  4.     <TextBlock Margin="4" Text="{Binding Published, StringFormat=Published: {0:d}}" />
  5. </StackPanel>

This assumes the ListBox is named _list. Although this works, it’s a bit too specific: we’re looking up the SelectedItem of a specific control. What happens if that control is later replaced with something else (like a ComboBox) and is named differently? What is the ListBox is removed altogether and selection is controlled programmatically via some other UI elements?

It turns out, we can do better. We need to add the IsSynchronizedWithCurrentItem=”true” to the ListBox. This will use the default view, that sits between the ListBox and the actual data collection (the books). Now we can bind to the view, by hooking up to the CurrentItem property (from the ICollectionView interface implemented by the view):

  1. <StackPanel Grid.Row="1" TextBlock.FontSize="16" DataContext="{Binding CurrentItem}">

That’s better. No dependency on any specific ListBox. Can we make it even better? We can. We’ll remove the local DataContext on the StackPanel and prepend a forward slash (/) to the property names within the TextBlocks Text property, like so:

  1. <StackPanel Grid.Row="1" TextBlock.FontSize="16" >
  2.     <TextBlock Margin="4" Text="{Binding /Name, StringFormat=Name: {0}}" />
  3.     <TextBlock Margin="4" Text="{Binding /Author, StringFormat=Author: {0}}" />
  4.     <TextBlock Margin="4" Text="{Binding /Published, StringFormat=Published: {0:d}}" />
  5. </StackPanel>

Note the slash in the bound properties (/Name, /Author, /Published). We simply pick the relevant properties on a single item (book in our example). Note that the IsSynchronizedWithCurrentItem must be set to true, as before.

Parallel Programming Open House Session

Published at Dec 01 2011, 05:34 PM by pavely

Today I presented a half-day session on Multithreading & Parallel Programming at John Bryce center in Tel Aviv. Thank you all for attending! I certainly enjoyed presenting these fascinating topics.

I’ve attached the demos I showed. The presentation will be sent to those who attended by email.

Thank you!

More Posts Next page »