ailon's DevBlog: Development related stuff in my life

Obstruction Detection in Silverlight for Windows Phone

4/3/2011 1:12:14 PM

image

AdDuplex Silverlight control is used quite often as a fallback for other networks. As a result it could be obstructed by the other network’s control at times. Problem is that in general case we can’t rely on developers always collapsing AdDuplex control when it’s not visible or informing it about this state in any way.

The other problem is that some of the other network controls (namely Microsoft’s pubCenter) don’t collapse when they have no ad to show, but rather either collapse some internal elements or just make them transparent. This allows underlying elements to show through but they still don’t get the touch events.

So I decided to solve this programmatically. It sounded really easy, but as usual there are some small things that stand in the way.

Meet ObstructionDetector

I’ve created a class with some helper methods that could be useful both in the above scenario and probably some other. You can find it in full at the end of this post.

The “title” method of this class is IsElementObstructed:

public static bool IsElementObstructed(FrameworkElement target)
{
var page = GetPage(target);
var frame = GetFrame(target);
var transform = target.TransformToVisual(frame);
var rect = TransformBoundsToPortrait(transform.TransformBounds(new Rect(0, 0, target.ActualWidth, target.ActualHeight)), page);
var covers = VisualTreeHelper.FindElementsInHostCoordinates(rect, page);

if (covers != null && covers.Count() > 0)
{
return !IsElementChildOf(covers.First(), target);
}

return false;
}

You just pass an element in question to it and it returns true if there’s something in the way of user’s eyes or fingers in front of this element.

The key technique is to use VisualTreeHelper.FindElementsInHostCoordinates() method. It returns elements residing in the same rectangle on the screen as our target. The elements are returned in the descending z-index order. So what’s left to do is to check if the first element in returned collection belongs to (is a child of) our target. If so, then there’s nothing in the way.

A few gocthas

Everything is portrait to VisualTreeHelper.FindElementsInHostCoordinates()

I’ve spent quite some time trying to figure out why the code worked fine in Portrait pages but didn’t work in Landscape. Turns out FindElementsInHostCoordinates() considers everything as portrait oriented even when other parts operate correctly. Apparently this is “by design”. So we need to adjust to this “feature”. For that I’ve added TransformBoundsToPortrait() method.

Get PhoneApplicationPage by going up the visual tree

It’s tempting to use Application.Current.RootVisual and assume it’s child is our PhoneApplicationPage, but it’s not the case in some cases (like page transitions in Silverlight Toolkit). So it’s safer to just go up the visual tree until we find the page.

Account for SystemTray

We need to create a transform based on PhoneApplicationFrame (not Page) since transforming from PhoneApplicationPage doesn’t include optional SystemTray and can result in offset in the results.

Known Issues

  • VisualTreeHelper.FindElementsInHostCoordinates() doesn’t return elements with IsHitTestVisible set to false. So if someone creates a cover for your control and set this property to false it won’t be detected. Any ideas?

Feedback

I know this code is far from perfect, but it’s what I’ve got so far. I would really appreciated your feedback on how to improve it. The class is too small for a separate OS project or something like that, but I’d be happy if someone included it in some WP7 toolkit and improved on it.

The code

using System.Windows;
using System.Windows.Media;
using System.Linq;
using Microsoft.Phone.Controls;
 
namespace Ailon.Phone.Tools
{
    public static class ObstructionDetector
    {
        public static PhoneApplicationPage GetPage(DependencyObject target)
        {
            var parent = VisualTreeHelper.GetParent(target);
            while (parent != null && !(parent is PhoneApplicationPage))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
 
            return (parent as PhoneApplicationPage);
        }
 
        public static PhoneApplicationFrame GetFrame(DependencyObject target)
        {
            var parent = VisualTreeHelper.GetParent(target);
            while (parent != null && !(parent is PhoneApplicationFrame))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
 
            return (parent as PhoneApplicationFrame);
        }
 
