Skip to content

SilverlightShow: Silverlight Community
Syndicate content
Silverlight articles, Silverlight tutorials, Silverlight videos, Silverlight samples
Updated: 52 sec ago

Favorite Tool and Library Downloads for Silverlight

11 hours 41 min ago
Adam Kinney has a list with 17 tools that you need to know about when working with Silverlight.

I’ve created my list of favorites tools and libraries and posted them to the Downloads page on the Project Rosetta site. After posting the updated list yesterday I realized I missed two big ones: SilverSprite and Balder.

Breaking the new list down into categories, I ended up with 3 Essential, 4 Optional and 10 Specialty downloads.

Categories: Communities

Introducing the Earthquake Locator – A Bing Maps Silverlight Application, Part 1

12 hours 5 min ago
Bobby Diaz has created a nice Bing Maps application that shows the location and relative strength of recent seismic activity.

The recent wave of earthquakes (no pun intended) being reported in the news got me wondering about the frequency and severity of earthquakes around the world. Since I’ve been doing a lot of Silverlight development lately, I decided to scratch my curiosity with a nice little Bing Maps application that will show the location and relative strength of recent seismic activity.

Categories: Communities

MVVM with Prism 101 – Part 6b: Wrapping IClientChannel

12 hours 22 min ago
In his last MVVM with Prism post, Mark J. Miller talks about wrapping IClientChannel.

I could have used the title “Ditching Client Service Proxy” or “Avoiding Add Service Reference”, but that’s not what the meat of the post is about. However, that is essentially the goal of this post. The client service proxy generated when you use “Add Service Reference…” to reference your web service from your client project is used by almost every demo I know. It quickly generates a proxy class for you that at first blush is “the bee’s knees”.

Here you can find all parts from the series:
Categories: Communities

1 Simple Step for Commanding in Silverlight

12 hours 39 min ago
Christopher Bennage has a blog post about commands in Silverlight 4.

Silverlight 4 is now supporting the commanding that we’ve come to love from WPF. Commanding was a foundational feature for MVVM. It’s what enabled us to bind to methods on our view models.

Categories: Communities

Uploading and downloading images from WCF in Silverlight

12 hours 44 min ago
Uploading and downloading images using a WCF service with Silverlight

Quite often, when browsing the web, we encounter a situation where we are required to upload a file. When I want to register myself on a forum, I often get the question if I want to upload an avatar. Or when using a social networking site such as Facebook, I can upload pictures of me doing something that probably no one is interested in. The point I’m trying to make here is that when developing in Silverlight, we’ll also come in a situation where we want our users to upload files such as images to the server. Next to uploading, users may want to download files such as images, which are stored as a physical file on the server as well.

In both cases, WCF can help us out, allowing us to create services that are capable of working with an uploaded file as well as processing a requested file for download. In this article, I’ll be showing a sample Silverlight application where users can upload and download images from using a WCF service. The interface is very simple; a screenshot is shown below.

Picture1

Included with this article is the sample code, which can be downloaded here. We’ll be using this code to show how the upload and download process works.

Uploading a file to the server

We’ll start by looking at the upload process. We need to write code both on the server side and on the client side.

Server-side: a WCF servoce

To allow a Silverlight application to send files to the server-side and store these on the file system of the server, we’ll start by creating a WCF service. In the sample code, this service is named PictureService. In the service contract, IPictureService, we define a method called Upload, which accepts an instance of PictureFile.

[ServiceContract]
public interface IPictureService
{
    [OperationContract]
    bool Upload(PictureFile picture);
}

The PictureFile class is defined as DataContract; it defines two fields namely the filename and the contents of the file. The latter is stored as a byte stream. Both these properties are attributed with the DataMemberAttribute, meaning that both will travel over the wire when send from and to the service.

[DataContract]
public class PictureFile
{
    [DataMember]
    public string PictureName { get; set; }
 
    [DataMember]
    public byte[] PictureStream { get; set; }
}

