Simulating GPS on Windows Phone 7

by Morten 9. December 2010 00:52

If you are building Windows Phones apps that require the use of GPS, you cannot use the Emulator, and should preferably be outside.

While building some of my latest WinPhone apps, I needed to be able to able test moving around on a map, while being able to debug. However I preferred doing this at the comfort of my desk. So I had to “fake” a GPS signal. Luckily the GeoCoordinateWatcher class that is used for this, implements the interface “IGeoPositionWatcher<GeoCoordinate>”.  If I were to create my own class that implements this interface, I had an option for using a separate class for receiving data from the location service. I ended up needing two types of location simulators for my routing app: One that starts at a given location and direction, and randomizes speed and direction over time. The other follows a predefined route. You can download the source code for these below.

The next step is to automatically use the simulator when I’m running on the emulator, but use the “real” location service when running on the device. You can accomplish this by checking the DeviceName first. Example:

   1:  IGeoPositionWatcher<GeoCoordinate> geowatcher; 
   2:  string deviceName = Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceName").ToString(); 
   3:  if (deviceName == "XDeviceEmulator") //Use simulator for emulator 
   4:      geowatcher = new GeoCoordinateSimulator(34.0568, -117.195, 270) 
   5:  else 
   6:      geowatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); 
   7:  geowatcher.PositionChanged += watcher_PositionChanged; 
   8:  geowatcher.Start();

The above uses the “random” simulator when running on the emulator.

The other simulator takes a set of GeoCoordinates and interpolates between them at the specified speed. Example:

   1:  var pnts = new List<GeoCoordinate>(); 
   2:  pnts.Add(new GeoCoordinate() { Longitude = -117.195670639, Latitude = 34.0568044102 }); 
   3:  pnts.Add(new GeoCoordinate() { Longitude = -117.195697272, Latitude = 34.0585127272 }); 
   4:  pnts.Add(new GeoCoordinate() { Longitude = -117.204302784, Latitude = 34.0515719501 }); 
   5:  geowatcher = new SharpGIS.WinPhone.Gps.GpsDriveSimulator(pnts, 20);

Below is an example of this simulator in action on the emulator in a little app I’m working on:

screenshot_12-7-2010_22.7.41.326photo[1]

It was fun putting this app on the real device, go for a drive along roughly the same route and it worked exactly same. The simulator helped me weed out a series of bugs that would have taken me several (dangerous) “test drives” if I hadn’t had this simulator.

Download Simulator code here:

Tags:

Submitted my first WinPhone 7 Application

by Morten 2. December 2010 21:42

imageI’ve just submitted my first application to the Windows Phone Marketplace. It’s a very simple app that creates a “Guide Post” with signs on a pole showing distances and direction to any point in the world. You have probably seen these at various sites all over the world, or in the TV Show “M*A*S*H”.

It’s all built in Silverlight, and uses PlaneProjection to give give the signs a 3D effect. You use your finger to slider over the screen to rotate it.

In addition to that there’s a Map where you can view your current location and the great circle line (ie. shortest path) between you and the points of interest. This is of course using the ESRI ArcGIS API for Windows Phone that we just released.

Below is a few screenshots and a video clip of the app in action.

screen_12-1-2010_8.51.30.996screen_12-1-2010_8.50.48.336
screenshot_12-2-2010_12.26.46.864screenshot_12-2-2010_12.27.59.830

GuidePost Screen Capture

It was a great fun little app to build and only took a few evenings to get done. You can download the app to your phone from this link: http://bit.ly/WP7GP

Tags:

ESRI | ESRI Silverlight API | GIS | Silverlight | Windows Phone

Displaying HTML in Silverlight

by Morten 15. September 2010 12:18

In my second post in the series of ripping off other peoples work :-) here’s an updated version of David Anson’s HtmlTextBlock control back from 2007.

This was originally written based on the TextBlock control, but since the TextBlock control was sealed and couldn’t be inherited from, it required a lot of copying properties around. Textblocks also only supports text, so the HyperLink method was not really a hyperlink, and there was no image support, but from what we had available back them, it was a really good solution considering the simplicity (I like simple small implementations).

Since then Silverlight 4 has arrived, and we now have the RichTextBlock control. This supports hyperlinks, images etc, and it is not sealed, so we can pretty easily get around the limitations that the original implementation had. Most of the logic for generating the HTML is the same, but now with proper support for images and real hyperlinks. Again all the credit goes to the original author. I just did some tweaks.

You can download the source with a sample app here: HtmlTextBlock.zip (34.15 kb)

