Category Archives: Silverlight

Using Sketchflow to create iPhone UX Prototypes

Standard

image 

I’ve been using Expression Sketchflow for many things over the past few weeks for both prototyping Winforms, mobile, web and sometimes even Silverlight applications.

Once you give up on the idea of reusing your prototype it’s amazing what it can be used for.

I’ve found the creation of an iPhone usercontrol useful in prototyping.  Simply add iPhone.xaml to your project and drop this onto your screens.

To create iPhone.xaml, create a blank usercontrol, then use the following xaml (remember to change MyProject to the name of your project):

 

<UserControl
    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"
    mc:Ignorable="d"
    xmlns:ps="clr-namespace:Microsoft.Expression.Prototyping.SketchControls;assembly=Microsoft.Expression.Prototyping.SketchControls"
    x:Class="MyProject.iPhone"
    d:DesignWidth="341" d:DesignHeight="685" Width="341" Height="685">

    <Grid x:Name="LayoutRoot">
        <Rectangle Fill="#FF0A0000" Stroke="Black" RadiusX="21" RadiusY="21"/>
        <ps:SketchRectangleSL Margin="11,103,10,102" Style="{StaticResource Rectangle-Sketch}" Height="480" Width="320"/>
        <Ellipse Fill="White" Stroke="Black" Height="59" Margin="139,0,139,20" VerticalAlignment="Bottom"/>
        <Rectangle Fill="White" Stroke="Black" Height="26" Margin="157,0,157,36" VerticalAlignment="Bottom" RadiusX="2.75" RadiusY="2.75"/>
        <Rectangle Stroke="Black" RadiusX="3.5" RadiusY="3.5" Height="7" Margin="139,51,139,0" VerticalAlignment="Top" Fill="White"/>
        <ps:SketchRectangleSL Height="24" Margin="11,103,10,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Background="#FF020000"/>
        <ps:SketchRectangleSL Height="13" HorizontalAlignment="Right" Margin="0,109,23,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Width="27" Background="#FFFCFCFC"/>
        <ps:SketchRectangleSL Height="7" HorizontalAlignment="Right" Margin="0,112,20,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Width="5"/>
        <TextBlock Margin="41,107,0,0" Style="{StaticResource BasicTextBlock-Sketch}" VerticalAlignment="Top" Text="Carrier" TextWrapping="Wrap" Foreground="#FFFCFCFC" HorizontalAlignment="Left" Width="41"/>
        <ps:SketchRectangleSL Height="10" HorizontalAlignment="Left" Margin="33,111,0,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Width="4" BorderBrush="#FFFFFDFD"/>
        <ps:SketchRectangleSL Height="8" HorizontalAlignment="Left" Margin="29,113,0,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Width="4" BorderBrush="#FFFFFDFD"/>
        <ps:SketchRectangleSL Height="6" HorizontalAlignment="Left" Margin="25,115,0,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Width="4" BorderBrush="#FFFFFDFD"/>
        <ps:SketchRectangleSL Height="5" HorizontalAlignment="Left" Margin="21,116,0,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Width="4" BorderBrush="#FFFFFDFD"/>
        <ps:SketchRectangleSL Height="3" HorizontalAlignment="Left" Margin="17,118,0,0" Style="{StaticResource Rectangle-Sketch}" VerticalAlignment="Top" Width="4" BorderBrush="#FFFFFDFD"/>
        <TextBlock Margin="141,107,121,0" Style="{StaticResource BasicTextBlock-Sketch}" VerticalAlignment="Top" Foreground="#FFFCFCFC" Text="12:00 PM" TextWrapping="Wrap"/>
    </Grid>
</UserControl>

Advertisements

Sketchflow – “Duplicate” Bug

Standard

 

image

 

The Problem

At the moment I’m trialling Sketchflow for Expression Blend.  There’s an annoying bug that happens when you use the “Duplicate” action on a node:

image

If you use this action, sooner or later you’ll end up with this error:

‘InitializeComponent’ is not a member of ‘xxxxxxxxxx.xxxxxxxxxxxxxx’

This can be very frustrating if you are trying to advocate Sketchflow as a prototyping tool for non wpf savvy analysts.