Now that we have defined the contract for the service, let’s take a look at the implementation. The logic here relies on System.IO. Basically, the Silverlight client application will upload a file as a stream of bytes (using an instance of the above defined class PictureFile). This stream of bytes is to be converted to a file on the server. The following code does just that: using a BinaryWriter, we grab the sent bytes and save them as a file. The location of the upload directory is stored here in the web.config.

[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class PictureService : IPictureService
{
    public bool Upload(PictureFile picture)
    {
        FileStream fileStream = null;
        BinaryWriter writer = null;
        string filePath;
 
        try
        {
            filePath = HttpContext.Current.Server.MapPath(".") + 
                       ConfigurationManager.AppSettings["PictureUploadDirectory"] + 
                       picture.PictureName;
 
            if (picture.PictureName != string.Empty)
            {
                fileStream = File.Open(filePath, FileMode.Create);
                writer = new BinaryWriter(fileStream);
                writer.Write(picture.PictureStream);
            }
 
            return true;
        }
        catch (Exception)
        {
            return false;
        }
        finally
        {
            if (fileStream != null)
                fileStream.Close();
            if (writer != null)
                writer.Close();
        }
    }
}

By default, WCF only accepts messages with a maximum length of 65536 bytes. This is however, not enough for sending normal files to the server. We should therefore make some configuration changes to our service so that the larger uploads are accepted. To do so, I’m specifying a custom binding configuration for the basic HTTP binding. Here, I’m allowing uploads of 2.000.000 bytes, meaning 2MB, you can of course specify another value here.

<bindings>
    <basicHttpBinding>
        <binding name="PictureBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
            <readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
        </binding>
    </basicHttpBinding>
</bindings>

Because this WCF service is to be connected to from Silverlight, the binding itself should of course be a BasicHttpBinding and not a wsHttpBinding which is the default for WCF.

At this point, our service has all it needs to start accepting uploads from Silverlight. Let’s turn our attention to the client now.

Client side: the Silverlight application

The first thing we should do is letting our Silverlight application know about the PictureService by adding a service reference to the service within the Silverlight project. Here I set the namespace to PictureService.

Picture2

Visual Studio creates for us a proxy. Included in the client proxy is a client side copy of the PictureFile class.

To allow the user of the application to upload a file from the local file system, we use the OpenFileDialog class. Within Silverlight, this class gives us a read-only stream to a local file. Apart from reading the contents of the file, Silverlight can’t perform other actions on the file such as deleting or renaming. Using the OpenRead method, we get access to the above mentioned stream which we can then read out using the Read method into a byte array.

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "JPEG files|*.jpg";
if (openFileDialog.ShowDialog() == true)
{
    Stream stream = (Stream)openFileDialog.File.OpenRead();
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, (int)stream.Length);
 
    string fileName = openFileDialog.File.Name;
}

We’re can now try uploading the file. We therefore create a new instance of the PictureFile class, passing in a name for the file and the byte array.

PictureService.PictureFile pictureFile= new FileUpAndDownload.PictureService.PictureFile();
pictureFile.PictureName = fileName;
pictureFile.PictureStream = bytes;

All that’s left now is creating a proxy instance. As with all other service communication within Silverlight, service communication works asynchronously. Therefore, we define a callback which will be invoked when the upload is finished.

PictureService.PictureServiceClient client = new FileUpAndDownload.PictureService.PictureServiceClient();
client.UploadCompleted += new EventHandler
    <FileUpAndDownload.PictureService.UploadCompletedEventArgs>(client_UploadCompleted);
client.UploadAsync(pictureFile);

In the callback, we can check if the service interaction went OK or if there where any errors.

void client_UploadCompleted(object sender, FileUpAndDownload.PictureService.UploadCompletedEventArgs e)
{
    if (e.Error == null)
    {
        if (e.Result)
        {
            ResultTextBlock.Text = "Upload succeeded :)";
        }
        else
        {
              ResultTextBlock.Text = "Upload failed :(";
        }
    }
}

With that, we are ready to try our upload process. The image below shows the upload working.

Picture3

Let’s now look at how we can download files.

Downloading files from the server