        public static Rect TransformBoundsToPortrait(Rect bounds, PhoneApplicationPage page)
        {
            if ((page.Orientation & PageOrientation.Portrait) > 0)
            {
                return bounds;
            }
            else
            {
                Rect result;
 
                if (page.Orientation == PageOrientation.LandscapeLeft)
                {
                    result = new Rect(bounds.Y, bounds.X, bounds.Height, bounds.Width);
                }
                else
                {
                    result = new Rect(bounds.Y, 800 - bounds.X - bounds.Width, bounds.Height, bounds.Width);
                }
 
                return result;
            }
        }
 
        public static bool IsElementObstructed(FrameworkElement target)
        {
            var page = GetPage(target);
            var frame = GetFrame(target);
            var transform = target.TransformToVisual(frame);
            var rect = TransformBoundsToPortrait(transform.TransformBounds(new Rect(0, 0, target.ActualWidth, target.ActualHeight)), page);
            var covers = VisualTreeHelper.FindElementsInHostCoordinates(rect, page);
 
            if (covers != null && covers.Count() > 0)
            {
                return !IsElementChildOf(covers.First(), target);
            }
 
            return false;
        }
 
        public static bool IsElementChildOf(DependencyObject element, DependencyObject parent)
        {
            var current = element;
            while (current != null)
            {
                if (current == parent)
                {
                    return true;
                }
 
                current = VisualTreeHelper.GetParent(current);
            }
 
            return false;
        }
 
    }
}

Tags: ,

EcoContest

2/28/2011 12:32:52 PM

eco_badge_130There’s a Silverlight ECO Contest in progress with a theme of forest management and a grand prize of a trip to MIX11.

I’ve decided that it’s targeted mostly at designers and copy-writers at first and decided not to even try. Then I had an idea and decided to give it a try. When I was like 2/3 way through the implementation I decided again that I’m not a designer and quit. The files were left unattended on my disk for a couple of weeks.

Today I thought that there’s no reason for me not to submit what I’ve done. I’m not embarrassed by the idea, I still like it a lot, and I’m not a designer to be embarrassed by my design skills (or lack of them).

So, I took 1/3 of what I’ve done, packaged it and submitted to the contest.

You can check it out here, VOTE for it by clicking 5 leafs at the bottom and send me to MIX11.

Thanks!

Tags: , ,

WPF, Silverlight and WP7 at MIX11 – My Picks

1/26/2011 6:31:57 PM

I’ve submitted a proposal to present a talk at MIX11 conference in Las Vegas called “Developing for WPF, Silverlight and Windows Phone 7 at Once”. The proposal has passed the first round of filtering and now it needs your votes to get me into one of the 10 spots. With more than 200 candidates that’s going to be a tough task. But it’s doable, right? RIGHT!?

image

If you like the subject of my talk you can vote for it by selecting all the cats in the CAPTCHA and pressing the “Vote for the session” button.

Obviously mine is not the only great proposal there. Here are some of my favorites I voted for:

  • First of all my virtual friend (devirtualization at MIX?), great developer, Silverlight MVP and overall nice guy René Schulte has 3 proposals: The World Is Not Enough - Silverlight Augmented Reality, Pictures Lab - How To Write A Silverlight Photo Effects Application For Windows Phone 7 and Silverlight 3D. I’m sure he can deliver and you should definitely vote for one of his proposals (if not all).
  • Then there’s The tale of two apps - Making a splash in the Windows Phone Marketplace by András Velvárt and Bálint Orosz. A story of 2 of the most popular WP7 apps made by developers from the “unsupported” Hungary who instead of whining and fighting for justice (like I do) found ways to make a splash in the Marketplace despite obstacles Microsoft put in front of them.
  • Then there’s PHP on Windows by fellow Lithuanian Juozas Kaziukėnas. I’ve seen him present an earlier version of this talk and it was great even though it feels a little out of place in my list. Juozas is a great presenter and the content is interesting for those who want to keep their eye on what’s happening in the area.
  • Then I chose Exploring a Blendable Windows Phone 7 Application by Laurent Bugnion out of 2 of his proposals. I believe Deep dive MVVM will get through without my help. Laurent is probably the most knowledgeable and influential Silverlight MVP in Europe and probably the whole world. It’s always interesting to see him speak.
  • One talk that has a chance to be overlooked but seems very interesting and important is Introduction to Maps by Colin Blair. Mapping becomes more common in all sorts of apps but quite a few developers understand the terms and concepts involved.