The Workaround

The simplest workaround is to delete the code-behind file.  To do this, go to the project pane and choose “Delete”.

image

 

At first I tried hard to ensure that the xaml filenames and classnames were correct.  This just causes a cascading comedy of errors.

Upgrading Sketchflow prototype projects to real code is a pipe-dream at the moment.

If you know of a better way of handling this situation (and fixing the errors) more quickly, feel free to comment.  I just want get on with the prototyping.

RIAServices – Proudly using SessionState within your DomainServices

Standard

 image

 

As mentioned in my previous article How to build huge dynamically loading cross platform Silverlight Business Applications, I’m experimenting with the idea of a hybrid web application that has some parts implement as webforms, others as Silverlight.

A problem I encountered was that RIAService calls did not necessarily access to the same information as my webforms did.  An example is “SessionState”.  In the case of my company’s framework, the authentication system must be invoked prior to anything else within my domain services.  In addition the authentication system needs access to SessionState.

 

To do this I thought I could inherit from DataServiceFactory and add what I needed.  Unfortunately the class is marked as not inheritable.  The way around this is to encapsulate the class.

In the code sample below you can see an implementation of MyDataServiceFactory that encapsulates DataServiceFactory and returns an encapsulated HttpHandler that flags to ASP.Net that sessionstate is needed.

 

Imports System.Web
Imports System.Web.SessionState

Public Class MyDataServiceFactory
    Implements IHttpHandlerFactory
    Private moHandlerFactory As IHttpHandlerFactory

    Public Sub New()
        moHandlerFactory = New System.Web.Ria.DataServiceFactory
    End Sub

    Public Function GetHandler(ByVal context As System.Web.HttpContext, ByVal requestType As String, ByVal url As String, ByVal pathTranslated As String) As System.Web.IHttpHandler Implements System.Web.IHttpHandlerFactory.GetHandler

        Return New MyDataServicesHandler(moHandlerFactory.GetHandler(context, requestType, url, pathTranslated))

    End Function

    Public Sub ReleaseHandler(ByVal handler As System.Web.IHttpHandler) Implements System.Web.IHttpHandlerFactory.ReleaseHandler
        moHandlerFactory.ReleaseHandler(DirectCast(handler, MyDataServicesHandler).InnerHandler)
    End Sub
End Class
Public Class MyDataServicesHandler
    Implements IHttpHandler
    Implements IRequiresSessionState ' Let ASP.Net know that you need to use the session object

    Public InnerHandler As IHttpHandler
    Public Sub New(ByVal handlerToWrap As IHttpHandler)
        InnerHandler = handlerToWrap
    End Sub
    Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
        Get
            Return InnerHandler.IsReusable
        End Get
    End Property

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
        ' You can access context.Session here if you want to...
        InnerHandler.ProcessRequest(context)
    End Sub
End Class

 

Of course to use this, you need to modify the web.config and change the two references to DataServicesFactory to point to your new class instead, which should be hosted in it’s own class library.

 

Share this post :

How to build huge dynamically loading cross platform Silverlight Business Applications

Standard

Embedding RIAs in your web pages can be a rewarding experience

The Silverlight 3 navigation framework provides a really nice way of integrating with the browser history.  By default it tends to support a single silverlight control model rather than leveraging the full power of asp.net.  In this article I propose an way of structuring applications that utilise asp.net and Silverlight.   The approach even allows the use of HTML, WPF-XBAP and Flash as an alternative to Silverlight or in any combination. 

 

Out of the box with Silverlight 3

It seems to me that the Silverlight 3 navigation system works best as a single control embedded in a page (contained in a single xap file).  Navigation (and loading of the many parts of an application) happen within that single control.  This is similar to the traditional “smart client” architecture.

The Silverlight 3 navigation samples provided allow the straight forward creation of this kind of smart client, with a nice Silverlight themeable container.  For simple applications, I recommend people take a look.

To take this even further the Prism framework (which I have found integrates well with Silverlight 3) provides and excellent container framework for those who would like to take this model further.

image

 

Dynamically loaded Assemblies in Silverlight 3

