Monthly Archives: July 2009

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 :

Advertisements

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.