My other votes in no particular order:

As you can see these are only a few of the proposals and they are well worth their own conference and they need your votes.

And most importantly (shameless plug and I’m not even sorry) I need your votes. Thanks!

P.S. In case you don’t like cats think of the CAPTCHA as the one were you have to eliminate all the cats.

Tags: , , ,

amCharts Quick Charts in “Colin Eberhardt’s Performance Test”

12/17/2010 7:04:19 PM

About a week ago Colin Eberhardt has published a post in Scott Logic blog comparing performance of several Silverlight charting libraries. Not surprisingly their Visiblox charts came on top in a shoot out between 6 contenders (2 of them unnamed for licensing reasons).

amCharts Quick Charts were absent from the comparison. One can only guess why. Maybe they aren’t known enough, even though amCharts comes up higher on Google when looking for “silverlight charts” than many of the reviewed contenders. Or maybe the reason is in the paragraphs below ;)

amCharts Quick Charts Test

I’ve plugged Quick Charts into the test project provided in the above mentioned blog and here’s the result:

Here’s the XAML for Quick Charts

   1: <Grid x:Name="LayoutRoot" Background="White">
   2:       <chart:SerialChart x:Name="chart" 
   3:                          CategoryValueMemberPath="Location" 
   4:                          LegendVisibility="Collapsed" 
   5:                          MinimumValueGridStep="5"
   6:                          MinimumCategoryGridStep="1000"
   7:                          >
   8:           <chart:SerialChart.Graphs>
   9:               <chart:LineGraph Brush="#A00" ValueMemberPath="RIntensity" />
  10:               <chart:LineGraph Brush="#0A0" ValueMemberPath="GIntensity"  />
  11:               <chart:LineGraph Brush="#00A" ValueMemberPath="BIntensity"  />
  12:           </chart:SerialChart.Graphs>
  13:       </chart:SerialChart>
  14:   </Grid>

and C# for hooking app the data from the test suite:

   1: protected override void RenderDataToChart(List<List<Histogram.DataPoint>> rgbData)
   2: {
   3:     _chart.Chart.DataSource = GetRGBData(rgbData);
   4: }
   5:  
   6: private List<RGBData> GetRGBData(List<List<Histogram.DataPoint>> rgbData)
   7: {
   8:     var data =
   9:         from r in rgbData[0]
  10:         join g in rgbData[1] on r.Location equals g.Location
  11:         join b in rgbData[2] on r.Location equals b.Location
  12:         select new RGBData() { Location = r.Location, RIntensity = r.Intensity, GIntensity = g.Intensity, BIntensity = b.Intensity };
  13:  
  14:     return data.ToList();
  15: }

Notice that I had to combine data from 3 separate lists in the test suite into one list for Quick Charts which affects performance somewhat.

Even though I admit this is due to an intentional limitation in Quick Charts, I still can’t see why the data for each point is in 3 separate lists in the first place? 1 object per point would make more sense. Maybe there’s an objective reason for that, or maybe this way is preferable for Visiblox API. I don’t know and lets just leave it at that.

Test results

I’ve ran the automated tests for Visiblox and amCharts Quick Charts on my machine (10 times each) and here are the average results:

  • Visiblox – 63.9 fps
  • amCharts Quick Charts – 70.6 fps.

Conclusion

You probably expect my conclusion to be that amCharts Quick Charts is faster than Visiblox and consequently all the other charting libraries in the original test. Sure, that too ;)

But my main conclusion is that you shouldn’t compare apples to oranges. All the charting libraries on that list have their strong features and they all probably have some killer features that affect performance. Now if you need that feature the performance advantage of some other library (that doesn’t have the feature) is pointless.