In the article “Silverlight 3 Navigation: Navigating to Pages in dynamically-loaded assemblies” , David Poll shows a way of dynamically loading pages into the primary navigation container by using “shim” pages within it. 

David describes his strategy as follows:

  • Load an assembly containing a Page dynamically
  • Include in this assembly a “shim” Page with no code behind.  In its XAML, reference the real page with code behind, and forward any navigation-related information (events, title, query strings, etc.) to that Page
  • When that page is navigated to, replace the Frame’s content with the real page.
  • From the application, navigate to the “shim” page in the dynamically-loaded assembly

For a developer, this means creating empty shim pages in the main project for every page they require in other assemblies.

As admitted by the author, this solution is “it’s a bit obtuse, and still harder to do than it ought to be”.  I believe David has pushed the Silverlight smart client model as far as it can go. 

If you read through the comments section of David’s article “mitkodi” discusses a way of using UriMapping to simplify the solution.  This is similar to the approach I’m proposing in this article.  (I didn’t see this before)

Perhaps Microsoft will create some markup of some kind to allow cross navigation between assemblies.  I hope they do. 

 

Another Way

It seems to me that there are two ways RIA applications can be built, either as a smart client (as described above) or as true web application web pages, each with embedded controls. 

In the second approach, each Silverlight page could be embedded on it’s own web page.  Navigation could happen at the page level, leveraging the natural navigability of web solutions.    The web page could act as a simple “shim” for hosting the RIA content, or it could provide more such as cross-platform and “deep linking”.

 

image

 

In short you would have a solution that is:

  • Navigable : Navigation could work without the Navigation framework
  • Cross Platform : An alternate web rendering of it’s content could be provided (which also allows for simpler “deep linking” for SEO)
  • Modular : If each Silverlight page was on it’s own webpage, each page could have it’s own xap file, with no special workarounds or compromises
  • Versatile: You can use any Silverlight 3 features you like (including RIA Services for example), using as many or as few assemblies you wish
  • Not Silverlight Specific : The solution could work for any embedded RIA technology, including Flash (Flex) or WPF-XBAP.

 

I’ve always thought that combining existing web technologies (DHTML, AJAX, Server side rendering) with RIA would provide something far greater than just an RIA or a web application on their own.

In the the RIA Hybrid example shown in this article, Routing support (introduced in .NET 3.5 SP1) and master pages are used to make the solution simpler.

 

The RIA Hybrid

 

Write a letter Maria, address it to Silverlight...

 

In this example, Maria the customer begins at a “home” page, then navigates from this page to a contact enquiry, then to a contact detail.

image

The Solution

To the Maria it’s just a normal website with normal navigation.  They can use browser history and bookmarking work regardless of the browser they are using.  Here’s what the solution looks like:

 

The solution

The content Maria sees is actually implemented entirely in Silverlight.  In web page“Home.aspx” is a simple web page that provides an alternate web rendering of it’s content if Silverlight is not available.

 

image

 

Here’s the layout xaml of Home.Mainpage,xaml:

  <Grid x:Name="LayoutRoot">
        <StackPanel>
             <TextBlock FontSize="100" Text="Welcome to Home" />
            <HyperlinkButton  x:Name="lnkViewContactEnquiry"  Content="View Contact Enquiry" Tag="ContactEnquiry.aspx" />
        </StackPanel>
        </Grid>
</UserControl>

Here’s the code of Home.Mainpage.vb:

Private Sub lnkViewContactEnquiry_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles lnkViewContactEnquiry.Click
    System.Windows.Browser.HtmlPage.Window.Navigate(New Uri(sender.Tag, UriKind.Relative))
End Sub

 

As you can see, the code is quite simple and provides an almost html-like approach to navigation.

The code for Home.aspx is also straight forward:

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Container.Master" CodeBehind="Home.aspx.vb" Inherits="WebHybrid.Web.Home" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

     <h1>Welcome to Home</h1>  
    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="ContactEnquiry.aspx" >View Contact Enquiry</asp:HyperLink>
</asp:Content>

As you can see, the asp.net page only contains simple html.   This means that the developer only has to concentrate on providing the cross-platform rendering of the content.   So where’s the Silverlight?