When it comes to downloading images, we could in most cases solve things by simply using a link to the original file and sending this link back to the client Silverlight application. However, in some cases, this link can’t be created. Take for example the case where images are stored within a database. Or another possibility here is that images are stored on a non-publicly available folder on the server. In both these cases, we need to send the byte information to the client using a service again. In the client Silverlight application, we can then recreate the file and use it within our app. Let’s look at the code to do this.

Service changes

For this sample, we’ll allow the user to enter the name of the picture he or she wishes to download, so we’ll pass in a string as argument for a new method, quite logically named Download, on our WCF service. In the service contract, I added the following code:

[OperationContract]
PictureFile Download(string pictureName);

As we can see here, this operation defines that we are sending to the client an instance of the PictureFile class (the same class as we used for the upload process). The file that will thus be sent to the client, will be sent as a byte array. In the implementation code, we check if the file exists first. If it does, we use a BinaryReader to read the contents of the file, create he PictureFile instance and return it.

public PictureFile Download(string pictureName)
{
    FileStream fileStream = null;
    BinaryReader reader = null;
    string imagePath;
    byte[] imageBytes;
 
    try
    {
        imagePath = HttpContext.Current.Server.MapPath(".") +             
        ConfigurationManager.AppSettings["PictureUploadDirectory"] + 
        pictureName + ".jpg";
        
        if (File.Exists(imagePath))
        {
            fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
            reader = new BinaryReader(fileStream);
 
            imageBytes = reader.ReadBytes((int)fileStream.Length);
 
            return new PictureFile() { PictureName = pictureName, PictureStream = imageBytes };
        }
        return null;
    }
    catch (Exception)
    {
        return null;
    }
}

The service’s configuration code does not need to be changed for this new operation.

Changes to the Silverlight client

Within the Silverlight client, update the web service reference. Visual Studio will update the proxy class, making the new Download method available. Upon clicking the button, we’ll launch a request to the service asynchronously, passing in the filename.

private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
    PictureService.PictureServiceClient client = 
        new FileUpAndDownload.PictureService.PictureServiceClient();
    client.DownloadCompleted += 
        new EventHandler<FileUpAndDownload.PictureService.DownloadCompletedEventArgs>(client_DownloadCompleted);
    client.DownloadAsync(FileNameTextBox.Text);
}

Upon completion of the service call, the callback method is invoked. If no errors occur, we receive a PictureFile instance, containing the bytes of the requested file. Here we know that the file is in fact an image, so we use it to display the picture in an Image control.

BitmapImage image = new BitmapImage();
if (e.Error == null)
{
    if (e.Result != null)
    {
        ImageDownloadService.ImageDownload imageDownload = e.Result;
        MemoryStream stream = new MemoryStream(imageDownload.Image);
        image.SetSource(stream);
        ResultImage.Source = image;
    }
    else
    {
        ErrorTextBlock.Text = "No image with that name exists";    
    }
}
Summary

To send files from and to a service from within a Silverlight application, we can use a WCF service, which accepts a byte array, optionally wrapped in a class like we did here with the PictureFile class. In this example, we looked at how to do this with images; however, the method is similar for other file types.

Gill Cleeren is Microsoft Regional Director (www.theregion.com), MVP ASP.NET, INETA speaker bureau member and Silverlight Insider. He lives in Belgium where he works as .NET architect at Ordina. Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF. He also leads Visug (www.visug.be), the largest .NET user group in Belgium. He’s the author of the upcoming book called Silverlight 4 Data and Services Cookbook. You can find his blog at www.snowball.be.

Categories: Communities

A syntax highlighting TextBlock for Silverlight 3

12 hours 54 min ago
Jeff Wilcox has adapted a syntax highlighting engine to generate a syntax highlighting TextBlock control for Silverlight

Add the control assembly to your Silverlight project. Then, add an XMLNS prefix to your Silverlight page where you’d like to use the control.

There are two properties of interest that should be set or bound: SourceCode (the actual source text), and SourceLanguage

Categories: Communities

Cool demonstration of Silverlight VideoBrush

13 hours 10 min ago
Tim Greenfield has a demonstration of a fun and novel use of the VideoBrush in Silverlight.