amCharts Quick Charts was created with simplicity in mind. So, even though it’s not very performance oriented, it beats other charts because it doesn’t do some special things other libraries (including amCharts Bundle and amCharts Stock Chart) might do.

Anyway the point is: if you need simple and performing WPF, Silverlight or Windows Phone 7 charts, probably nothing beats amCharts Quick Charts, but, when you are after some advanced features or deeper customization, performance becomes a secondary factor, not primary.

Tags: ,

Tic-Tac-Toe 3D on Windows Phone 7

12/9/2010 6:02:56 PM

wp7_152x50_blueToday an enhanced version of my award winning Tic-Tac-Toe 3D game was published on Windows Phone 7 marketplace. This version was developed and published in cooperation with René Schulte and, in addition to adaptation for the Windows Phone 7 platform, includes a 2 player mode, scoreboard, inertia and other minor enhancements.

The game costs only $0.99 and includes a free trial which is a fully functional single player game.

Get it here (if you have Zune installed or reading this from the phone) and please spread the word if you like it. Thank you! In case you don’t have Zune installed, you can check a web listing for the app on WP7applist.

Here are some screenshots:

screenshot3screenshot5screenshot4

And here’s a video demo:

wp7_152x50_blue

Tags: ,

Developing Controls for Windows Phone 7 as a Business

11/22/2010 10:48:07 AM

Yesterday I couldn’t sleep and was thinking about feasibility of developing Windows Phone 7 (Silverlight) controls as a business. Since I’m already in the the WPF/Silverlight control business and we already have an open-source charting product for WP7 this is a really interesting and sensitive topic for me.

Here are some of my thoughts. Some are facts, some are pure speculation and/or brain dump.

As you probably know, at this stage Windows Phone 7 is a consumer platform and the only way to get and distribute apps is through Windows Phone Marketplace. This makes it pretty easy to see the current state of the whole market/ecosystem.

image

As of this writing there are almost 2500 apps in the marketplace. Almost 600 are games meaning about 24% of the total number. Obviously the total number of apps is going to grow over coming months and years but I guess we can assume that the proportion of games will stay at approximately the same level. Let’s fix it at a nice number of 25%. Out of the rest of the apps a really large chunk are various “flashlight”, “fart” and other simple apps. These are not a target market for custom controls either. I’d say the number of apps that would benefit from advanced controls is no more than 10% of non-games (pure speculation based on non-scientific observation).

imageSo let’s say apps using 3rd party controls constitute 7% of all apps (I’d say that’s in optimistic range). Also, let’s say that the total number of apps grows to about 50,000 over the next 1-2 years. That’s roughly 3500 apps.

Now I’m not sure where to get the actual average number of apps per publisher but my guess is that what says “1325 Top publishers” in Bing’s Visual Search for Windows Phone 7 Apps is actually a total number at this point in time.

So basically the average is close to 2 apps per publisher. Meaning that with 50,000 apps in the marketplace we’ll have ~1750 publishers interested in 3rd party controls.

Now I believe most of the publishers are one man shops or really small companies. I guess the average number of developers per publisher is not more than 2. So let’s say these publishers are going to spend $1000 per developer on 3rd party controls over the next 2 years (again optimistic number, imho). That makes the market worth no more than 1750 x 2 x $1000 = $3,500,000 over all 3rd party control publishers. And that’s on the optimistic side in my opinion.

Conclusion

This post is pure speculation and I would like to hear your thoughts either based on more facts or deeper knowledge or just higher intelligence, but as I see it now the market is really small.

That said I still see some reasons to participate:

  1. These are still Silverlight controls and should cost less to adopt from desktop Silverlight than writing from scratch. That said WP7 Silverlight is going to be 2 versions behind pretty soon and that imposes serious challenges balancing between doing things the better (new) way and making them work on the phone.
  2. Sooner or later Microsoft is going to open the platform for enterprise development and distribution and that is going to be a much bigger market for control developers. The question is when is this going to happen? But hopefully this happens sooner than later and you’d want to be in the game when it does.

Again, I’m sorry for posting such a speculative rant, but if governments can expect 3% higher budget incomes by upping taxes by 3% why can’t I speculate using the same “Excel logic”?