I’ve stored the Silverlight magic in a master page (“Container.Master”) which can be reused with other Shim pages.  Basically it checks to see if a matching xbap file exists for the page, and if it does it will render this in a Silverlight host instead of the “ContentPlaceHolder1” web content.

You may notice, that in either case, Maria navigates successfully to ContactEnquiry.aspx.  If you look at the solution screenshot above you’ll notice there is not ContactEnquiry.aspx.

 

The Phantom ContactEnquiry.aspx – Routing

If the developer doesn’t need to provide web content, the cool new .NET3.5 SP1 “Routing” feature comes to the rescue.   This feature allows redirection to a generic hosting page if the called aspx doesn’t exist.  In this case, GenericSilverlightHost.aspx. 

 

The magic of redirection is accomplished by creating a “Route Handler” class.  I haven’t seen any vb.net examples of these on the web, so here’s the code:

Imports System.Web.Routing
Imports System.Web
Imports System.Web.UI
Imports System.Web.Compilation
Imports System.IO
Public Class WebFormRouteHander
    Implements IRouteHandler
    Private msWebFolder As String
    Public Sub New(ByVal path As String)
        msWebFolder = path
    End Sub
    Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler Implements System.Web.Routing.IRouteHandler.GetHttpHandler

        Dim lsPage As String = requestContext.RouteData.GetRequiredString("Page") & ".aspx"

        Dim lsFullPathOfPage As String = Path.Combine(msWebFolder, lsPage)
        If File.Exists(lsFullPathOfPage) Then
            Return BuildManager.CreateInstanceFromVirtualPath("~/" & lsPage, GetType(Page))
        Else
            Return BuildManager.CreateInstanceFromVirtualPath("~/GenericSilverlightHost.aspx", GetType(Page))
        End If

    End Function
End Class

It’s wired up with this code in Global.asax:

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    ‘ Fires when the application is started
    RouteTable.Routes.Add(New Route("{Page}.aspx", New WebFormRouteHander(Server.MapPath("/"))))
End Sub

Please remember that to get Routing working on your site you will need to modify your web.config file.  The easiest way is to search for the word “Routing” in the sample web.config.

So that’s it!

Download the code now and try out the solution, I think you’ll like it.

 

Conclusion

So developers can create an unlimited number of Silverlight pages, in any number of dynamically loaded xbap assemblies and provide navigation between these.

This rather obvious solution could be taken much further. It could work with other web frameworks such as ASP.Net-MVC or a completely non-Microsoft one.  It could work with any RIA technology or combinations of those.

I’m really interested in what people have to say about this approach.

 

Download the Code

Links

Silverlight 3 Navigation: Navigating to Pages in dynamically-loaded assemblies – David Poll

Goodbye to Url Rewriting

 

Share this post :

Silverlight 3 style NavigationContext in WPF

Standard

 image

At the moment I’m experimenting with various user interface technologies.  Because the prototypes are working in parallel, I want to reuse code where possible.  With this in mind, I’ve created a couple of useful wrapper functions for navigation in both Silveright 3 and WPF that I thought I’d share.

 

In case you don’t know the Silverlight 3 Beta now has a navigation framework that works in a similar way to WPF’s Frame navigation feature.   To learn more about it, check our Jeff Poise’s great article Silverlight 3’s New Navigation Framework.

 

I brief, to navigate to a new page and pass a parameters you use a syntax like this in the code behind:

 

Me.NavigationService.Navigate(New Uri(String.Format(“/SomePage.xaml?someparameter={0}”,somevalue), UriKind.Relative))

 

In the loaded event of the page you’re navigating to, you use code like this:

 

Private Sub MyPage_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
     txtSomeTextbox.Text =  Me.NavigationContext.QueryString("someparameter")
End Sub

 

Nicer Navigating

I found the Navigate method above a little awkward, so in Silverlight I created a little helper function called “NavigateTo”, on page that makes the code a bit nicer.

 

Me.NavigateTo(“/SomePage.xaml”,”someparameter”,somevalue)

 

Here’s the implementation:

 

