Friday, December 16, 2011

How to customize Esri’s Silverlight TimeSlider

image

The Esri ArcGIS SIlverlight Toolkit SDK is a companion of Esri’s ArcGIS API for Silverlight. The toolkit includes a number of useful controls including a magnifier, scale bar and an info window to display map popup windows. This post will demonstrate how to customize (or style) the toolkit’s TimeSlider control.

To view a live application click here.
To download the full source code click here.

By default, the toolkit’s TimeSlider looks like this:

image

With a style applied it is possible to transform the TimeSlider to look like this:

image

To achieve this appearance you but include the follow two styles as a resource. The first style is for the Thumb.

<Style x:Key="SleekThumb" TargetType="Thumb">
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="IsTabStop" Value="False"/>
    <Setter Property="Height" Value="12"/>
    <Setter Property="Width" Value="12"/>
    <Setter Property="Cursor" Value="Hand"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Thumb">
                <Grid>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver"/>
                            <VisualState x:Name="Pressed" />
                            <VisualState x:Name="Disabled" />
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="FocusStates">
                            <VisualState x:Name="Focused"/>
                            <VisualState x:Name="Unfocused"/>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Ellipse Fill="{TemplateBinding Background}"
Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}"
Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="{TemplateBinding BorderThickness}"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter
>
</
Style
>

And then the TimeSlider itself.

<Style x:Key="SleekTimeSlider" TargetType="esri:TimeSlider">
    <Setter Property="IsTabStop" Value="False" />
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="esri:TimeSlider">
                <Grid>
                    <!--VisualState wiring - not used-->
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver"/>
                            <VisualState x:Name="Disabled"/>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="FocusStates">
                            <VisualState x:Name="Focused" />
                            <VisualState x:Name="Unfocused"/>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>

                    <!-- Slider core -->
                    <Grid x:Name="HorizontalTrack">
                        <!--Hide tick marks (but still used for snapping)-->
                        <esriToolkitPrimitives:TickBar x:Name="TickMarks"
Margin="0,0,0,0"
IsHitTestVisible="False">
                            <esriToolkitPrimitives:TickBar.TickMarkTemplate>
                                <DataTemplate>
                                    <Grid />
                                </DataTemplate>
                            </esriToolkitPrimitives:TickBar.TickMarkTemplate>
                        </esriToolkitPrimitives:TickBar>

                        <!--Background Track-->
                        <Rectangle Height="3" Margin="5,0"
StrokeThickness="{TemplateBinding BorderThickness}"
Fill="LightGray"/>

                        <!--Left repeater button-->
                        <RepeatButton
                           x:Name="HorizontalTrackLargeChangeDecreaseRepeatButton"
                                                           
                          
IsTabStop="False"
                                 
                          
HorizontalAlignment="Stretch"
                           Opacity="0" />

                        <!--Minimum thumb-->
                        <Thumb
                           x:Name="MinimumThumb"
                          
                          
DataContext="{TemplateBinding Value}"
                           ToolTipService.ToolTip="{Binding Start}"
 
                          
ToolTipService.Placement="Top"
                           HorizontalAlignment="Left"
                           Foreground="{TemplateBinding Foreground}"
                           Style="{StaticResource SleekThumb}" />

                        <!--Middle thumb-->
                        <Thumb
                           x:Name="HorizontalTrackThumb"
                                                                                                                         
                          
IsTabStop="False"
                           Cursor="Hand"
                           HorizontalAlignment="Left"
              
                          
Foreground="{TemplateBinding Foreground}">
                            <Thumb.Template>
                                <ControlTemplate>
                                    <Rectangle Height="3"
Fill="{TemplateBinding Foreground}" />
                                </ControlTemplate>
                            </Thumb.Template>
                        </Thumb>

                        <!--Maximum thumb-->
                        <Thumb
                           x:Name="MaximumThumb"
                                   
                          
DataContext="{TemplateBinding Value}"
ToolTipService.ToolTip="{Binding End}"
 
                          
ToolTipService.Placement="Top"
                           HorizontalAlignment="Left"
                           Foreground="{TemplateBinding Foreground}"
                           Style="{StaticResource SleekThumb}" />

                        <!--Right repeater button-->
                        <RepeatButton
                           x:Name="HorizontalTrackLargeChangeIncreaseRepeatButton"
   
                          