UPDATE: Rewrote the parser approach quite a lot. Now it also supports tables (!) as well as setting fontsize using the H1..H4 tags. With the new parser approach it should be easier to add support for other more complex tags as well.

You can download the source with a sample app here: HtmlTextBlock_v2.zip (34.15 kb)

Tags: , ,

Silverlight

REALLY small unzip utility for Silverlight – Part 2

by Morten 25. August 2010 20:50

I earlier blogged about a very small unzip utility for Silverlight.

However there was one problem with the method: It relied on some Silverlight framework libraries that didn’t support all zip file formats (a known bug I’m told). Some file zippers places the file size after the zip data chunk, and Silverlight does not like that. So I added a little bit to the utility to detect this case and if so, will re-arrange the bytes in the zipfile so Silverlight will read it.

So I present to you: The really small unzip utility v.2.0. It’s slightly larger than before, but still under 200 lines of code (plus comments).

It works the same way as before, so read the original blogpost to see how to use it.

Although I only tested this on Silverlight 4 and WinPhone 7, it should work with earlier Silverlight releases as well.

Download here: SharpGIS.UnZipper_v2.zip (2.53 kb)

Also available at NuGet

Tags:

Silverlight

Dependency Property gotchas

by Morten 10. June 2010 20:44

Here’s a quick list of gotchas I’ve learnt the hard way or seen over the time while working with Dependency Properties in Silverlight and WPF (most of this applies to Attached Properties as well).
Here’s a typical dependency property defined on a class inheriting from DependencyObject:

public int SomeValue
{
    get { return (int)GetValue(SomeValueProperty); }
    set { SetValue(SomeValueProperty, value); }
}
public static readonly DependencyProperty SomeValueProperty =
    DependencyProperty.Register("SomeValue", typeof(int), typeof(ownerclass), null);
private static void OnSomeValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ownerclass obj = (ownerclass)d;
    int newValue = (int)e.NewValue;
    int oldValue = (int)e.OldValue;
} 

Naming

The naming is very important. Note ‘SomeValue’ is not only the name of the property, but the static DependencyProperty field is prefixed with the word ‘Property’, and the string in the first parameter also must match this name.

Type and default values.


Below we instead create a dependency property of type double and define a default value in PropertyMetadata to 0. See if you can spot the bug:

public static readonly DependencyProperty SomeValueProperty =
    DependencyProperty.Register("SomeValue", typeof(double), typeof(ownerclass), new PropertyMetadata(0));

The problem is very subtle, and the error you will get at runtime is not always obvious. The reason is that PropertyMetadata takes an object as parameter, and there’s no way for the debugger to know that you meant to put a double there, and it will wrongly assume Int32. At runtime you will get an exception because of this. Instead make sure you explicitly declare the default value as a double:

public static readonly DependencyProperty SomeValueProperty =
    DependencyProperty.Register("SomeValue", typeof(double), typeof(ownerclass), new PropertyMetadata(0d));

Default values are static – Beware of object references!

Don’t ever ever EVER declare a default value in a DependencyProperty that is not a value type. Since this field is static, the default value will be shared among every instance that’s using the default value.

If I were to access the property and modify its sub properties, anything using this instance would be affected.
Example: Brush property on a control. I have multiple instances of the control, but changing a subproperty on the property will affect all the controls:

public static readonly DependencyProperty MyBrushProperty =
    DependencyProperty.Register("MyBrush", typeof(SolidColorBrush), 
    typeof(ownerclass), new PropertyMetadata (new SolidColorBrush(Colors.Red))); 

. . . 

myControl.MyBrush.Color = Colors.Blue;

Instead set the default value to null. Then either set the property in the default style template (if it’s declared on a control), or set it in the constructor of your class.

Code in property setter

Often you are used to execute code in the setter of your property when a value changes like so:

public int SomeValue
{
    get { return (int)GetValue(SomeValueProperty); }
    set 
    { 
        if(value != SomeValue)
        {
            SetValue(SomeValueProperty, value); 
            UpdateValues(value);
        }
    }
}

However, if you’ve done this, you might have seen that sometimes your setter is not called, and the UpdateValues() method is never executed. The reason is that if you are binding to this property instead of just calling the setter directly, this setter will never be hit! Instead Silverlight/WPF will call SetValue(…) directly and “circumvent” your setter (this is also why the naming mentioned above is important so it can find the property).
Instead the correct way is to declare a method to call when the value changes. This is done in the PropertyMetadata instance: Also note that you do not need to check whether the value actually has changed. The changed handler will only be called if the value is actually different.

public static readonly DependencyProperty SomeValueProperty =
    DependencyProperty.Register("SomeValue", typeof(int), typeof(ownerclass), new PropertyMetadata(0, OnSomeValuePropertyChanged));