Imports System.ComponentModel
Public Module PageHelper
    <System.Runtime.CompilerServices.Extension()> _
   Public Sub NavigateTo(ByVal page As System.Windows.Controls.Page, ByVal navigationUrl As String, ByVal ParamArray arguments() As String)
        Dim lsUrl As String = navigationUrl & "?"
        Dim lbIsParamName As Boolean = True
        For Each lsArg As String In arguments
            lsUrl &= lsArg
            If lbIsParamName Then lsUrl &= "="
            lbIsParamName = Not lbIsParamName
        Next

        page.NavigationService.Navigate(New Uri(lsUrl, UriKind.Relative))
    End Sub

End Module

 

Nicer NavigationContext

 

I found Silverlight3’s NavigationContext quite nice to use.  Unfortunately this is not available in WPF.  I set about creating a helper function that would emulate this functionality in WPF.

 

WPF Navigation Helper

 

Here’s a WPF version of PageHelper that allows a compatible syntax with Silverlight3.  

 

Imports System.ComponentModel
Public Module PageHelper

    Private WithEvents moCurrentNav As NavigationService
    <System.Runtime.CompilerServices.Extension()> _
   Public Sub NavigateTo(ByVal page As System.Windows.Controls.Page, ByVal navigationUrl As String, ByVal ParamArray arguments() As String)

        '  Update Navigation Args
        Dim loNavigationUri As New NavigationContext

  If arguments.Length > 0 Then
            For i As Integer = 0 To arguments.Length - 1 Step 2
                 loNavigationUri.QueryString.Add(arguments(i), arguments(i + 1))
            Next

            End If

           
        loNavigationUri.Uri = New Uri(navigationUrl, UriKind.Relative)

        ' Strip the Xaml extension 
        Dim lsClassName As String = navigationUrl.Substring(0, navigationUrl.Length - 5) 
        ' Make my class name 
         Dim lsName As String = page.GetType.Namespace & "." & lsClassName 
        ' Instantiate the class 
        Dim loPage As Page = page.GetType.Assembly.CreateInstance(lsName) 
        ' Do the Navigation 
         page.NavigationService.Navigate(loPage, loNavigationUri)
    

        ' Store the current NavigationService so we can complete
        moCurrentNav = page.NavigationService

    End Sub
    <System.Runtime.CompilerServices.Extension()> _
Public Function NavigationContext(ByVal page As System.Windows.Controls.Page) As NavigationContext
        Return moLastNavContext
    End Function
    Private Sub moCurrentNav_Navigated(ByVal sender As Object, ByVal e As System.Windows.Navigation.NavigationEventArgs) Handles moCurrentNav.Navigated
        moLastNavContext = e.ExtraData
        moCurrentNav = Nothing
    End Sub
    Private moLastNavContext As New NavigationContext

End Module
Public Class NavigationContext
    Public QueryString As New Dictionary(Of String, String)
    Public Uri As Uri
End Class

 

I also have provided primitive support for cross-assembly navigation.

 

I hope someone found this useful, let me know.

 

 

Share this post :

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Silverlight “Name ‘InitializeComponent’ is not declared”

Standard

She'd be far less frutrated if she plugged it into the network first.

It is quite common in Webforms, Winforms and other environements to copy user interface views from one project to another.

When you copy xaml files from one Silverlight project to another you may experience the error:

“Name ‘InitializeComponent’ is not declared”

 

This happens because the “x:Class” directive in the top of the xaml file includes the project namespace.

So, open up your xaml file, and change this:

 

x:Class=”PreviousProject.YourClass”

 

To the new project namespace:

x:Class=”NewProject.YourClass”

 

Oh and BTW…..ITS CASE SENSITIVE! 

 

I know this isn’t much of a post, but hopefully it will provide a useful search engine hit for the desperate.

Estranged Siblings – Silverlight Mobile and the Compact Framework CLR

Standard

An illustration that contemplates the cojoined nature of Silverlight and the Compact Framework

 

At PDC 2008 in the session Microsoft Silverlight 2 for Mobile- Developing for Mobile Devices, Amit Chopra revealed some interesting details about Silverlight Mobile that I haven’t seen written elsewhere.