IsTabStop="False"
                                   
                          
HorizontalAlignment="Stretch"
                           Opacity="0" />
                    </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter
>
</
Style
>

The XAML page containing two styles above must have the following namespaces defined.

xmlns:esri="http://schemas.esri.com/arcgis/client/2009"
xmlns:esriToolkitPrimitives=
"clr-namespace:ESRI.ArcGIS.Client.Toolkit.Primitives;
assembly=ESRI.ArcGIS.Client.Toolkit"

Finally, apply the style to the TimeSlider as shown below.

<esri:TimeSlider
   Grid.Row="1"
   x:Name="TimeSlider"
   TimeMode="TimeExtent"
   Foreground="Black"

    Style="{StaticResource SleekTimeSlider}"
/>

In closing, the controls included in the ArcGIS Silverlight Toolkit are no different from other controls with respect to styling and templating. To assist with styling other toolkit controls I would recommend browse the toolkit’s source code on codeplex. Alternatively you can just tweak the XAML in the post to fit your needs.

Thursday, December 15, 2011

How to use WPF in a web service?


Using WPF in a web service might seem bizarre, but consider the following scenarios:
  1. You need to burn in a watermark into images requested from web application,
  2. You want to apply a red-eye reduction process to photographs takes from a mobile application, or
  3. You want to apply a Jason Bourne night effect to images in a web mapping application.