Tags: , ,

Unit Testing Combo WPF/Silverlight Projects

9/23/2010 8:24:52 PM

With release of WPF 4 and Silverlight 4 creating WPF and Silverlight applications sharing the same code became easier and less frustrating than it was before. The main techniques that I described in my series for WPF 3.5/Silverlight 3 (“Add as Link”, partial classes and preprocessor directives) are still the most reasonable approach for this task.

It is also commonly agreed that your ride will be smoother if you start with Silverlight. This doesn’t mean that you have to leave WPF for later. What this means is that you create files in your Silverlight project and “Add as Link” to your WPF project (not the other way around). The main benefit of this approach is that you get Intellisense , etc. for Silverlight and, since Silverlight doesn’t have all the classes, methods and overloads that full .NET framework has, you won’t be tempted to use them.

A very simple solution utilizing this approach would look something like this:

image

So What About Unit Testing?

If you are some unit testing fanatic you might want to unit test WPF part with MSTest (or other testing framework) and separately unit test Silverlight part with Silverlight Unit Test Framework. Now this would be good in test reliability but I can bet you won’t run both of them anyway and since most of your code is identical you would probably want to unit test that common code with only one of the testing suites.

It wouldn’t come as a surprise if you decide to use MSTest running inside Visual Studio over SilverlightUT running in browser. The problem here is that you are doing Silverlight project first and you can’t add a reference to your Silverlight project to the MSTest project.

image

So what you have to do if you want to go this route is constantly add new files to your WPF project and reference that project from the test project.

image

Problems with this Approach

Unfortunately this approach is far from perfect.

First of all it’s problematic to do TDD/tests first. When you write a call to a not yet defined method and try to generate method stub using Visual Studio you get this error:

image

This happens because you have MyControl.cs file open from a Silverlight project and the tool tries to generate the stub into WPF project and fails because the file is already open from another project. Now if you close the file as the message box suggests, the generation will succeed but it will open the file from the WPF project and you won’t be doing Silverlight-first unless you close the file again and reopen it from the Silverlight project again.

Then there’s a similar problem with refactoring/renaming. When you have your file open from the Silverlight project and you rename a method, class, property, etc. using Visual Studio refactoring tool it won’t be renamed in the test project. So you’ll have to go and do a bunch of manual finding and replacing.

These are obviously not critical issues but pretty annoying nevertheless. It’s very important that writing tests is as painless as it could be or you won’t write them. And pain is pretty much a part of the process considering these issues.

Hopefully there’s a better way to unit test such projects and I’m just not aware of it. If so, please, let me know in the comments.

Shout it kick it on DotNetKicks.com

Tags: , , ,

Side Effects of Silverlight Marketing

7/1/2010 9:47:07 AM

Note: this post is about marketing to developers (not general public).

Yesterday Tim Heuer published a blog post titled “Top issues for Silverlight” where he summarizes reported Silverlight issues. Apparently number one issue is “WPF and Silverlight feature (dis)parity”. Tim writes:

It’s a little weird to call this one an issue with Silverlight, but this was seen requested more often in these areas that it is worth calling attention to.  Some of the genesis of this angst comes from an expectation that WPF applications ‘just work’ in Silverlight and not understanding the areas of the subset in both XAML and the .NET base class libraries (BCL).

Now this is true but one has to wonder where this expectation comes from.

Silverlight is NOT a subset of WPF

The root of this problem (at least how I see it) is the initial marketing message of Silverlight for developers was that it is a subset of WPF. Now Microsoft is a serious and cautious company and you would hardly find any direct evidence of this but this is what gets stuck in minds of developers who know about WPF and/or Silverlight from various presentations before they dig deeply into development.

It’s hard for Microsoft insider to realize this. That is not that obvious even for someone who is working with both WPF and Silverlight. But if you take someone who does some real work with either WPF or Silverlight but not both and ask them what’s the relation between WPF and Silverlight, most of the time you are going to hear the mantra – “Silverlight is a subset of WPF”. I’ve heard developers, project managers, etc. with no experience in WPF and/or Silverlight repeat this numerous times. And that was exactly as I saw things before I started coding with both. This is encrusted deeply in the minds of developers and is the main source of frustration when they realize that this is not exactly the case.

