An Original Idea

because all great software begins with an original idea

Enabling callto (Skype) in your application

Posted by anoriginalidea on September 30, 2009

image image

You may have noticed that Skype seems to embed itself into Internet Explorer, Firefox and Chrome.  It recognises contacts and phone numbers in the page and provides the ability to call them.

I believe people will expect this kind of functionality in conventional windows applications also.  To assist with this I created a little class that will not only allow calls, but allows a check for the existence of a skype and give the ability to extract the calling applications icon.

Sample Project

The sample winforms project includes the CallTo class and a simple Winforms test form:

image

The form has a textbox and button.   One load, the call button is enabled and give an image.  The button makes the call.

 

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim loCallTo As New CallTo
        cmdCall.Image = loCallTo.Image
        cmdCall.Enabled = loCallTo.Enabled
    End Sub
    Private Sub cmdCall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCall.Click
        Dim loCallTo As New CallTo
        loCallTo.DoCall(txtPhoneNumber.Text)
    End Sub

End Class

 

 

Heres the source of CallTo.vb:

 

Imports Microsoft.Win32
Imports System.Runtime
Imports System.Runtime.InteropServices

''' <summary>
''' This class allows for making callto calls
''' </summary>
Public Class CallTo

    ''' <summary>
    ''' Gets the image.
    ''' </summary>
    ''' <value>The image.</value>
    Public ReadOnly Property Image() As Image
        Get
            If Not Enabled Then Return Nothing

            Dim lsValue As String
            With Registry.ClassesRoot.OpenSubKey("callto\DefaultIcon")
                lsValue = .GetValue("")
            End With

            If lsValue.Contains(",") Then
                Dim lsBits() As String = lsValue.Split(","c)
                Dim lsFilename As String = lsBits(0).Trim(New Char() {""""c})
                Dim liPosition As Integer = Val(lsBits(1))
                Return moGetIconFromExeOrDll(lsFilename, liPosition)
            Else
                Return Nothing
            End If

        End Get
    End Property
    Private Declare Auto Function ExtractIcon Lib "shell32" ( _
ByVal hInstance As IntPtr, ByVal lpszExeFileName As String, _
ByVal nIconIndex As Integer) As IntPtr
    Private Function moGetIconFromExeOrDll(ByVal filename As String, ByVal position As Integer) As Image
        Dim hInstance As IntPtr = Marshal.GetHINSTANCE( _
           System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0))
        Dim hIcon As IntPtr = ExtractIcon(hInstance, filename, position)
        Dim loBitmap As Bitmap = Bitmap.FromHicon(hIcon)
        Dim loReturn As Image = loBitmap.GetThumbnailImage(16, 16, Nothing, Nothing)

        loBitmap.Dispose()
        Return loReturn

    End Function

    ''' <summary>
    ''' Gets a value indicating whether this CallTo is enabled.
    ''' </summar
    ''' <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
    Public ReadOnly Property Enabled() As Boolean
        Get
            Try
                Dim loReg As RegistryKey = Registry.ClassesRoot.OpenSubKey("callto", False)
                loReg.Close()
            Catch
                Return False
            End Try
            Return True
        End Get
    End Property
    ''' <summary>
    ''' Does the call.
    ''' </summary>
    ''' <param name="destination">The destination.</param>
    Public Sub DoCall(ByVal destination As String)

        If Not Enabled Then Throw New ApplicationException("Callto is not enabled")
        Process.Start("callto://" & destination)

    End Sub

End Class

 

Download Sample

Posted in .net Framework, Code, Software Development | Tagged: , , , , | Leave a Comment »

Using Sketchflow to create iPhone UX Prototypes

Posted by anoriginalidea on September 21, 2009

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>

Posted in Expression Blend, Silverlight, Sketchflow, iPhone | 2 Comments »

Sketchflow – “Duplicate” Bug

Posted by anoriginalidea on August 27, 2009

 

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.

Posted in .net Framework, Expression Blend, Silverlight, Sketchflow, Windows Presentation Foundation | 2 Comments »

Serialize and Deserialize objects as Xml using generic types in VB.Net

Posted by anoriginalidea on August 10, 2009

image

In his blog post Serialize and deserialize objects as xml using generic types in C# 2.0 , Paul Whitaker creates some ubiquitous functions for doing Xml Serialization with generics.

 

To serialize:

Dim lsXml As String = GenericXmlSerializer.SerializeObject(of MyObjectType)(myObject)

 

To deserialize:

Dim myObject As MyObjectType = GenericXmlSerializer.DeserializeObject(of MyObjectType)(lsXml)

 

Here’s the code

Imports System.Collections.Generic
Imports System.Text
Imports System.Xml
Imports System.IO
Imports System.Xml.Serialization

Class GenericXmlSerializer
    ''' <summary>
    ''' To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
    ''' </summary>
    ''' <param name="characters">Unicode Byte Array to be converted to String</param>
    ''' <returns>String converted from Unicode Byte Array</returns>
    Public Shared Function UTF8ByteArrayToString(ByVal characters As Byte()) As String

        Dim encoding As New UTF8Encoding
        Dim constructedString As String = encoding.GetString(characters)
        Return constructedString

    End Function

    ''' <summary>
    ''' Converts the String to UTF8 Byte array and is used in De serialization
    ''' </summary>
    ''' <param name="pXmlString"></param>
    ''' <returns></returns>
    Public Shared Function StringToUTF8ByteArray(ByVal pXmlString As String) As Byte()

        Dim encoding As New UTF8Encoding()
        Dim byteArray As Byte() = encoding.GetBytes(pXmlString)
        Return byteArray
    End Function

    ''' <summary>
    ''' Serialize an object into an XML string
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="obj"></param>
    ''' <returns></returns>
    Public Shared Function SerializeObject(Of T)(ByVal obj As T) As String

        Try
            Dim xmlString As String = Nothing

            Dim memoryStream As New MemoryStream()
            Dim xs As New XmlSerializer(GetType(T))
            Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)
            xs.Serialize(xmlTextWriter, obj)
            memoryStream = CType(xmlTextWriter.BaseStream, MemoryStream)
            xmlString = UTF8ByteArrayToString(memoryStream.ToArray())
            memoryStream.Dispose()

            Return xmlString
        Catch

            Return String.Empty
        End Try
    End Function

    ''' <summary>
    ''' Reconstruct an object from an XML string
    ''' </summary>
    ''' <param name="xml"></param>
    ''' <returns></returns>
    Public Shared Function DeserializeObject(Of T)(ByVal xml As String) As T

        Dim xs As New XmlSerializer(GetType(T))
        Dim memoryStream As New MemoryStream(StringToUTF8ByteArray(xml))
        Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)

        Dim theObject As T = CType(xs.Deserialize(memoryStream), T)
        memoryStream.Dispose()
        Return theObject

    End Function

End Class

 

Rather than be original, I converted most of his code verbatim and have found the functions useful. 

I offer them to you warranty free, unadorned and hopefully useful.

 

 


Share this post :

Posted in .net Framework, VB.Net | Leave a Comment »

Flick Scrolling in Winforms

Posted by anoriginalidea on August 10, 2009

image

 

In the article A Simple Scroll Controller for Winforms I mentioned that I was working on a FlickScrolling framework for Winforms.

I finished a version of this code a couple of months ago and it seems to work well.  

The code never went into production because I think that Windows 7 will provide this functionality automatically for winforms applications. 

Nevertheless, some people have showed an interest in what I came up with, so I’m posting it here for your edification.  I hope someone finds it useful.

Usage

To use, simply instantiate the “ApplicationFlickScrolling” class, passing in the datatypes of the container controls you wish to scroll.

For example:

Private Shared moApplicationFlick As New ApplicationFlickScrolling(GetType(Panel))

To switch it on and off, used the “Enabled” property:

moApplicationFlick.Enabled = True

That’s it!

 

The Implementation

image

The code consists of 3 classes:

  • ApplicationFlickScrolling to act as the master controller class
  • ApplicationMouseEvents class for detecting mouse events
  • FlickDetector for detecting simple gestures
  • ScrollController for performing elastic-style easing of scrolling

Improvements

If I’d have continued developing this I would have modified ScrollController to use “proper” easing functions. 


 
Note: The usual disclaimers apply for this code, which has been given freely to help others learn and is not intended for usage in your business application or for running a nuclear facility.


Share this post :

Posted in VB.Net, Windows Forms | Tagged: , , | Leave a Comment »

RIAServices – Proudly using SessionState within your DomainServices

Posted by anoriginalidea on July 31, 2009

 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 :

Posted in RIAServices, Silverlight | Tagged: , , , | Leave a Comment »

How to build huge dynamically loading cross platform Silverlight Business Applications

Posted by anoriginalidea on July 22, 2009

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 :

Posted in Silverlight | Tagged: , , , | 10 Comments »

Silverlight 3 style NavigationContext in WPF

Posted by anoriginalidea on July 8, 2009

 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 :

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Posted in Silverlight, Windows Presentation Foundation | Tagged: , , | Leave a Comment »

Silverlight “Name ‘InitializeComponent’ is not declared”

Posted by anoriginalidea on July 1, 2009

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.

Posted in Silverlight | Tagged: , | 3 Comments »

Reflections on Permutation City

Posted by anoriginalidea on April 15, 2009

Permutation City

 

Imagine a world where your a copy of your consciousness could be downloaded into a supercomputer, where you continue to exist, running as another computer program.   A Virtual World is provided for your “Copy” to exist in.

Although Copies only run at one seventeenth of the speed (at most) of “real” humans, they don’t notice, as from their point of view, time seems normal. 

The Copy itself made up of a brain and a body.  The brain is a software simulation of the neural network of the brain, which provides a copy of the consciousness with full fidelity.  The “body” is made up of a number of less sophisticated simulations of various organs.

The way a Copy actually “thinks” is not fully understood.  Nevertheless it is possible for the Copy to alter it’s world, body, memories and emotions.

The ability to dull or intensify specific emotions is a key driver of life.  We continue to seek happiness, thrills and highs whilst trying to alleviate suffering, unpleasantness and guilt.

In our society this is done using both external and internal stimulus.  The use of alcohol and drugs (or the iPhone) in our society provide many with a quick (although temporary) fix, others follow a seemingly endless variety of ideas, philosophies, sciences and religions.

In the book “Permutation City”, by Greg Egan, the idea of “Copies” began in medicine, where medical researchers were creating increasingly sophisticated software models of the brain and body.  A breakthrough occurred when a researcher was able to activate the consciousness of a scan of himself and place it in a primitive VR environment.  It’s first words were “Please let me out! This feels like being buried alive.”  Despite this (as it turns out common) reaction, copies became an attempt at designer immortality, with very interesting repercussions.

The book is full of great ideas and was a really interesting read.

Posted in Book Review | 1 Comment »