We recently implemented something similar to the third scenario (see blog, source, live app). A client web application written in JavaScript, Flex or Silverlight could apply an image rendering effects by parsing an image’s url through a proxy service. The proxy service, using WPF, would apply a bitmap effect and return a modified image. This technique adds the power of WPF to thin client at the cost of minimal network latency.
Below is a detailed description of this proxy web service.
The following class is an ASP.NET generic web handler called “invert”. When published it will be accessible as ../virtualdirectory/invert.ashx. and will perform a color negative effect on parsed images. Because our server is accommodating multiple effects, one effect per handler, the web context is handed to static method to reduce the amount of redundant code.
public class Invert : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        Shader.Process(context, ShaderType.Invert);
    }
    public bool IsReusable {
        get { return false; }
    }
}
The code below is performing a number of important tasks. Firstly, because this proxy is published on the internet we need to add some restrictions so that it is only used as intended. The proxy will only entertain requests from web applications published on the maps.esri.com domain and it will only process images hosted on the services.arcgisonline.com domain. If the proxy request is legitimate, the remote image is downloaded and passed to a new background thread. The key is the creation of a background thread with a single-threaded apartment which is required to use COM and hence WPF.  The proxy (or IIS) process is put only hold as the WPF operation is underway.  The background thread returns a new image as an array of bytes which are then passed back to the client.
public class Shader {
    public static void Process(HttpContext context, ShaderType effect) {
        // Only accept request from apps from this domain!
        if (!context.Request.UrlReferrer.ToString().ToLowerInvariant().
                Contains("maps.esri.com")) {
            context.Response.StatusCode = 403;
            context.Response.End();
            return;
        }
            
        // Check for query string
        string query = Uri.UnescapeDataString(context.Request.QueryString.ToString());
        if (string.IsNullOrEmpty(query)) {
            context.Response.StatusCode = 403;
            context.Response.End();
            return;
        }
 
        // Filter requests
        if (!query.ToLowerInvariant().Contains("services.arcgisonline.com")) {
            context.Response.StatusCode = 403;
            context.Response.End();
            return;
        }
 
        // Create web request
        WebRequest webRequest = WebRequest.Create(new Uri(query));
        webRequest.Method = context.Request.HttpMethod;
 
        // Send the request to the server
        WebResponse serverResponse = null;
        try {
            serverResponse = webRequest.GetResponse();
        }
        catch (WebException webException) {
            context.Response.StatusCode = 500;
            context.Response.StatusDescription = webException.Status.ToString();
            context.Response.Write(webException.Response);
            context.Response.End();
            return;
        }
 
        // Exit if invalid response
        if (serverResponse == null) {
            context.Response.End();
            return;
        }
 
        // Configure reponse        context.Response.ContentType = serverResponse.ContentType;
        Stream stream = serverResponse.GetResponseStream();
 
        // Read response
        byte[] buffer = new byte[32768];
        int size = 0;
        int chunk;
        while ((chunk = stream.Read(buffer, size, buffer.Length - size)) > 0) {
            size += chunk;
            if (size != buffer.Length) { continue; }
            int nextByte = stream.ReadByte();
            if (nextByte == -1) { break; }
 
            // Resize the buffer
            byte[] newBuffer = new byte[buffer.Length * 2];
            Array.Copy(buffer, newBuffer, buffer.Length);
            newBuffer[size] = (byte)nextByte;
            buffer = newBuffer;
            size++;
        }
        serverResponse.Close();
        stream.Close();
 
        // Shrink buffer
        byte[] bytes = new byte[size];
        Array.Copy(buffer, bytes, size);
 
        // If the request is not a JPEG image then return data
        if (!serverResponse.ContentType.ToLowerInvariant().Contains("image/jpg")) {
            context.Response.OutputStream.Write(bytes, 0, bytes.Length);
            context.Response.End();
            return;
        }
 
        // Create class to send to STA backgroung thread
        ShaderWorker work = new ShaderWorker() {
            Source = bytes,
            ShaderEffect = effect
        };
 
        // Execute background thread
        Thread worker = new Thread(new ThreadStart(work.Execute));
        worker.SetApartmentState(ApartmentState.STA);
        worker.Name = "CreateImageWorker";
        worker.Start();
        worker.Join();
 
        // Return processed stream
        context.Response.OutputStream.Write(work.Target, 0, work.Target.Length);
        context.Response.End();
    }
}
This enumerator lists available pixel shaders. These shaders (or “effects”) were downloaded from the Windows Presentation Foundation Pixel Shader Effects Library.
public enum ShaderType {
    Emboss,
    Invert,
    Monochrome,
    Mosaic,
    Pixelate,
    Tint
}
And lastly, this is were the magic happens. This class is executed from the main IIS thread as a single-apartment thread as explained above. The source image is loaded as a generic BitmapImage in an Image, rendered with an effect and then exported to a new byte array.
public class ShaderWorker {
    public ShaderType ShaderEffect { private get; set; }
    public byte[] Source { private get; set; }
    public byte[] Target { get; private set; }
    public void Execute() {
        // Create bitmapimage
        MemoryStream m = new MemoryStream(this.Source);
        BitmapImage b = new BitmapImage();
        b.BeginInit();
        b.DecodePixelWidth = 256;
        b.DecodePixelHeight = 256;
        b.StreamSource = m;
        b.EndInit();
        b.Freeze();
 
        // Create image element
        Image i = new Image() {
            Source = b
        };
 
        // Assign shade effect
        switch (this.ShaderEffect) {
            case ShaderType.Emboss:
                i.Effect = new EmbossedEffect();
                break;
            case ShaderType.Invert:
                i.Effect = new InvertEffect();
                break;
            case ShaderType.Monochrome:
                i.Effect = new MonochromeEffect();
                break;
            case ShaderType.Mosaic:
                i.Effect = new MosaicEffect();
                break;
            case ShaderType.Pixelate:
                i.Effect = new PixelateEffect();
                break;
            case ShaderType.Tint:
                i.Effect = new TintEffect();
                break;
        }
 
        // Assign element size        i.Arrange(
            new System.Windows.Rect(
                new System.Windows.Size(256, 256)
            )
        );
        i.UpdateLayout();
 
        // Render image element to a new bitmap
        RenderTargetBitmap r = new RenderTargetBitmap(256, 256, 96, 96,
                                                      PixelFormats.Default);
        r.Render(i);
 
        // Create a new memory stream
        MemoryStream memoryStream = new MemoryStream();
 
        // Export bitmap to the stream
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(r));
        encoder.Save(memoryStream);
 
        // Export the stream to a byte array
        byte[] bytes = memoryStream.ToArray();
        memoryStream.Close();
 
        // Shutdown rendering thread (if alive)
        if (r.Dispatcher.Thread.IsAlive) {
            r.Dispatcher.InvokeShutdown();
        }
 
        // Store processed image (as a byte array)
        this.Target = bytes;
    }
}
In summary, this post describes the technique of using WPF in a web service to perform advanced rendering. In theory, this technique is not restricted to image processing but could also be used to generate graphics of charts, diagrams and even three dimensional scenes. During limited testing it is obvious that this technique introduces network latency, particularly when the service has been dormant. And what is still unknown is whether the rendering is performed in hardware (i.e. GPU) or software (i.e. CPU). Please comment below if you know the answer to this or know of a definitive test for GPU vs. CPU.