The presentation mainly consists of “here’s Silverlight running on Windows Mobile”.   The interesting bits are at the end.  I dear reader, present these to you here.

 

Compact Framework, small but mighty

The compact framework, is small yet mighty.  (Some may say mighty ugly...by default)

The Compact Framework provides a great deal of rich device integration and sheer programmability. It is a pleasure to create software for.  I even think that Compact Framework based applications have been a reason for customers, particularly in the Mobile Fieldworker areas to adopt Windows Mobile devices.

If you’re a Compact Framework developer like me, you may have been frustrated by the default “yesterday” appearance of the System.Windows.Forms forms engine.  It takes a great deal of work to make forms look good. 

Silverlight, a Framework Apart?

Two frameworks, Silverlight and Compact Framework, so alike, yet so different.

I for one was very excited last year at the thought of a Silverlight (ie WPF) graphics engine being available for Mobile Device development.  I was then saddened to learn that the Silverlight runtime would not be extending the Compact Framework, but would exist in addition to Compact Framework.

This is disappointing news. (I am now showing my disappointed face….beware!) It appears that Microsoft (at the moment) seem determined to give Silverlight minimal access to the device.  This is aligned with the idea that Silverlight is only a competitor to traditional Flash app that runs from a Web page. 

Although this may be acceptable for certain kinds of desktop oriented Silverlight applications, I doubt this is a believable use case for mobile developers.  The power of mobility is not only the ability to access data anywhere, but the ability to talk to the features of the device.

In the presentation mentioned at the outset, there was declaration of the intention to support Webcams, accelerometer and other device features in the future, depending on the support for this on other platforms (eg Windows and Mac). 

So, we are restricted to the lowest common denominator.  You may believe this is for technical reasons.  It isn’t. Because….

Silverlight Uses the Compact Framework!

Diagram of Silverlight Architecture on Windows Mobile

Amit said that the Silverlight runtime for Windows Mobile may be smaller because it may omit certain codecs and it also shares the Compact Framework Clr.    He went on to say that the Compact Framework would be a prerequisite to installing the Silverlight runtime.

A new and nobler purpose for Silverlight Mobile

I give you....Silver-Knight

It’s Microsoft’s belief that targeting Windows Mobile 6.? (Sorry about that WM2003 and 5) and Nokia phones will mean Web users will eschew DHTML and Flash websites for Silverlight ones.  

With the proliferation of device operating systems (particularly that pesky iPhone) I don’t think this is a likely scenario.  Do you?  Well do you?

I’ve I got an idea!  As it’s unlikely Microsoft will backtrack on their “one platform everywhere” philosophy for Silverlight, why not, in addition enable Silverlight as a cutdown WPF for the Compact Framework on Windows Mobile? Microsoft, I know you can!  Doing this would earn the gratitude of all Compact Developers and provide a side benefit to their current Silverlight efforts on Mobile.

Call to Action

If you agree, please add a comment or bookmark this article using the links below, blog about this yourself or email the people at Microsoft.   Amit said they wanted feedback, lets give it!

(BTW Any physical resemblance between Amit and myself is entirely coincidental, so don’t say it)

 

Links

Microsoft Silverlight 2 for Mobile- Developing for Mobile Devices

Amit Chopra’s Blog (Email) – WIndows Mobile Program Mananger

Giorgio Sardo’s Blog (Email: gisardo @ microsoft  com) – Evangelist for Windows Mobile

 

Share this post :

Automatically stretching a Silverlight 2 control on a webpage

Standard

image

A couple of fun hours were spent trying to get my Silverlight content to resize when the user resized the browser. 

I mean, what’s the point of having your Silverlight content replace HTML if it wont flow and resize when the user resizes the browser? I want my Silverlight content to take up the whole browser frame.

The Html Code

You’d think this would be the default behaviour for an asp.net tag definition like this:

<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/TechnologyOneCrm.xap" Version="2.0" Width="100%" Height="100%" />

 

Sadly this is not enough.  Your silverlight sits there in a dumb un-resizeable box.

The Xaml

When you create a Silverlight 2 control in Visual Studio 2008 or blend, the UserControl typically has Height and Width properties set, something like this:

<UserControl x:Class="Daphne.WorkplaceHome"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Width="900" Height="400" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
    <Grid x:Name="LayoutRoot" Background="White" >
    </Grid>
</UserControl>

 

The Elusive Auto

Hence the reason why your content is not resizable.

One solution is to remove the Width and Height property.   Another is to set them to “Auto”, like so:

<UserControl x:Class="Daphne.WorkplaceHome"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Width="Auto" Height="Auto" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
    <Grid x:Name="LayoutRoot" Background="White" >
    </Grid>
</UserControl>

 

If you run the project, it will start resizing.  Unfortunately this causes the designer in Blend and VS2008 look like rubbish.  (or more rubbish than usual anyway).

The trick is to set the Width and Height properties to “Auto” after the the screen has been rendered.

 

In WPF (apparently) you can use code like this:

Partial Public Class Page
    Inherits UserControl
    Public Sub New()
        InitializeComponent()

        Me.Height = new System.Windows.LengthConverter().ConvertFromString("Auto")
        Me.Width =  new System.Windows.LengthConverter().ConvertFromString("Auto")
    End Sub

...

 

Sadly, in another twist of fate, “LengthConverter” does not exist in Silverlight.

The Silverlight Solution – Who’s your Nan?

 

image

 

Fortunately, browsing the type library showed me that setting the property value of Height or Width to “System.Double.Nan” has the same effect as “Auto”.

So, in the intialise of your Silverlight control, put this:

 

Partial Public Class Page
    Inherits UserControl
    Public Sub New()
        InitializeComponent()

        Me.Height = System.Double.NaN
        Me.Width = System.Double.NaN
    End Sub

 

I am not sure if Microsoft intend to support LengthConverter (or TypeDescriptor.GetConverter!) in a future Silverlight version, but I’m guessing not.

Links

 

Share this post :

Problem calling a Web Service from Silverlight 2

Standard

image

Apparently the “System.ServiceModel.ProtocolException” error is common in the fledgling world of Silverlight 2 and Web Services.

 

In my case I tried to reference a Web Service that my company created and was disappointed with this entertaining message:

 

System.ServiceModel.ProtocolException’ occurred in System.ServiceModel.dll but was not handled in user code Additional information: [UnexpectedHttpResponseCode]Arguments:Not Found
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30226.2&File=System.ServiceModel.dll&Key=UnexpectedHttpResponseCode

 

What this meant in my case is that I needed a “crossdomain.xml” file placed in the root folder of the server I was accessing.

 

For a development server, this could mean something like this:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" />
</cross-domain-policy>

 

This gives all applications (Silverlight, Flash) no matter where they’re from to access any web applicaitons on your web host.

 

As an ISV I find this a bit annoying, as it means updating a file that is outside of the Web Application (in the Web Root).

 

It would be nice to be able to configure this information within the virtual directory of the application itself.

 

 

Links

Combining Silverlight 2 content from multiple web applications in VS2008

Standard

 image

In a project I’m doing I need to create a web application that can consume Silverlight 2 RIA content from other web applications.

As it turns out, this is pretty easy to do.  All you need to do is reference the xap in the other web application from your page and it works exactly the same as if you were using an xap from within your own web application.

A Problem with Debugging

One problem is that Visual Studio tries to run the two web applications on different ports, which makes it impossible to reference the other web app directly.  You can’t use a relative url:

<form id="form1" runat="server" style="height:100%;">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div  style="height:100%;">
        <asp:Silverlight ID="Xaml1" runat="server" Source="../Crm_Web/ClientBin/TechnologyOneCrm.xap" Version="2.0" Width="100%" Height="100%" />
    </div>
</form>

Therefore you need to set the web application you wish to point to on a static port, like this:

image

You can then access the web application directly:

<form id="form1" runat="server" style="height:100%;">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div  style="height:100%;">
        <asp:Silverlight ID="Xaml1" runat="server" Source="http://localhost:2000/Crm_Web/ClientBin/TechnologyOneCrm.xap" Version="2.0" Width="100%" Height="100%" />
    </div>
</form>

There’s probably many better solutions to this problem, but I thought I’d post my workaround.