Silverlight provides a variety of brushes that can be used to paint just about any area in your app: from text to shapes to borders. The most common brushes are for painting color and images: SolidColorBrush,LinearGradientBrush, RadialGradiantBrush, and ImageBrush.However, today I paired the less common VideoBrush with an unusual visual element.

Categories: Communities

25 Inspiring Silverlight Websites, Videos and Customer Stories

13 hours 29 min ago
Arturo Toledo has published a list with the coolest Silverlight videos, websites and customer stories.

As part of the CRE8 Conference last week in Miami, August de los Reyes and I presented a collection of the cool videos, websites and customer stories. Here is a great list for you with the best of best in Silverlight and UX.

Categories: Communities

Watermark Textbox Part III

Mon, 03/08/2010 - 11:29
The final part of the tutorial of Phil Middlemiss on building a Watermarked TextBox control is now here. In Part 1 and Part 2 Phil created the visual elements for the Watermarked TextBox UserControl
Thumbnail for Watermarked TextBox controlIn this conclusion to the tutorial, we write a little bit of code to make all the parts of the UserControl work together.
Categories: Communities

Free Silverlight 4 Beta Theme

Mon, 03/08/2010 - 11:20
Felix Corke has designed a theme called Blackspike using the new Implicit Style feature.

I am playing with Silverlight 4 beta a lot at the moment, and one of its best features is the new Implicit Styles. This means that I can design a Silverlight theme for all the controls, and all developers have to do is include my supplied Resource Dictionary and all their controls will be skinned.So I’ve made a theme called Blackspike, please download it and try it out on your project.

Categories: Communities

InvalidOperation_EnumFailedVersion when binding data to a Silverlight Chart

Mon, 03/08/2010 - 09:39
Jim Lynn had a problem when binding data to a Silverlight Toolkit chart and decided to post the workaround in case someone else needs it.

We’re releasing an analytics application in Silverlight to people inside the BBC. Today is release day, and we had some last-minute tweaks we wanted to roll out. Unfortunately, some of our customers were reporting a strange error when they tried this new version.

Categories: Communities

Past and current state of Smooth Streaming Development

Mon, 03/08/2010 - 09:26
Ola Karlsson has published this post in which he shares his experiences with Smooth Streaming development.

Over the last year, a rather large part of my development work has included working with IIS Smooth Streaming, especially in relation to Silverlight. When I started looking at Smooth Streaming, about a year ago, there were not many places around the web where you could find Smooth streaming development related resources. And although the pictures is somewhat better today, there’s still not a whole lot of good material around, so I thought I’d try and putt together some posts sharing my experiences with Smooth Streaming development. 

Categories: Communities

How to: Easily rotate the axis labels of a Silverlight/WPF Toolkit chart

Mon, 03/08/2010 - 09:08
David Anson has written a post about rotating the axis labels of a chart.

When someone asked me how to rotate the axis labels of a chart from the Data Visualization package of the Silverlight Toolkit/WPF Toolkit earlier today, I realized it was time for a quick blog post. Because when I've answered a question two or three times, it's usually a pretty good sign that I'll keep on answering it for some time. I usually try to head that kind of thing off at the pass, so here's my post on the topic for the benefit of future generations.

Categories: Communities

Enhancing Silverlight Video Experiences with Contextual Data

Mon, 03/08/2010 - 08:56
Jit Ghosh has a great post about Smooth Streaming with Silverlight and adding context data to your video.

There are two primary requirements for enabling a glitch-free viewing experience in Web-based, high-definition digital video delivery. First, the video provider needs to support high video delivery bit rates over the network. Second, the client computer needs to support continuous availability of processing capacity to decode the video at its fullest resolution.

Categories: Communities

XAML Attributes on Separate Lines

Mon, 03/08/2010 - 08:42
In this post, Christopher Bennage demonstrates how to get all your XAML attributes on separate lines by using Visual Studio.

I initially started using this option because it made code samples easier to read (especially when going to print). However, a more valuable reason is that this practice is source control friendly.

Categories: Communities