Thursday, November 10, 2011

Applying Custom Effects to Silverlight Maps

Larry King

The Larry King effect is many custom map effects available in a newly published sample by the Applications Prototype Lab.

Click here for the live app.
Click here to download the source code.

Background

With the release of Silverlight 3, Microsoft introduced the capability to apply custom effects using pixel shaders.

The ArcGIS API for Silverlight allows developers to assign effects directly to a layer or map. This sample demonstrates the application of custom effects to a map.

Silverlight versions 3 and 4 currently applies effects in software, that is, using the CPU rather than the GPU. On slower computers users may experience a slight delay when navigating or changing effects.

One advantage of this technique is that web developers can extend the utility of standard base maps. For example, a developer could create an effect that would allow the Esri streetmap base map to be more legible at night. Applying effects does not create more content nor impact network bandwidth.

For a technical discussion on pixels shaders for Silverlight we recommend this article.

Below are a few screenshots from the live application linked above.

Inverted
Inverted

Gray
Gray

Saturation/Desaturation
Saturation/Desaturation

Censored
Censored

Embossing
Embossing

Movie
Movie

Thursday, August 25, 2011

How to add mouse drag behavior in Silverlight

Charles Babbage

Today, end users expect (or demand) intuitive and interactive web applications. One component of this is the ability to manipulate object with a mouse. This blog post provides a three step walk through that describes how to create a draggable picture of Charles Babbage, the inventor of the first computer.

This walkthrough requires:

  1. Microsoft Visual Studio 2010 (link)
  2. Microsoft Visual Studio 2010 Service Pack 1 (link) – Optional
  3. Microsoft Silverlight 4 Tools for Visual Studio 2010 (link)
  4. Microsoft Expression Blend SDK for Silverlight 4 (link)

Step 1 – In VS2010, create a new Silverlight application called SilverlightApplication1

How to add mouse drag behavior in Silverlight

Click ok to create a host ASP.NET web application

How to add mouse drag behavior in Silverlight

Step 2 – Add blend interactivity behavior

Add the following assembly references:

  1. Microsoft.Expression.Interactions
    c:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries\Microsoft.Expression.Interactions.dll
  2. System.Windows.Interactivity
    c:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries\System.Windows.Interactivity.dll

How to add mouse drag behavior in Silverlight

Step 3 – Add drag behavior to an image

Copy and paste the following code into MainPage.xaml. This will display an image of Charles Babbage in the center of the screen. The XAML to enable mouse dragging is highlighted in yellow below.

<UserControl
   x:Class="SilverlightApplication1.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 
  
 xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
 
  
mc:Ignorable="d"
   d:DesignHeight="600"
   d:DesignWidth="800"
   >
    <Grid x:Name="LayoutRoot" Background="White">
       
<Image
           Width="100"
  Source="http://upload.wikimedia.org/wikipedia/commons/6/6b/Charles_Babbage_-_1860.jpg"
           >
            <i:Interaction.Behaviors>
                <ei:MouseDragElementBehavior/>
            </i:Interaction.Behaviors>
        </Image
>

    </Grid
>
</
UserControl
>

You are done! Press F5 to start the project is debug mode. Using your mouse, the picture of Charles Babbage can dragged around the screen.

How to add mouse drag behavior in Silverlight

This works fine but with a little extra work we can make the application a little more intuitive. By adding a frame, drop shadow and associating a hand cursor, the picture now has a visual queue inviting users to interact.

<UserControl
   x:Class="SilverlightApplication1.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 
  
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
 
  
mc:Ignorable="d"
   d:DesignHeight="600"
   d:DesignWidth="800"
   >
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid>
            <Grid Background="White" Cursor="Hand" HorizontalAlignment="Center"