I guess with all the advances in Silverlight over the recent years this disparity became a little more expected than before but the “subset” idea is pretty much still alive. Now I don’t know what needs to be done to kill this mantra and I’m not even sure Microsoft’s business departments want to kill it but I think this is the main source of this “issue” being number one.

Silverlight for Windows Phone 7 is NOT Silverlight

This subtitle is a little too drastic on my part but I’ll explain what I mean in the next few paragraphs.

One might think that WPF vs. Silverlight case was one of it’s kind but just this spring during MIX10 conference while unveiling Silverlight as one of the main developer platforms for Windows Phone 7 Scott Guthrie said this: “It’s not Silverlight Lite. It’s not Silverlight Mobile. It’s Silverlight.” (watch MIX10 Day 1 Keynote).

Now the wording is really clever. And later he explained that it’s Silverlight 3 with some parts of Silverlight 4 and phone specific stuff. He never said that you can run exactly the same code on the phone as you can on desktops and those who were interested in WP7 development understood that. But majority of the folks who just listened to this as high level overview have this notion stuck deeply in their minds. They believe that they can continue working on their Silverlight apps as they did before and then if they decide to move the app to WP7 they will only have to shuffle the UI a little to fit the smaller screen.

Do you think they are going to be frustrated when they find out that this is not the case? What do you think is going to be the top issue for Silverlight for Windows Phone 7? My guess is “Silverlight and Silverlight for WP7 (dis)parity”.

Shout it kick it on DotNetKicks.com

Tags: , , ,

Quick Charts for WPF & Silverlight v.1.0 Beta Released

5/10/2010 3:48:46 PM

We are happy to announce availability of feature complete version of amCharts Quick Charts for WPF & Silverlight.

Quick Charts is an easy to use, fast set of charting controls for WPF & Silverlight. And it's FREE and Open Source (Ms-PL)!

Quick Charts for WPF & Silverlight

Quick Charts motto is: Ease of Use, Speed, Small Footprint. It is amCharts Bundle's little brother. It has less features, but concentrates on what's important for the majority of users. In order to achieve this we didn't just strip the features off of amCharts Bundle, but created Quick Charts from scratch.

Check them out and, please, spread the word. Thanks!

Shout it kick it on DotNetKicks.com

Tags: , ,

Debugging Silverlight Out-of-Browser Applications on 64-bit Windows

4/22/2010 3:53:52 PM

Today I had to debug a problem in my Silverlight 3 project that manifested itself exclusively in out of browser mode.

Here’s a concise and to the point guide on debugging Silverlight 3 applications in out of browser (OOB) mode by Jimmy Lewis. Problem is that when you follow it in Visual Studio 2008 running on 64-bit Windows 7 (and as far as I understand Vista too) you get this message box when you try to start debugging:

Warning: A StringBuilder buffer has been overflowed by unmanaged code. The process may become unstable. Insufficent capacity allocated to the StringBuilder before marshaling it.

I’ve tried to search for a solution on the web and all I found was a simple but not very satisfactory workaround: Use VS2010.

Yes, as far as I can tell the only way to debug your Silverlight 3 OOB app on Windows x64 is to open it in Visual Studio 2010. Problem is that first of all you need to have VS2010 and another problem is that it has to convert your project to 2010 format.

Luckily in my case I was able to just copy my VS2008 project to a new location, open it, convert it, quickly find a lame bug (I was assuming in one place that HTML Bridge is always available), implement single line fix and copy it back to my VS2008 project. So it was a small inconvenience in my case but if I ever need to debug something more substantial that could be a big pain.

However it’s quite possible that my googling skills aren’t perfect and I’ve missed a real solution to this problem. If so, please, let me know in the comments below.

Tags: ,

Copyright © 2003 - 2017 Alan Mendelevich
Powered by BlogEngine.NET 2.5.0.6