&quot;What's New in Silvelright 3&quot; Video from 0reDev

Mon, 03/08/2010 - 08:28
Shawn Wildermuth announces that his "What's New in Silverlight 3" video has been just released.

Last fall I visited 0redev in Sweden and gave a "What's New in Silverlight 3" talk. THey've just released the video if you interested in wathcing it.

Categories: Communities

DotNetNuke&#174; Silverlight Traffic Module

Mon, 03/08/2010 - 08:07
Michael Washington has created a simple module that tracks the visitors to a page for the current day and the past hour, and displays the results using Silverlight gauges.Image 

This application is more of an example of what is possible with Silverlight and DotNetNuke rather than it is a practical application. Instead of just showing traffic to the page, the gauges could show more relevant data such as total orders placed, or the number of help desk tickets (there are plans to use this in a future version of http://ADefHelpDesk.com).

Categories: Communities

How to extend Bing Maps Silverlight with an elevation profile graph - Part 1

Mon, 03/08/2010 - 03:40
Introduction

One of the things I found missing in the current Bing Maps product is the possibility to create an elevation surface profile of routes. Perhaps this feature may not seem much on demand but actually affects more people than expected. Think for example about sports events like marathons and cycling races: to see a preview of the elevation profile of the trail would be of great benefit to the participants. But even if you're just simple hikers you might want to know what is the difference in level of your walking or bicycle trip to better understand the effort that it would entail.
So why not try to create this feature from scratch using the Bing Maps Silverlight Control? In this first part we will see how to extend the Bing Maps Silverlight Control by adding new commands to the navigation bar, how to create a route based on a start and end address or by clicking directly on the map and how to obtain elevation data of the route. In the second part we will briefly deal with details about the implementation via threads of the elevation data retrieval and we will show how to add some interactivity to the Chart control of the Silverlight toolkit.
I assume that the reader is already familiar with the basics related to the use of Bing Maps in Silverlight. If not so, I would like to suggest reading the first chapters of the SDK guide or at least the "Getting started" paragraph of the following interesting article already published on SilverlightShow.
In the second part a link to the live demo and to the source code will be made available; in the meantime you can watch a video here of an early beta.

The User Interface

What I wanted to do was to add this type of functionality to the Bing Maps Silverlight Control integrated with the existing interface. With this aim in mind I added 2 items to the navigation bar of the Bing Maps Silverlight Control as you can see on the following image, where the items “Route Profile“ and “Arbitrary Profile” have been added.

Navigation Bar Extended

A click on “Route Profile” item opens a popup window which allows choosing 2 options:

  • Building the route by inserting pushpins on the map
  • Building the route providing a start address and an end address

With the first option you can put a series of pushpins on the map with a simple click of the mouse on the map; a double click starts the route calculation and, after that, the generation of the elevation profile graph. The second option considers first the geocoding of the start and end address of our route and then proceeds in the same way as the first option.
A click on “Arbitrary Profile”, instead, allows you to draw polylines directly on the map; even here a double click of the mouse triggers the generation of the route and the subsequent creation of the elevation profile graph.

The graph offers some kind of interactivity in the way that you can select and move 2 cursors over the points of the profile and see some conclusive data like the average elevation with regard to the portion of the profile between the two cursors.

User Interface Main points of interest

An interesting element is the description of how it was possible to add new commands to the navigation bar of the Bing Maps Silverlight Control without giving the impression of a last minute addition but of a natural integration. Another point which might be of interest for the reader is the retrieval of the elevation data and the subsequent creation of the profile graph; during the process the user is allowed to interact with the map thanks to the use of threads. Finally, the possibility to interact with the Chart control can offer some ideas for further improvements.

How to How to add items to the navigation bar of the Bing Maps Silverlight Control

The first thing I thought of doing to achieve this objective was to understand how the navigation bar was made. Obviously to better understand that I needed to see the XAML code which generates the navigation bar; but, how to get the XAML code? The setup of the Bing Maps Silverlight Control SDK (which can be downloaded at the following link ) installs two DLL files on your pc : “Microsoft.Maps.MapControl.dll” and “Microsoft.Maps.MapControl.Common.dll”. They contain all the assemblies needed in order to use the Silverlight Bing Maps Control in your applications. While I was looking inside the installation folders in order to find an inspiration at some point I remembered reading somewhere on the web that one could just open the DLL in a text editor and see the XAML code in plaintext. Indeed, if you open the "Microsoft.Maps.MapControl.dll" file and scroll down the content, at a certain point you see a large portion of XAML code and there is where you have to investigate. If you look at the code below which is the part describing how it is organized the superior portion of the navigation bar:

   1: <StackPanel Grid.Row="0" Grid.Column="3" Orientation="Horizontal" x:Name="HorizontalPanel">
   2:     <StackPanel Orientation="Horizontal" x:Name="HorizontalLeftPanel">
   3:         <navigation:CommandRadioButton x:Name="RoadStyleButton"  />
   4:         <navigation:CommandRadioButton x:Name="AerialStyleButton"  />
   5:     </StackPanel>
   6:     <navigation:CommandSeparator />
   7:     <StackPanel Orientation="Horizontal" x:Name="HorizontalRightPanel">
   8:         <navigation:CommandToggleButton x:Name="LabelsButton" />
   9:     </StackPanel>
  10: </StackPanel>

You see that there is a StackPanel (called “HorizontalPanel”) which contains two other StackPanels called respectively “HorizontalLeftPanel” and “HorizontalRightPanel”. Inside them, there are the buttons you are used to clicking when you interact with the Bing Maps Silverlight Control, i.e. “Road”, “Aerial” and “Labels”.

So, if you want to add two other commands as in the first image above, in principle you just have to create two instances of the type CommandRadioButton (which is in the assembly Microsoft.Maps.MapControl.Navigation) and add them to the “HorizontalPanel” as children controls. But the reality is somewhat more complicated than just described. In order to add these controls you have to wait for the completion of the initialization phase of some components. This phase, without going too much over details, can be regarded as made up of 2 steps. A first step where the ForegroundMap Control is loaded; this is the control which displays amongst other the map navigation bar on the map. A second step where the navigation bar is loaded. Only after these two phases you can add your controls. In practical terms first you have to add an EventHandler to the TemplateApplied EventHandler of the ForegroundMap Control. When the event is triggered it means that the NavigationBar has been instantiated and you can add another EventHandler this time to the TemplateApplied EventHandler of the NavigationBar. Once this last event is triggered you can add your controls to the NavigationBar. The portion of code below realizes what I have just described.

   1: ...
   2: private CommandRadioButton routeBtn = new CommandRadioButton();
   3: private CommandRadioButton freeProfileBtn = new CommandRadioButton();
   4: ...
   5: public MainPage()
   6: {
   7:     InitializeComponent();
   8:     ...
   9:     ElevationChartMap.MapForeground.TemplateApplied += new EventHandler(MapForeground_TemplateApplied);
  10:     ...
  11: }
  12:  
  13: void MapForeground_TemplateApplied(object sender, EventArgs e)
  14: {
  15:     ElevationChartMap.MapForeground.NavigationBar.TemplateApplied += new EventHandler(NavigationBar_TemplateApplied);
  16: }
  17:  
  18: void NavigationBar_TemplateApplied(object sender, EventArgs e)
  19: {
  20:      NavigationBar navControl = ElevationChartMap.MapForeground.NavigationBar;
  21:  
  22:      navControl.HorizontalPanel.Children.Add(routeBtn);
  23:      navControl.HorizontalPanel.Children.Add(freeProfileBtn);
  24: }
  Creating the route with the “Route Profile” option

For the creation of the route either giving start and end address or inserting some markers on the map I used part of the code samples available on Keith Kinnan’s Blog and presented during the PDC09. I don’t want to repeat what has been already very well explained at the links above so I will stick to a brief description.
First of all, you have to create two service references, the Geocode service and the Route service:

https://staging.dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc?wsdl

https://staging.dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc?wsdl

Don’t forget the final postfix “?wsdl” which is missing in the related paragraph (“Calculating a Route Using Bing Maps Web Services “) of the SDK Guide version 1.01.
With the first Service you obtain the coordinates of the user location inputs; these coordinates can be then provided to the Route Service to calculate the route. Since Silverlight uses an asynchronous model all the requests to the Services above have to be asynchronous. For instance, after you inserted the start and end address of your route, two asynchronous calls to the Geocode Service are made. To catch them, an EventHandler to the GeocodeCompleted event has been added. Inside this EventHandler we keep track of how many times it was crossed; if it has been twice it means that both start and end address have been elaborated and then it is possible to make the request to the Route Service, where another EventHandler has been added to intercept the CalculateRouteCompleted event. In this EventHandler the result of the calculation is checked and if it is Ok the Polyline representing the route is drawn. In particular an object of type MapPolyline is instantiated and the points in geographic coordinates resulting from the calculation are added to its "Locations" property. This object is then added to a MapLayer which represents a layer over the map and allows to position UI elements according to geographic coordinates. The code below illustrates what I have described.

   1: double dist = e.Result.Result.Summary.Distance;
   2: Color routeColor = Colors.Blue;
   3: SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
   4:                
   5: //Add the Polyline for the route
   6: MapPolyline routeLine = new MapPolyline();
   7: routeLine.Locations = new LocationCollection();
   8: routeLine.Stroke = routeBrush;
   9: routeLine.Opacity = 0.65;
  10: routeLine.StrokeThickness = 5.0;
  11: foreach (Location loc in e.Result.Result.RoutePath.Points)
  12: {
  13:     routeLine.Locations.Add(loc);
  14: }
  15: profileLayer.Children.Add(routeLine);

“Arbitrary Profile” option: how to allow the user to draw lines directly on the map

The “Arbitrary Profile” option gives the user the chance to draw a completely arbitrary polyline with subsequent mouse clicks; you can either follow the profile of a road or click on whatever you want. A double click ends the drawing mode and launches the generation of the elevation profile graph. To do that two EventHandlers have been added to the Map Control in order to intercept the mouse click and double click on the map. In case of a single click, the ViewportPoint of the MouseEventArgs object is evaluated and the result is added to the Locations Collection of a MapPolyline previously added as a child UI element to the same MapLayer used for route showing. 

   1: ...
   2: private MapPolyline arbitraryProfilePolyline;
   3: ...
   4:  
   5: void ElevationChartMap_MouseClick(object sender, MapMouseEventArgs e)
   6:   {
   7:       if (myProfileModeMap.EnableArbitraryProfileMode == true)
   8:       {
   9:           arbitraryProfilePolyline.Locations.Add(ElevationChartMap.ViewportPointToLocation(e.ViewportPoint));
  10:       }
  11:       ...

Summary

In this first part we have explored some “internals” of the navigation bar of the Bing Maps Silverlight Control and we have given some advice on how to create routes using Geocoding and Route Services and on how to draw lines on the Map and obtain the geographics coordinates of its points. In the next article we will see how to obtain elevation data for the routes and the arbitrary paths we created and how to customize the Chart Control of the Silverlight Toolkit for the needs of this specific application. You will be also able to try a live demo and download the source code.

Categories: Communities

Watermarked Textbox Part II

Fri, 03/05/2010 - 09:59
Part II of the tutorial of Phil Middlemiss on building a Watermarked Textbox control is now here. In the first post Phil created the visual elements for the WatermarkedTextbox user control.
Watermarked Textbox imageIn Part II we finish defining the visual elements, and create the animations for the various states the control requires
Categories: Communities

Twisting Navigation

Fri, 03/05/2010 - 09:28
If you are tired of using menues or buttons to let the user navigate your website then this Twisting Navigation example created by LawBot might be the right navigation surface.

I implemented some projections to let it twist along the zero point of the x and y axis when the user hovers over it. Combined with a slight DropShadowEffect the result is a very cool 3D effect. Just take a look at it and enjoy playing around with it.View and enjoy the example and download the sourcecode at the Expression Gallery. If you like it give me some stars. If not please leave a comment.

Categories: Communities