VerticalAlignment="Center">
                <i:Interaction.Behaviors>
                    <ei:MouseDragElementBehavior/>
                </i:Interaction.Behaviors>
                <Grid Background="Black">
                    <Grid.Effect>
                        <BlurEffect Radius="15"/>
                    </Grid.Effect>
                </Grid>
                <Grid Background="White"/>
                <Image
                   Margin="10"
                   Width="100"
  Source="http://upload.wikimedia.org/wikipedia/commons/6/6b/Charles_Babbage_-_1860.jpg"
                   />
            </Grid>
        </Grid>
    </Grid
>
</
UserControl
>

How to add mouse drag behavior in Silverlight

Wednesday, August 24, 2011

How to create a simple proxy in ASP.NET

A common obstruction when developing Silverlight web applications is cross domain access. Silverlight has built-in security that prevents communication to servers that do not explicitly granted access using with either a client access policy or cross domain file. Even though a server has services intended for public use, if the server does not have a cross domain file then Silverlight apps will be denied access.

This post presents a convenient and legitimate way to overcome this restriction with a simple proxy service in three easy steps!

Step 1 – In Visual Studio 2010, create a new ASP.NET Web Application project called WebApplication1

How to create a simple proxy in ASP.NET

Step 2 – Add a new generic handler called proxy.ashx

How to create a simple proxy in ASP.NET

Step 3 – Copy and paste this code into proxy.ashx.cs.

using System;
using System.IO;
using System.Net;
using
System.Web;

namespace
WebApplication1 {
   
public class proxy : IHttpHandler
{
       
public void ProcessRequest(HttpContext
context) {
           
HttpResponse
response = context.Response;

           
// Check for query string
            string uri = Uri
.UnescapeDataString(context.Request.QueryString.ToString());
           
if (string
.IsNullOrWhiteSpace(uri)) {
                response.StatusCode = 403;
                response.End();
               
return
;
            }

           
// Filter requests
            if (!uri.ToLowerInvariant().Contains("
wikimedia.org")) {
                response.StatusCode = 403;
                response.End();
               
return
;
            }

           
// Create web request
            WebRequest webRequest = WebRequest.Create(new Uri
(uri));
            webRequest.Method = context.Request.HttpMethod;

           
// Send the request to the server
            WebResponse serverResponse = null
;
           
try
{
                serverResponse = webRequest.GetResponse();
            }
           
catch (WebException
webExc) {
                response.StatusCode = 500;
                response.StatusDescription = webExc.Status.ToString();
                response.Write(webExc.Response);
                response.End();
               
return
;
            }

           
// Exit if invalid response
            if (serverResponse == null
) {
                response.End();
               
return
;
            }

           
// Configure reponse
            response.ContentType = serverResponse.ContentType;
           
Stream
stream = serverResponse.GetResponseStream();

           
byte[] buffer = new byte
[32768];
           
int
read = 0;

           
int
chunk;
           
while
((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) {
                read += chunk;
               
if (read != buffer.Length) { continue
; }
               
int
nextByte = stream.ReadByte();
               
if (nextByte == -1) { break
; }

               
// Resize the buffer
                byte[] newBuffer = new byte
[buffer.Length * 2];
               
Array
.Copy(buffer, newBuffer, buffer.Length);
                newBuffer[read] = (
byte
)nextByte;
                buffer = newBuffer;
                read++;
            }

           
// Buffer is now too big. Shrink it.
            byte[] ret = new byte
[read];
           
Array
.Copy(buffer, ret, read);

            response.OutputStream.Write(ret, 0, ret.Length);
            serverResponse.Close();
            stream.Close();
            response.End();
        }
       
public bool
IsReusable {
           
get { return false; }
        }
    }
}

You are done! To test, press F5 to run the web application in debug mode. Your default web browser will display the Default.aspx page from your project.

How to create a simple proxy in ASP.NET

Without closing the web browser, append the name of the proxy service and the web resource (highlighted below) that you need access to. For example:
http://localhost:51220/proxy.ashx?http://upload.wikimedia.org/wikipedia/en/f/f0/New-esri-logo.jpg

This is the result.

How to create a simple proxy in ASP.NET

In summary, this post described how to crate a simple proxy web service. The proxy can be used by Silverlight web application to access resources that are restricted due to a missing cross domain file. To prevent malicious use of the proxy it is advisable to add some sort of access restriction, for example, in this exercise the proxy was configured to only accept requests for content from the wikimedia.org domain.