private static void OnSomeValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ownerclass obj = (ownerclass)d;
    int newValue = (int)e.NewValue;
    obj.UpdateValues(newValue);
}

Tags:

Code Syntax Highlighting in Silverlight

by Morten 6. June 2010 13:54

A little while back, Jeff Wilcox wrote an awesome syntax highlighter (blog post here). It enables you to display code in Silverlight with similar syntax highlighting that we know and love from Visual Studio. This is really useful if you want to display some code samples inside your Silverlight application.

However it had one major feature missing: You couldn’t select and copy the code. And what good are code samples if you can’t do that (unless you’re the patient type who likes typing a lot). Vladimir Horbovanu had commented that he had modified the sample to be built on MVVM and added the option of selecting and even editing the text. However, this only supported C# and not VB, JS, Xaml, C++ and Xml as the original sample did, and there were a few issues with getting the text to properly align. However the “trick” he applied was simple but clever: Put a TextBox on top of the existing control, and make it transparent.

So I basically took Jeff’ awesome library, modified the template a bit, bound a TextBox with transparent text to the source code and put it on top of the existing template parts, tweaked the TextBox template to properly align and voila: The SyntaxHighlightingTextBlock is now a SyntaxHighlightingTextBox. I also added a couple of properties to the control to quickly get the selected text, set readonly state etc.

Jeff deserves most of the credit for this one, and Vladimir the rest for the neat TextBox trick. All I did was put it together, clean it up a bit and fix a couple of bugs in the highlighter. Expect to see this used in the next release of our SDK.

You can get the source here, and view the sample app here.

The library still only requires Silverlight 3, however the demo app uses Silverlight 4’ right-click feature for the context menu.

image

Update: Vlad took this sample further and improved rendering performance when editing larger amounts of code. See his updated blogpost here: http://www.vladhorby.com/blog/post/2010/11/01/code-editor-control-with-syntax-highlighting-for-silverlight-available.aspx
Isn't it great how the .NET community works together on building some useful stuff? Thanks Vlad!

Tags:

Silverlight

Add MouseWheel scrolling to Silverlight's DataGrid

by Morten 17. September 2009 20:31

In my previous post, I wrote about how you could add MouseWheel scrolling to the ScrollViewer using a simple behavior. I wanted to have the same MouseWheel scroll on the DataGrid, and thought that it could be done the exact same way.

However, it turns out that the DataGrid is not using a ScrollViewer, but instead used a Virtualized panel that is re-rendered every time a ScrollBar is scrolled. Unfortunately the DataGrid only reacts to the Scroll event of the ScrollBar, and not it’s Value property (not sure why they did it like this), so it’s not just a matter of finding the ScrollBar and increase the value. If I did that, the ScrollBar would move, but the DataGrid would not update. In fact the only way to raise the Scroll event was to click the ScrollBar, but I wanted to do this in code so I can’t really “click” something.

Fortunately Silverlight has a UIAutomation framework, that allows you to simulate user interaction. This is great for running automated tests against your controls, where you want to simulate a user clicking and typing inside your application. This got me thinking that the way to raise the Scroll event was simply to use the UIAutomation framework to virtually ‘click’ the ScrollBar. So in other words, each time you scroll down, the code ‘clicks’ the down button in the ScrollBar, and vice versa. While this simulated click approach works well, there’s an even simpler way, since the DataGrid’s Automation allows for calling scroll, which is what I’ll be using here.

The first step is to get a reference to the AutomationPeer of the DataGrid:

AutomationPeer automationPeer = FrameworkElementAutomationPeer.FromElement(this.AssociatedObject);

Since the automation peer for the DataGrid implements the IScrollProvider pattern, we can simply request that pattern and call Scroll() to scroll the DataGrid:

IScrollProvider scrollProvider = automationPeer.GetPattern(PatternInterface.Scroll) as IScrollProvider;
ScrollProvider.Scroll(ScrollAmount.NoAmount, ScrollAmount.SmallIncrement);

The rest is trivial for the DataGrid MouseWheel behavior. On the MouseWheel event of the DataGrid we call the Scroll method with either a SmallIncrement or SmallDecrement, and the DataGrid will scroll one row. It’s not as smooth as the ScrollViewer implementation in the previous blogpost, but at least it allows us to use the MouseWheel to scroll the rows. Since most scrollable controls in Silverlight already has UIAutomation and IScrollProvider support, this behavior will also work on other scrollable controls, and not only the DataGrid.

So here’s what it looks like in XAML when you included a reference to the behavior assembly:

<data:DataGrid x:Name="datagrid" Height="100" >
	<i:Interaction.Behaviors>
		<behaviors:MouseScrollBehavior/>
	</i:Interaction.Behaviors>
</data:DataGrid>

I’ve updated the source code for my Behavior library, and also updated the sample application to include the DataGrid.

Tags:

Silverlight Behaviors, Triggers and Actions

by Morten 11. August 2009 18:30

My recent new love when doing Silverlight Development is Expression Blend’s Interactivity API that gives you some really neat support for attaching behaviors, triggers and actions to your elements, which in turn lets you structure your code better and allows you to reuse it more often (It boggles my mind why these are not part of core Silverlight).

You can download the Expression Blend SDK for free here, but you also get it with Expression Blend 3.0.

How often haven’t you done something like this:

<Button OnClick=”ShowToolsWindow” Content=”Show Tools” />

and in the code behind:

private void ShowToolsWindow(object sender, RoutedEventArgs e)
{
            ToolsWindow.Visibility = Visibility.Visible;
}

While this probably isn’t much code, imagine a whole toolbar or menu each with code in two places, and especially the code-behind more or less the exact same, but with a different target. And if I remove a button, I also have to remember to remove the eventhandler. Enter triggers and actions…

With the Expression SDK we can create a trigger that does this for us.

public class ToggleVisibilityAction : TargetedTriggerAction<UIElement>
{
	protected override void Invoke(object parameter)
	{
		this.Target.Visibility = 
			this.Target.Visibility == Visibility.Visible ?
				Visibility.Collapsed : Visibility.Visible;
	}
}

What this allows us to do is the following in xaml and without using any code-behind:

<Button Content="Show Tools" Margin="20" >
	<i:Interaction.Triggers>
		<i:EventTrigger EventName="Click" >
			<behaviors:ToggleVisibilityAction TargetName="ToolsWindow" />
		</i:EventTrigger>
	</i:Interaction.Triggers>
</Button>

While this might be a little more XAML than before, it cleanly separates the button into one little local piece, and also allows me to reuse the same behavior for multiple tools.

In the above case, I’m using a TargetedTriggerAction, meaning that it is triggered by one control, but acts on another. There are also non-targeted actions. For instance this one for toggling full screen:

public class ToggleFullScreenAction : TriggerAction<UIElement>
{
	protected override void Invoke(object parameter)
	{
		Application.Current.Host.Content.IsFullScreen = 
			!Application.Current.Host.Content.IsFullScreen;
	}
}
<Button Content="Toggle Fullscreen" >
	<i:Interaction.Triggers>
		<i:EventTrigger EventName="Click" >
			<behaviors:ToggleFullScreenAction />
		</i:EventTrigger>
	</i:Interaction.Triggers>
</Button>

Another more powerful item, is the behaviors. Behaviors allows us to add any logic to the control (or the application) it is attached to, when it gets attached. Basically there are two methods to override when creating a behavior: OnAttached and OnDetached. Usually this is where you will want to attach and detach eventhandlers to the element.

Here is one example that will hide an element if the application gets installed:

public class HideOnInstall : Behavior<UIElement>
{
	protected override void OnAttached()
	{
		base.OnAttached();
		Application.Current.InstallStateChanged += Current_InstallStateChanged;
	}

	protected override void OnDetaching()
	{
		base.OnDetaching();
		Application.Current.InstallStateChanged -= Current_InstallStateChanged;
	}

	private void Current_InstallStateChanged(object sender, EventArgs e)
	{
		this.AssociatedObject.Visibility = (Application.Current.InstallState == InstallState.Installed)
			? Visibility.Collapsed : Visibility.Visible;
	}
}

Now we can use that on our install button, so when the app has been installed, the button will automatically hide itself:

<Button Content="Install">
	<i:Interaction.Triggers>
		<i:EventTrigger EventName="Click" >
			<behaviors:InstallAction />
		</i:EventTrigger>
	</i:Interaction.Triggers>
	<i:Interaction.Behaviors> 
		<behaviors:HideOnInstall />
	</i:Interaction.Behaviors>
</Button>

A thing that has always bothered me is that the ScrollViewer control by default doesn’t listen to MouseWheel events. Delay recently blogged about adding smooth scrolling to the scroll viewer. Based on that, I changed this to be a behavior that listens to the MouseWheel event.

To do this we first create a behavior that inherits from Behavior<ScrollViewer>. This ensures that the behavior can only be attached to a ScrollViewer. In OnAttached we start listening for the MouseWheel event:

protected override void OnAttached()
{
       AssociatedObject.MouseWheel += AssociatedObject_MouseWheel;
       base.OnAttached();
}

In the event handler we just call AssociatedObject.ScrollToVerticalOffset(offset) to apply the scroll (The sample you can download here goes a little further and uses a DoubleAnimation with easing to make the scrolling more smooth). Now to add MouseWheel scrolling support to all scroll viewers, all you need to do is add the behavior to the scroll viewer:

<ScrollViewer>
	<i:Interaction.Behaviors>
		<behaviors:MouseScrollViewer />
	</i:Interaction.Behaviors>
</ScrollViewer>

The neat thing about these behaviors is that you get drag’n’drop behavior inside Expression Blend. This means that you can simply drag these from the Assets window right on to your elements without having to touch any code or XAML. Here’s what my sample application looks like in the objects and assets windows:

image

When I migrated this application from Silverlight 2 to 3, I managed to remove almost 70% of the code-behind in page.xaml.cs mostly caused by reusing simple actions and behaviors, and separating the logic into reusable classes instead. Later I found myself often going back to grab these classes and re-use them for other projects.

You can try out the sample application here and download the code here.

Tags:

Silverlight

ESRI ArcGIS Silverlight/WPF API released

by Morten 13. July 2009 16:25

Last week we finally released v1.0 RTW of our Silverlight/WPF API. Today at our User Conference in San Diego, Jack Dangermond announced, that it even will be free for non-commercial use. The API will run on both v2 and v3 of Silverlight.

Furthermore today we released the entire source code for the toolkit assembly on CodePlex: http://esrisilverlight.codeplex.com

Also today at the Windows Partner Conference, we announced MapIt, a mapping solution running on a combination of SQL Server 2008, IIS and Silverlight/WPF and also with integration into Sharepoint. You can download a free 60-day evaluation of MapIt today. I encourage you to go see some of the demonstration videos – especially if you are new to GIS, this video could be an eye-opener to what information is hidden in your existing business intelligence.

If you are at the ESRI User Conference this week, come by the Silverlight Island in the showcase area and talk some Silverlight. I’ll be there most of the time Tuesday through Thursday. I’ll also be joining Rex Hansen and Art Haddad at the .NET SIG Tuesday evening, and the Silverlight intro sessions Wednesday and Thursday. Also watch Rich’s Demo Theater session which will demonstrate the ESRI Map Web Part for SharePoint and MapIt (the title on this session is incorrect).

Tags:

ArcGIS Server | ESRI | ESRI Silverlight API | GIS | Silverlight

Silverlight 3 Released

by Morten 9. July 2009 10:32

Silverlight 3 RTW is finally out !

Find the downloads here:

Expression Blend 3 with Sketchflow

Silverlight 3 Software Development Kit (SDK)

Silverlight 3 Tools for Visual Studio 2008 SP 1

or just go here to install the plugin: http://www.microsoft.com/silverlight/resources/install.aspx

While most of the new SL3 features has already been announced with the beta release, below are some of the new stuff that wasn’t available in the beta.

Mouse Wheel support !

We finally get native mouse wheel support with Silverlight 3. This means support for wheel in full screen, out of browser, when the DOM bridge is disabled, and most importantly no more ugly JavaScript hacks to get this working. The API is exactly the same as in WPF.

image 

 

Multi Touch Support.

Scott Guthrie announced this feature a few months ago, but it wasn’t included in the beta. Below is what this new API looks like:

image

Compared to the Surface API it looks like a fairly low-level version. The touch points you get will tell you if the user started touching, let go or is moving the finger, and also has methods for getting the element that is directly under the touch point. It’s up to the developer to then convert these gestures to something meaningful. The new behaviors API might come in handy for streamlining this.

Our prototype lab has already created some cool demos using Microsoft’s Surface table and our WPF API, and hopefully we can easily extend that to our Silverlight API as well.

 

Support for Alpha in 8bit PNG.

To me this is huge! We can finally start optimizing the download size by using PNG8 images and still have an alpha channel. Unfortunately Microsoft forgot 1, 2 and 4 bit, which a lot of optimized PNGs end up being. Hopefully that’ll come in a later version (judging from the PNG spec, there really isn’t much difference between 1, 2, 4 and 8 bits).

Out of browser changes

Out of browser configuration has been changed, and can now be configured using the UI tool in Visual Studio project properties:

image

Clear-type support

All browsers now get clear-type rendering of fonts.

Tags:

Silverlight

About the author

Morten Nielsen

Silverlight MVP

Morten Nielsen
<--That's me
E-mail me Send mail

Twitter @dotMorten 

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2005-2014

Month List

Recent Comments

Comment RSS