Silverlight HVP Design, Refinements

MiniTutorialLogo

SLHvpLogo

Design Update 

This was posted on Dec. 29 and updated on Dec. 30. The significant changes are to the Configuration and Marker Events sections

This blog post extends the  previous post in which I discussed the IMarkerEventHandler interface and how it might be implemented.

Readers and Frames

The design calls for one or more Pages each of which may have any number of UI modules. The default case is to have a TableOfContents module, a LinksDisplay module and a Reader module.

A Reader houses Frames where a Frame is a set of controls.  The Reader knows which frame to create and manages the lifetime of Frames.

A given frame has a known set of controls. For example, Frame-Type-1 might house the  HVP-extended version of the Silverlight Media Framework player (as described in this blog post) and Frame-Type-2 might display an html page and have a set of navigation controls.   (More on readers and Frames early in January)

Configuration

We anticipate using XML configuration files (delivered via WCF RIA Services and instantiated by MEF into a collection of business objects that for now I’ll call  HVPLayout. 

Marker Events

The meaning and actions to be taken by a Frame in response to hitting a marker in the video will be managed by the IMarkerEventHandler (MEH) implementing class. as described in the previous post mentioned earlier. 

One approach is to have the Marker Event Handler class  own a collection of HVPMarkerEvent business objects, each representing one association between a marker, its time, its type (link, etc.) and whatever other information the MEH class will need to raise the appropriate event.  A second approach, and one that is gaining a lot of traction, is to bring in the EventAggregator from Prism.

Supporting Legacy Videos

The Silverlight HyperVideo Player will continue to support existing videos that do not have markers nor our config files by having a default layout in which there is a reader that takes up the entire page, and that reader contains a Frame that itself contains nothing but our extension to the SMF player.

Other Technologies

We are actively looking at when using an IoC (Inversion of Control) container such as Ninject would provide services that are not otherwise available. For now, we believe MEF will provide the Container services, configuration and interaction with Unit Test that we need.

Posted in z Silverlight Archives | Tagged , | Comments Off on Silverlight HVP Design, Refinements

Silverlight HVP Design Update

 

SLHvpLogo
This blog post is part of the documentation for the Silverlight HyperVideo Player Open Source Project

Design Change:

  1. Create an Interface: IMarkerEventHandler
  2. Optionally derive a base class MarkerEventHandler that implements the interface
  3. Instantiate MarkerEventHandler classes that are decoupled from the HyperVideo player

This change is designed to decouple the response to markers in a video from the other responsibilities of the Silverlight HyperVideo player.

IMEH 
[Click on image for full size]

Each MEH encapsulates a strategy for responding to markers.

Here are four examples of how a MEH might interact with markers.

  • Heartbeat markers – every n seconds, used as lookups into a data source to see if there is an action at that time
  • Synchronization markers – at known times, used to resynchronize, but the logic for what happens at a given time is independent of any marker event
  • Meaningful Markers  – traditional use of a marker that tells you what time it was raised and identifies what the marker indicates (tied to an event in the video)
  • Null marker – the MEH is responsible for whatever we choose but does not depend on markers in the video

There is, potentially, more than one way to have an MEH associated with a HyperVideo player:

Option 1: The HVP will have-a MarkerHandler. As the video is played, if a marker is encountered the HVP will invoke a method on the contained MarkerHandler.

Option 2: (Looser coupled). The application will instantiate a player and a MEH object and when the player encounters a marker it will raise an event to which the MEH will subscribe. If the MEH needs to have the player take an action (e.g., pause or resume) the MEH will fire an event to which the player will subscribe.

These ideas are not fully developed but are thought through enough to move forward and with luck, sufficiently flexible to be easily modified as design emerges.

 

Details about the Silverlight HyperVideo Player Project can be found at our CodePlex Site and information on joining the Development effort can be found on the Developer Page within the project documentation.

Posted in HyperVideo Player | Tagged | 1 Comment

Being a writer, and having an editor. A Short Rant.

I have been incredibly lucky; the editors I’ve worked with have been terrific. O’Reilly, for example, spends a lot of time on editing. And they interpret the term editing correctly and broadly: everything from copyediting to technical editing to just making sure that what you’ve written is clear, correct and concise.

I should add that my current development editor, one Brian MacDonald, is among the best I’ve ever worked with; he has incredible patience, intellect, perspicacity, proportion, tact… you know, he’s a mensch.

So, with apologies to him and others, here is my rant on topics I run into as an author…

<rant>

Outliars

 

Whence the rule that any heading must have at least two sub-heads? Silly, absurd and a prescriptivist straight-jacket.

Animals

  Mammals

    Dogs

    Other Animals

  Marsupials

    Why they are funny looking

Plants

I simply reject as overly constraining the notion that “Why they are funny looking” must either have a sibling (“why editors are marsupials?”) or be merged into the parent (“Marsupials,  and why editors are funny looking”). 

Let me Make A Preposition To You

There are a number of dopey rules about prepositions that arise out of an insipid and false attempt to Latinize our Germanic language. The silliest is the “never end a sentence with a preposition”

No native-English speaking person would ever say  “What movie was it to which we went?”  You and I and everyone else who speaks the language would say “What movie did we go to?”

Infinitely Annoying

Again, arising from Latin but having nothing to do with English, came the pseudo-rule that you should never split the infinitive.  Besides causing you to stupidly put the verb in the wrong place (stupidly to put?) such a rule would not allow Captain Kirk to bravely go anywhere.

Are you more careful than she?

If I fell

I’ll just quote from John Lennon

If I give my heart to you

I must be sure

From the very start

That you would love me more than her

Can you quite imagine him writing “love me more than she”  ???

“Knock Knock”

“Who’s there?”

“I”

“eye?”

“Aye, it’s me”

    – Liberty 2009

Off To A Bad Start

There is no excuse for thinking that you can’t start a sentence with “There is.”  And I should add that I think it is fine to start a sentence with “and.” But not just and, even but.

A Singular Notion

While none of us is perfect, none of us are ever going to remember to use the singular because it doesn’t make sense much of the time.  Not everyone is annoyed when they see they used with a singular antecedent. If you are one who is, I recommend the brilliant paper written by Geoffry K. Pullman

Which Witch Created That Rule?

I’d almost given up on fighting the rule which is most often of concern to editors trained that one must never use  “which” to introduce a restrictive clause. But then I learned that this rule was invented out of whole cloth by the completely untrained  Strunk (of the infamous Strunk and White). It turns out, to his embarrassment, that Strunk violated this arbitrary caprice three times in Elements of Style.

 

</rant>

Posted in z Silverlight Archives | 1 Comment

Information for Silverlight HVP Developers…

Information for current and interested developers for the Silverlight HVP project has been consolidated, extended and updated on the new Developer’s Page.

</msg>

Posted in HyperVideo Player | Tagged | Comments Off on Information for Silverlight HVP Developers…

A Silverlight HVP Update

SLHvpLogo

A Silverlight HVP Update

I’m extremely pleased to report that a start-up e-learning company (currently code-named WL) has committed approximately 100 hours / week of development time by four of their world-class Silverlight developers,  from now through February. All of the work they do will be fully integrated into the Silverlight HVP and released under the Ms-PL.

We are currently working on the feature list for Version 1, but the very good news is that virtually all of the features they are most interested in,  are either on the feature list already (either for V1 or beyond) or are completely consistent with the idea and spirit of the Silverlight HyperVideo Player. 

Among the features under consideration for V1 (March, 2010) are:

Architecture

  • Implementing a fully modular architecture
  • MEF from Day 1
  • Creating a Viewer that will hold Frames, where Frames are named sets of controls.
  • One example of a Frame will be a player derived from the SMF
  • Another example of a Frame will be an HTML viewer for displaying web links
  • A third example of a Frame will probably display animations
  • A Table of Contents module that will house a class derived from Tree control
  • A Links module that will hold the links associated with a video
  • Features

    • Out of Browser capabilities
    • Identification, Authentication and Authorization
    • Local Storage
    • Skinning with Templates
    • Authoring Tools

    Interactivity & Collaboration

    • Multicasting
    • Interactive Response
    • Real-time communication

    Standards And Protocols

    • Extension of the protocols for encapsulating the linkage between a marker in a video and the actions to take (e.g., pausing the video and displaying additional information) to conform to emerging or existing industry standards.
    • Integration with existing or creation of new Experience (EMS) and Learning Management Systems (LMS) and other analytics
    • SCORM compatibility
    • Potential integration with Microsoft Semblio and related projects

    Details about WL will be available early in 2010, but we are already beginning the work of creating the specifications, and coding will start will start next week (“you start coding, I’ll go find out what they want…”)

    Core Technologies

    The Silverlight HVP is now committed to the following technologies and practices:

    Help Wanted!

    • Contributing Developers
    • QA
    • Project Management (assist with oversight of the project)
    • Software Architect to assist with creating units of work and “just-enough specification”

    Please see Contributing To The Project in the HVP CodePlex documentation.

    Unconfirmed and Fully Deniable Rumors

    We are discussing obtaining extensive User Interface support with a world-class web design organization that has done some incredibly creative and closely related work. More on this as soon as possible.

    Posted in z Silverlight Archives | Tagged | Comments Off on A Silverlight HVP Update

    4 Calendars & Plans for 2010 / 5770

    I live, more or less consciously. in the rhythm of four calendars; three of which are very closely aligned:

    • The Gregorian Calendar (Today is 12/20/2009)
    • The Jewish Calendar (Today is 3rd of Tevet, 5770 )
    • The Microsoft Fiscal Year (Today is about 3.5 months into my yearly commitments)
    • The Academic Calendar (while my kids are in school)

    Fortunately, the last three more or less align, so I tend to think in terms of two New Year’s – two times a year to revisit what I’m doing and recommit: early September and about now.

    Projects for Jan 1 – end of Microsoft FY

    Silverlight HVP

    This is a core commitment, both in terms of my commitments to Microsoft and to the community. It is also a labor of love – what could be more fund than bringing together a project that lets me work an application with potentially high value that also spins out learning material (mini-tutorials, tutorials, videos, etc.)  The state of this project as of Dec 19, 09, can be found here.

    Expect to see updates at least weekly and “releases” every other Wednesday as documented here.

    Tutorials & Mini-tutorials

    The Mini-Tutorials will focus on the following areas

    The Tutorials will often be roll-ups and integration of various mini-tutorials and videos. Expect to see mini-tutorials about weekly, and Tutorials about every six weeks.

    Blogging

    The blog will focus on the following topics (leavened now and again with other things as they occur to me):

    • Mini- Tutorials
    • HVP Status Updates
    • Geek Profiles
    • Twitter – Micro-blogging.

    Videos

    Videos will focus strongly on Silverlight 4 and MEF, SMF and WCF RIA Services

    Conferences & Presentations

    • Plans
    • Trip Reports
    Posted in z Silverlight Archives | Tagged | Comments Off on 4 Calendars & Plans for 2010 / 5770

    HVP Core Scaffolding and Updated News

     

    MiniTutorialLogo

    This article is part of the Mini-Tutorial Series

    slhvplogo50pct

    This article is part of the Silverlight HVP Documentation

     

    The State of the Silverlight HVP Project

     

    • LeanKit Kanban has licensed us under their Open Source provisions, and has gone the extra mile to give virtually unlimited licenses.
    • An e-learning start up is negotiating to contribute approximately 20+ hours per week for up to 3 months of free programmer time under the Ms-PL open source license as they are interested in using the HyperVideo player in their own project. This is not finalized, but is very exciting.
    • Six independent programmers have volunteered to contribute their time and effort to the project.
    • Discussions are under way with three different groups that may provide UX expertise.
    • Numerous groups inside and outside of Microsoft have expressed interest in participating in, or using the SilverlightHVP – announcements to follow as this firms up.

     Help Wanted: QA Testers – if interested, please contact me.

    Today:

    Today I checked in the scaffolding for the Silverlight HVP player, tearing out the test code in the player derived from the Silverlight Media Framework and adding ListBoxes for the Table of Contents and the Links. I also added splitters to allow the user to resize the windows, and a top and bottom row (in case we need it!)

    slhvp-12-19 

    Steps

    The steps to making these changes were to open the template in Blend and create a copy named SLHvpNoToggleButton in the same file (SlhvpPlayer.xaml).

    I took out all the changes we added previously, and then added 5 columns and 3 rows, placing the player in the second row, third column.

    In the first column (second row) I added  a list box to hold the Table of Contents, and hard wired some ListBoxEntry items as you can see in the image.

    In the fifth (far right) column (second row) I added a second list box in the same way, to represent the links.

    The second and fourth columns in the second row hold splitters to enable the user to resize the columns.

    All of this is checked-in to source code control as build 52656 available on the Silverlight HVP CodePlex Site under the Source Code tab.

      

      

      

      

      

      

      

      

    Project Management Tasks

    In addition to providing a more solid starting point, this completes a number of tasks. Here is the state of the project as represented on our KanBan board:

    KanBan-12-19-1330

    The newly completed tasks are under Ready To Deploy.  White indicates a task, Green a Feature, Light Blue an Improvement.

    Ready for Dev. indicates items from the backlog that have been pulled forward, waiting for a developer to take ownership. Participating developers start out as Patch Programmers (there are currently six), information on contributing is here. 

    Release Schedule

    As you may know, as of now, I’ve committed to two milestone releases.

    Current plans are to release an approved version every other Wednesday beginning December 23. Source code is continually available.

     

     

    Posted in z Silverlight Archives | Tagged | Comments Off on HVP Core Scaffolding and Updated News

    Extending the SMF for the HVP

    In a radical and terrifying experiment, I’m going to document what happens when I try to extend the Silverlight Media Framework (SMF) for the Silverlight HyperVideo Player as I do it.

    MiniTutorialLogo

    This article is part of the Mini-Tutorial Series

    SLHvpLogo

    This article is part of the Silverlight HVP Documentation

     

    My plan is to follow along with this video (part of the SMF documentation) and adapt it to extending the SMF player already embedded in the HVP source code so as to add a pseudo-links window to the right of the video player. 

    Note: Click on images below, to see full size.

    Adding the SMF Player

    1. I begin by checking out (updating) my copy of the Silverlight HVP source code (available here)SMFDlls to version 52279

    2. Opened the project and added a new view named Player

    3. Added the DLLs required by the SMF (see Image)

    4. Added the namespace for the Media Player to the top of the Player.xaml file

    5. Added the code to create a player that begins playing immediately, using the URL provided by the SMF project, as shown in the code block:

     

    xmlns:p="clr-namespace:Microsoft.SilverlightMediaFramework.Player;

       assembly=Microsoft.SilverlightMediaFramework.Player"

    <p:Player>

       <p:CoreSmoothStreamingMediaElement AutoPlay="True"

           SmoothStreamingSource="http://video3..../Manifest" />

    </p:Player>

     

     

     

    6. Added a block to MainPage.xaml to navigate to the new page:

    <HyperlinkButton x:Name="PlayerLink"

                     Style="{StaticResource LinkStyle}"

                     NavigateUri="/Player"

                     TargetName="ContentFrame"

                     Content="{Binding Path=ApplicationStrings.PlayerPageTitle, 

                            Source={StaticResource ResourceWrapper}}" />

    7. Opened Assets –> Resources –> ApplicationStrings.resx and added a string for the new page title and fixed up any detritus from previous updates.

    While I was at it, I removed the link to home.xaml and set About.xaml as the default page. Running the application brings you to the About page, clicking on the player page brings up the SMF player and starts the movie.

    Adding A Custom Player

    I’m now ready to begin the process covered in the SMF video Extending The Video Player

    Create a new class: SlhvpPlayer and add these attributes:

    [TemplatePart(Name="TOCToggle", Type=typeof(ButtonBase))]

    [TemplateVisualState(Name="ShowTOC", GroupName = "TOCVisibility")]

    [TemplateVisualState(Name="HideTOC", GroupName = "TOCVisibility")]

    Indicating that the class will have a template part of type Button that will toggle between the Show and Hide visual states.

    The new class extends Player, and thus needs a using statement:

    using Microsoft.SilverlightMediaFramework.Player;

    We’ll also give the class a private member variable to track whether the Table of Contents (toc) is visible,

    private bool tocIsVisible;

     

     

    The custom class also overrides OnApplyTemplate, calling the base method but retrieving a reference to the Button that (will be) in the templated player and setting a handler for the click event on that button. The click event toggles between the two visual states.

    public override void OnApplyTemplate()

    {

      base.OnApplyTemplate();

      var btn = GetTemplateChild("TOCToggle") as ButtonBase;

      if (btn != null)

      {

        btn.Click += BtnClick;

      }

    }

     

    private void BtnClick(object sender, RoutedEventArgs e)

    {

      tocIsVisible = !tocIsVisible;

      string whichState = tocIsVisible ? "ShowTOC" : "HideTOC";

      VisualStateManager.GoToState(this, whichState, true);

    }

     

    Returning to the Player.xaml file, you’ll need an alias to the project itself,

    xmlns:hvp="clr-namespace:SilverlightHVP"

     

    That will allow you to swap out the SMF player for your derived player:

    <hvp:SlhvpPlayer>

       <p:CoreSmoothStreamingMediaElement AutoPlay="True"

           SmoothStreamingSource="http://video3.../Manifest" />

    </hvp:SlhvpPlayer>

     

    Templating in Blend

    All of this is well and good, but nothing will change with the new player unless we open the project in Blend and set some form of behavior for the two Visual States we created. I’ll start by checking in what I have so far (always nice to have a working copy checked in). [Version 52355].

    Next Best Practice: I’ll stop for the night and get a good night’s sleep!

    — Next Day —

    My goal now is to modify the template to have a place for the links to the right of the video, and a button at the bottom that will make this appear and disappear.

    Adding the pseudo-links list

    Returning to the project, I’ll open it in Blend, double click on Player.xaml file and right click on the Player in Objects and Timeline and click on Edit Template –> Copy.  I’ve named the template SlhvpPlayerToggleButtonTemplate. I’ll select the radio button to place the new template into a Resource dictionary and name that dictionary SLHvpPlayer.xaml.

    Click on the layout controls in the toolbox and choose StackPanel. Double click to add a StackPanel to the template, and then right click on the StackPanel in the Objects and Timeline window and use the Order context menu to send it to the back. In the properties window, set its size to Auto/Auto and both alignments to Stretch. Finally, set its orientation to horizontal.

    Click on the  MediaPresenterElement (which displays the video) and drag and drop it onto the StackPanel, causing it to be a child of the StackPanel. Set its width to Auto.

    To stand in for the links, add a TextBlock to the StackPanel, Set its font to Goergia, 12 and its vertical alignment to center, horizontal alignment to stretch and its height and width to auto.

    Adding the Toggle Button

    In the Ojbects and Timeline window, click on the ControllerContainer, and then in properties set its height to Auto. Expand the Layout section and click on the elipses buttonRowDefinition for the RowDefinition collection (as shown, cropped) . Add two rows to the ControllerContainer, setting the height of each to Auto.

    In Objects and TimeLine click on the ControllerContainer to make it the selected object and then in the toolbox double click on the button, causing it to be added to the ControllerContainer. Click on the button in either Objects and Timeline or the designer and turn to the properties window where you can set the button’s ColumnSpan to 1, its Row to 1 (second row) and its margins to 0. Set its content to “Toggle.” 

    We want the name of the button to match the name we set up in the TemplatePart attribute for the derived player: TOCToggle.

    Toggling the View State

    Click on the States tab to open the States window and notice that the TOCVisibility states are available for you to modify. 

    CustomStatesClick on the ListBox and then on ShowTOC and set visibility to Visible. Then click on HideTOC and set visibility to collapsed. Finally, set the default transition time to 0.3s.  

     

     

    Click on the ShowTOC state and then click on the TextBox that holds our pseudo-links and set its Visibility property to visible. Then click on the red circle in the design frame to stop recording state changes.  Repeat for HideTOC setting Visibility to collapsed, and then save the project.

    Return to Visual Studio, click Yes to accept the changes that were made by Expression Blend and run the application. Click on the Player button and the movie starts playing. Click the toggle button to display or hide the “list of links”

    RunningPlayer

     

     

    Architectural  Note

    The goal will be to decouple the Links window, the Table of Contents window and the Player, through MEF, so that we can swap in alternative (or newer) versions of each without breaking the others. Time and resources will determine whether that is done in the first version or immediately afterwards

     

    There is much more to be done, but we’ve extended the SMF player within a view of the HVP project and it is quite clear that we can add both a links and a TOC window based on this work.  This is checked in as 52454

    Posted in z Silverlight Archives | Tagged | 5 Comments

    Contributing to the SL HVP

    [ Update:  Latest information on contributing now in the Silverlight HVP CodePlex documentation.]

    Help Wanted: Project Management

    The project would benefit tremendously by having someone in addition to me managing and coordinating the contributors, the trunk and branches of the source code and the evolving specifications for the core-project and any extensions.

     

    Posted in z Silverlight Archives | Tagged | Comments Off on Contributing to the SL HVP

    Best SF Books of All Time

    Someone just asked me my favorite SF books, and while creating such a list is almost absurd, nonetheless, it being the end of the year, here’s my top 10:

    Posted in z Silverlight Archives | Comments Off on Best SF Books of All Time

    Project Turing: Beginning RIA Services

    Reposted with VB.Net code

    From Database to DataGrid

    The next step in Project Turing is to create a first iteration of the Silverlight application that will retrieve data from our database.  Using our technology of choice: the Data Entity Framework coupled with .Net RIA Services.

    .Net RIA Services will allow us to create business logic on the server and to access that same set of classes on the client.  We will retrieve the data from these business classes and display them in a data grid within a business application, that is a multipage Silverlight application.

    .NET RIA Services

    While a great deal has been written about RIA Services, I find when talking with Silverlight developers that there is still some confusion about where RIA Services are best used and what the key benefits are.  This really  isn’t terribly surprising given how new the RIA Services platform is. Despite the incredible work done by Brad Abrams and others on the dev team  to document RIA Services,  it will take a while for many Silverlight programmers to fully integrate the platform into their designs

    Project Turing offers an ideal opportunity to provide an incremental introduction to  RIA Services and an illustration of the immediate benefits of the platform.

    Just before the progress took the digression into Linq, we created our basic database tables, and the initial architecture of Project Turing. Here is a snapshot of the database as it exists at this point in the project:

    DataBaseDesign
    (click on image for full size)

    Our goal now is to retrieve this data using the Data Entity Framework and to make it available to the DataGrid using .NET RIA Services.

    What You Need To Program With RIA Services Project

    For this part of Project Turing you’re going you need to install the latest .Net RIA Services framework.  You can find complete instructions and all of the libraries that you need here. (There is no cost.)

    You also want to create or download the Turing database, which you can install to SQL Server 2005, SQL Server 2008, or SQL express.  You can download a backup of this database and restore it to your system, from here.  Alternatively you can download a script to re-create the database from here.

    Getting Started

    We will build the application incrementally, starting with a simple version and adding complexity as we go.  Specifically, we will break down the steps of interacting with the database into a series of smaller tasks.

    The goal in this first example will be to create a shell of a multipage application, and within that a page to which we’ll add a basic  DataGrid. To get started open Visual Studio and create a new project. In the Project Type, select Visual C#/Silverlight, and in the templates select Silverlight Business Application.  I named my project TuringRIAServices.

    Creating Business App
    (Click image for full size)

    A fairly sophisticated Silverlight application is created for you out-of-the-box.  Your solution consists of two projects, and your Xaml project has three subdirectories: Assets, Libs, and Views.

    The views folder contains the initial pages already provided in the application.  These include Xaml files for logging in, a Home page, a custom error window and an about box.

    MainPage.xaml acts as a shell and a dispatcher to the pages that are in the Views folder.  The Assets folder contains your first styles Xaml page, but you are free to add more (as you are to all the folders).

    To begin open MainPage.xaml and let’s examine some of what has been put in place by Visual Studio.

    <Grid x:Name="LayoutRoot" Style="{StaticResource LayoutRootGridStyle}">
    <Border x:Name="ContentBorder" Style="{StaticResource ContentBorderStyle}">
               <navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}"
                                 Source="/Home" Navigated="ContentFrame_Navigated" NavigationFailed="ContentFrame_NavigationFailed">
                    <navigation:Frame.UriMapper>
                      <uriMapper:UriMapper>
                        <uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
                         <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
                       </uriMapper:UriMapper>
                     </navigation:Frame.UriMapper>
                 </navigation:Frame>
         </Border>
    
         <Grid Style="{StaticResource NavigationOuterGridStyle}">
           <Grid x:Name="NavigationGrid" Style="{StaticResource NavigationGridStyle}">
    
            <Border x:Name="BrandingBorder" Style="{StaticResource BrandingBorderStyle}">
            <StackPanel x:Name="BrandingStackPanel" Style="{StaticResource BrandingStackPanelStyle}">
    
                 <ContentControl Style="{StaticResource LogoIcon}"/>
                 <TextBlock x:Name="ApplicationNameTextBlock" Style="{StaticResource ApplicationNameStyle}"
                                   Text="Application Name"/>
    
              </StackPanel>
            </Border>
    
            <Border x:Name="LinksBorder" Style="{StaticResource LinksBorderStyle}">
              <StackPanel x:Name="LinksStackPanel" Style="{StaticResource LinksStackPanelStyle}">
    
    <HyperlinkButton x:Name="Link1" Style="{StaticResource LinkStyle}"
                                      NavigateUri="/Home" TargetName="ContentFrame" Content="home"/>
    
               <Rectangle x:Name="Divider1" Style="{StaticResource DividerStyle}"/>
    
                <HyperlinkButton x:Name="Link2" Style="{StaticResource LinkStyle}"
                                         NavigateUri="/About" TargetName="ContentFrame" Content="about"/>
    
               </StackPanel>
             </Border>
    
           </Grid>
    
           <Border x:Name="loginContainer" Style="{StaticResource LoginContainerStyle}"/>
        </Grid>
    
      </Grid>

    Before taking this apart lets look at what is created if you build and run this without making any changes.

    Running Out of the box

    (Click image for full size)

    You can see in the image that there is a frame around the home page, which has within it a logo, the name of the application, a button for the currently selected page, a button for the about page, and a small button for the login dialog.

    This corresponds directly of course to the Xaml above.

    On line 2, we  create a border, which uses the static resource predefined by Visual Studio and stored in  Styles.Xaml within the Assets folder.

    Within that border a Frame object is defined on line 3 through 11, within the navigation namespace defined at the top of the file.

    xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"

    The frame has three critical properties:

    • The source.
    • The name of the method to call after successfully navigating to the page.
    • The name of the method to call in the event of failure.

    Nested within the frame is a mapper, whose job is to map pages to URIs.

    Note on line 8, the generic mapping that is used with the substitution parameter pagename.  This is a subtle but very powerful capability that allows you to create essentially a template of the relationship between pages in their URI and avoid duplicating this code for every page.

    The second major UI area within this Xaml file begins on lines 14 and 15 with the creation of an outer and inner grid.

    The content control defined on line 20 is used to display the logo and on line 21 is a standard textblock, where the text is set to Application Name.  This would be a good opportunity to change that text to “Project Turing RIA Services”

    The second area is itself divided in to two areas each with its own water, and in the lower area beginning on line 27.  Line 30 shows the hyperlink button for the homepage and on line 35 is the hyperlink button for the about page.  Adding a new button only requires an additional hyperlink button.  In this section, the navigation is handled by the section about.

    You may find it worthwhile and interesting to open up the style.xaml  file, and take a look at the static resources that were created by this template.

    Adding A DataGrid

    We will add the Silverlight control DataGrid to a new Silverlight page.  To do so, right-click on the project and choose Add –> New Item.  In the Add Item dialog box, choose Silverlight under categories and Silverlight Page in the templates pane.

    Name the new page BlogsDataGrid and click Add.

    At the top of this page, we will place a header as we will on each new page.  The header consistents of a  ScrollViewer, within which we will place a StackPanel, within which we will place a Toolbox with the name of the page as shown here:

    Note: this design, and much in these examples, comes from the Walk-Through created by the development team and used here with their permission, for which I and my Carpal Tunnel Syndrome are very grateful.

    <ScrollViewer BorderThickness="0"

                  VerticalScrollBarVisibility="Auto"

                  Padding="12,0,12,0"

                  Margin="-12">

        <StackPanel Margin="0,12,0,12"

                    Orientation="Vertical">

            <TextBlock Text="Blogs"

                       Style="{StaticResource HeaderTextStyle}" />

        </StackPanel>

    </ScrollViewer>

    Finally, drag a DataGrid from the toolbox into the grid.

    Note: the advantage of dragging from the toolbox rather than writing the Xaml by hand is that Visual Studio will create the necessary namespace and use that as a prefix for the DataGrid
    xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

    Once Visual Studio has fixed up the namespace, modify the data grid element to include the properties Name (BlogsDataGrid), MinHeight (150), and IsReadOnly (true).

    <navigation:Page

      xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

      x:Class="TuringRiaServices.Blogs"

      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:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"

      mc:Ignorable="d"

      d:DesignWidth="640"

      d:DesignHeight="480"

      Title="Blogs Page">

        <Grid x:Name="LayoutRoot">

            <ScrollViewer BorderThickness="0"

                          VerticalScrollBarVisibility="Auto"

                          Padding="12,0,12,0"

                          Margin="-12">

                <StackPanel Margin="0,12,0,12"

                            Orientation="Vertical">

                    <TextBlock Text="Blogs"

                               Style="{StaticResource HeaderTextStyle}" />

                </StackPanel>

            </ScrollViewer>

            <data:DataGrid x:Name="blogsDataGrid"

                           MinHeight="150"

                           IsReadOnly="True"></data:DataGrid>

        </Grid>

    </navigation:Page>

    Your page is ready, but there is no way to navigate to it.  Return to MainPage.Xaml and let’s add the logic for an additional button.

    First, take a look at the solution Explorer, and if BlogsDataGrid.Xaml is not in the views folder   drag it there now.

    As noted above, all we need to do here is add a hyperlink button for our new page.  This will go immediately below the hyperlink button for the about box

    <HyperlinkButton x:Name="Link3"

                     Style="{StaticResource LinkStyle}"

                     NavigateUri="/Blogs"

                     TargetName="ContentFrame"

                     Content="Blogs" />

    Build and run the application and be sure to click on the new button for the Blogs page. Please take note of the very elegant handling of the exception that is thrown, because we wired up for a same blogs.  But our actual page is named BlogsDataGrid.

    While we’re fixing that link, lets take note of the fact that Visual Studio has named each of the hyperlink buttons.  Link one, link two etc. , while it is natural and common to continue this as we have done above, I greatly prefer to name the hyperlink buttons to indicate their function.  And so I will rename Link1  HomeLinkButton; Link2  AboutLinkButton and our Link3 BlogsLinkButton. I will also fix up the NavigateURI to the full name of the page.

    One defensible choice is to continue the pattern provided by Visual Studio, but it is my personal approach to rename all three on the premise that good naming practice makes for good documentation.

    <UserControl x:Class="TuringRIA_Services.MainPage"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"     xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"     xmlns:dataControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d"     d:DesignWidth="640"     d:DesignHeight="480">   <Grid x:Name="LayoutRoot"         Style="{StaticResource LayoutRootGridStyle}">      <Border x:Name="ContentBorder"              Style="{StaticResource ContentBorderStyle}">         <navigation:Frame x:Name="ContentFrame"                           Style="{StaticResource ContentFrameStyle}"                           Source="/Home"                           Navigated="ContentFrame_Navigated"                           NavigationFailed="ContentFrame_NavigationFailed">            <navigation:Frame.UriMapper>               <uriMapper:UriMapper>                  <uriMapper:UriMapping Uri=""                                        MappedUri="/Views/Home.xaml" />                  <uriMapper:UriMapping Uri="/{pageName}"                                        MappedUri="/Views/{pageName}.xaml" />               </uriMapper:UriMapper>            </navigation:Frame.UriMapper>         </navigation:Frame>      </Border>      <Grid Style="{StaticResource NavigationOuterGridStyle}">         <Grid x:Name="NavigationGrid"               Style="{StaticResource NavigationGridStyle}">            <Border x:Name="BrandingBorder"                    Style="{StaticResource BrandingBorderStyle}">               <StackPanel x:Name="BrandingStackPanel"                           Style="{StaticResource BrandingStackPanelStyle}">                  <ContentControl Style="{StaticResource LogoIcon}" />                  <TextBlock x:Name="ApplicationNameTextBlock"                             Style="{StaticResource ApplicationNameStyle}"                             Text="Project Turing RIA Services" />               </StackPanel>            </Border>            <Border x:Name="LinksBorder"                    Style="{StaticResource LinksBorderStyle}">               <StackPanel x:Name="LinksStackPanel"                           Style="{StaticResource LinksStackPanelStyle}">                  <HyperlinkButton x:Name="HomeLinkButton"                                   Style="{StaticResource LinkStyle}"                                   NavigateUri="/Home"                                   TargetName="ContentFrame"                                   Content="home" />                  <Rectangle x:Name="Divider1"                             Style="{StaticResource DividerStyle}" />                  <HyperlinkButton x:Name="AboutLinkButton"                                   Style="{StaticResource LinkStyle}"                                   NavigateUri="/About"                                   TargetName="ContentFrame"                                   Content="about" />                  <HyperlinkButton x:Name="BlogsLinkButton"                                   Style="{StaticResource LinkStyle}"                                   NavigateUri="/BlogsDataGrid"                                   TargetName="ContentFrame"                                   Content="Blogs" />               </StackPanel>            </Border>         </Grid>         <Border x:Name="loginContainer"                 Style="{StaticResource LoginContainerStyle}" />      </Grid>   </Grid></UserControl>

    This time clicking on the blogs hyperlink does not throw an exception but rather brings you to the blogs page, where the outline of the DataGrid is drawn but of course there is as of yet no data.  Let’s fix that now.

    Adding Business Logic And Data

    Our next principal task is to retrieve data from the database and present it to the DataGrid.  As noted in previous mini tutorials and postings for this project, there are a number options for retrieving data from a database.  One of the most powerful is to use the Entity Framework.

    When a developer says technology is “powerful,” we typically mean that it does a lot of the routine plumbing for us, and that it is highly flexible.  Certainly both are true of the Entity Framework.

    A quick look at Julia Lerman’s Programming Entity Framework (O’Reilly Media, 2009) is both reassuring and somewhat intimidating; her book is over 750 pages.  This stands as testimony to the enormous flexibility of the Entity Framework.

    That said, using the Entity Framework to retrieve data from a relatively straightforward relational database can be explained quite quickly. I will demonstrate enough of the Entity Framework to get a feel for the role that it plays and the level of abstraction that it provides, but in no way will this be a comprehensive survey of the Entity Framework in its entirety.

    To begin, add a new item to Turing RIA Services.web.  In the Add New Item dialog select Data in the Categories pane, and choose ADO.net Entity Data Model in the templates pane, and name the new Entity Data Model TuringBlogs.  Indicate to the Entity Data Model Wizard that you wish to generate your model from an existing database.

    Adding Entity Data Model

    (Click image for full size)

    You’ll be prompted to create or reuse a connection string for your database

    CreateDataConnection

    (Click image for full size)

    Note that using the second radio button “include the sensitive data in the connection string,”  will slightly simplify your code, but expose a significant security hole.

    After connecting to your database, you’ll be asked to choose which objects you wish to include.  Expand the tables, and select the Blogs table.

    SelectBlogsTable

    (Click image for full size)

    When you click finish, the entity data model will appear in the designer. To verify that everything is correct, build the solution.

    Transporting the Data Class To The Client With .Net RIA Services

    You’re halfway home.  You now have an entity (object) that represents the data that is stored in relational tables in SQL Server.  The next step is to create business classes that will represent and manipulate that data on the server, and be equally available on the client.  That is in a nutshell, what.net RIA Services does for a living.

    Once again right-click on the Turing RIA Services Web project, and add a new item. However this time, in the Categories pane, select Web and in the templates pane Domain Service Class.  Name the new item BlogsService and click Add.

    AddingBlogService

    (Click image for full size)

    Click Add which will open the Add New Domain Service Class dialog. Select Blogs from the list of entities (okay, in this case it’s the only item in the list).  In the same dialog, be sure to check Enable Editing, which enables the CRUD functionality, and at the bottom of the dialog, click “Generate associated classes for metadata.” Then click OK.

    NewDomainServiceClassDialog

    (Click image for full size)

    Open the class of this generates for you: BlogsService.cs and modifying the GetBlogs method as follows:

    C#

    //Replace this generated code:
    public IQueryable GetBlogs()
    {
       return this.Context.Blogs;
    }
    
    // with this custom code:
    public IQueryable GetBlogs()
    {
      return this.Context.Blogs.OrderBy(b => b.BlogName);
    }

    VB.Net

    'Replace this generated code:
    Public Function GetBlogs() As IQueryable(Of Blogs)
       Return Me.Context.Blogs
    End Function
    
    ' with this custom code:
    Public Function GetBlogs() As IQueryable(Of Blogs)
      Return Me.Context.Blogs.OrderBy(Function(b) b.BlogName)
    End Function

    In this first example, our customization is ordering the results by the name of the blog.

    Define It on the Server, Invoke It on the Client

    When you rebuild the solution not only will the classes that you’ve created in the server be built, but a corresponding set of proxy classes will be built in the client project.

    Thus the class and its method will be available on the client side, and therefore available to our DataGrid.  At the top of the code behind page will need to add three using statements; one to bring in the web project, and the other two for RIA Services:

    C#

    using TuringRIAServices.Web;
    using System.Windows.Ria.Data;
    using System.Windows.Ria.ApplicationServices;

    VB.Net

    Imports TuringRIAServices.Web
    Imports System.Windows.Ria.Data
    Imports System.Windows.Ria.ApplicationServices

    In the generated code in the client project, the BlogsContext is generated based on the BlogsService you created on the server. To see the definition, turn on show all files, and locate the file TuringRIAServices.web.g.cs / TuringRIAServices.web.g.vb. Inside the previously hidden Generated_Code folder. In that file, you will find the definition for the BlogsContext.

    C#

    public sealed partial class BlogsContext : DomainContext
    {
        partial void OnCreated();
    
        public BlogsContext() :
                this(new HttpDomainClient(
                  new Uri("DataService.axd/TuringRIA_Services-Web-BlogsService/", System.UriKind.Relative))) {}
    
       public BlogsContext(Uri serviceUri) :
                this(new HttpDomainClient(serviceUri)) {}
    
        public BlogsContext(DomainClient domainClient) :
                base(domainClient)
        { this.OnCreated(); }
    
        public EntityList Blogs
        {
            get { return base.Entities.GetEntityList();  }
        }
    
        public EntityQuery GetBlogsQuery()
        {
            return base.CreateQuery("GetBlogs", null, false, true);
        }
    
        protected override EntityContainer CreateEntityContainer()
        {
            return new BlogsContextEntityContainer();
        }
    
        internal sealed class BlogsContextEntityContainer : EntityContainer
        {
    
            public BlogsContextEntityContainer()
            {
                this.CreateEntityList(EntityListOperations.All);
            }
        }
    }

    VB.Net

    Public NotInheritable Partial Class BlogsContext
    	Inherits DomainContext
    	Partial Private Sub OnCreated()
    	End Sub
    
    	Public Sub New()
    		Me.New(New HttpDomainClient(New Uri("DataService.axd/TuringRIA_Services-Web-BlogsService/", System.UriKind.Relative)))
    	End Sub
    
       Public Sub New(ByVal serviceUri As Uri)
    	   Me.New(New HttpDomainClient(serviceUri))
       End Sub
    
    	Public Sub New(ByVal domainClient As DomainClient)
    		MyBase.New(domainClient)
    	Me.OnCreated()
    	End Sub
    
    	Public ReadOnly Property Blogs() As EntityList(Of Blogs)
    		Get
    			Return MyBase.Entities.GetEntityList(Of Blogs)()
    		End Get
    	End Property
    
    	Public Function GetBlogsQuery() As EntityQuery(Of Blogs)
    		Return MyBase.CreateQuery(Of Blogs)("GetBlogs", Nothing, False, True)
    	End Function
    
    	Protected Overrides Function CreateEntityContainer() As EntityContainer
    		Return New BlogsContextEntityContainer()
    	End Function
    
    	Friend NotInheritable Class BlogsContextEntityContainer
    		Inherits EntityContainer
    
    		Public Sub New()
    			Me.CreateEntityList(Of Blogs)(EntityListOperations.All)
    		End Sub
    	End Class
    End Class

    Returning to BlogsDataGrid.xaml.cs, instantiate a BlogsContext as a member variable,

    C#

    private BlogsContext blogsContext = new BlogsContext();

    VB.Net

    Private blogsContext As New BlogsContext()

    Here is the complete BlogsDataGrid.xaml.cs / BlogsDataGrid.xaml.vb

    C#

    private BlogsContext blogsContext = new BlogsContext();

    VB.Net

    Private blogsContext As New BlogsContext()

    Here is the complete BlogsDataGrid.xaml.cs (BlogsDataGrid.xaml.vb in case of VB.Net):

    C#

    using System.Windows.Controls;
    using System.Windows.Navigation;
    using TuringRIA_Services.Web;
    using System.Windows.Ria.Data;
    using System.Windows.Ria.ApplicationServices;
    
    namespace TuringRIA_Services
    {
       public partial class BlogsDataGrid : Page
       {
          private BlogsContext blogsContext = new BlogsContext();
    
          public BlogsDataGrid()
          {
             InitializeComponent();
             this.blogsDataGrid.ItemsSource = blogsContext.Blogs;
             blogsContext.Load( blogsContext.GetBlogsQuery() );
          }
    
          protected override void OnNavigatedTo( NavigationEventArgs e )
          {
          }
       }
    }

    VB.Net

    Imports System.Windows.Controls
    Imports System.Windows.Navigation
    Imports TuringRIA_Services.Web
    Imports System.Windows.Ria.Data
    Imports System.Windows.Ria.ApplicationServices
    
    Namespace TuringRIA_Services
       Partial Public Class BlogsDataGrid
    	   Inherits Page
    	  Private blogsContext As New BlogsContext()
    
    	  Public Sub New()
    		 InitializeComponent()
    		 Me.blogsDataGrid.ItemsSource = blogsContext.Blogs
    		 blogsContext.Load(blogsContext.GetBlogsQuery())
    	  End Sub
    
    	  Protected Overrides Sub OnNavigatedTo(ByVal e As NavigationEventArgs)
    	  End Sub
       End Class
    End Namespace

    In the constructor, you ask the BlogsContext object to retrieve its Blogs property (an entity list of Blogs) and this collection is assigned as the ItemsSource of the DataGrid. The following line instructs the Blog Context to call its Load member method, passing in the query retrieved by calling GetBlogQuery().  This will be the query that we customized earlier.

    The query as you remember, retrieves all of the blogs, ordered by the name of each blog.  This collection is assigned to the DataGrid and the page is displayed when you click on the blogs button.

    DataGridRunning

    (Click image for full size)

    What have you learned, Dorothy?

    In this first iteration of moving data from our SQL Server database to the DataGrid on our client, we have examined using the Entity Framework for creating an object orientated model of the data in the database, and using RIA Services both to provide a common set of business classes on the server and the client and to provide transportation of the data from server-side to client-side.

    In the next posting on Project Turing,  I will examine both more complex, data retrieval and how we go about modifying the data in the database based on user actions on the client.

    Please note that due to Carpal Tunnel Syndrome this posting was dictated and then transcribed by computer.  I apologize for any resulting absurdities.
    Novice Previous:  Linq Next: CRUD Operations with Entity Frameworks
    Advanced Previous:  Linq Previous:  Linq
    Posted in Mini-Tutorial, z Silverlight Archives | Tagged , | 6 Comments

    Geek Profiles – Scott Guthrie

    Part of what Tim and I do is to provide meaningful connections between the dev team and the community. Today I’m happy to launch a new series of Geek Profiles, highlighting many of the folks who design and implement Silverlight.  These are not intended to be “People Magazine” puff pieces, nor are they  intended to be probing journalistic inquiries into their work; rather a small attempt to bring forward some of the amazing people who work on this project in their own words.

    There couldn’t be a better person to begin with than Scott Guthrie.   Scott is Corporate Vice President .NET400px-MIX_Keynote-Scott_Guthrie_09_MS_05_2007 Developer Platform and is responsible for the development of Silverlight, the CLR, ASP.NET, WPF, IIS, and Visual Studio (among others). Not bad for a guy who was born three years after I graduated high school (!)

     He describes himself in a single sentence, “I live in Seattle and develop a few software products for Microsoft.”

    Yah.

    He has, in fact, become something of an icon among .NET developers, and I’ve commented before that he is the first manager I’ve ever seen at a presentation get a standing ovation before saying a word.

    On a personal note, I met Scott twice. The first time was in the very early 1990s at an author’s dinner, where he impressed as a very bright, interested guy, and I remember my editor and I saying “someone to get to know.”  It took about 15 years, until I met him again as part of my interview process at Microsoft (after seeing him give a sea-change presentation on Silverlight, but that is another story).

    During the time I was in his organization, I had the opportunity to talk with Scott quite a bit, and he has a unique ability to convince you that there is nothing he’d rather do than spend that 5, 15 or 30 minutes talking to you – everyone feels it.  He is passionate about his work, and about quality and I honestly think he is a bit nonplussed by becoming a geek celebrity.

    Here is the brief interview I had with him a couple weeks before PDC:

    Q: What are you most enthusiastic about in Silverlight 4?

    Scott: I like the power that is now available to out of browser SL applications.  This really opens up a ton of possibilities for developers.

    Q:  Do you have any words of advice for Silverlight programmers?

    Scott: Use the power of SL for good and not evil :-)  There is a lot of power there and you can do a lot of things – but always make sure that what you do enhances the user experience of your solution as opposed to being purely gratuitous eye-candy. 

    Q: Can you tell us something (or some incident) that folks probably don’t know about you?

    Scott: I’ve been fortunate to have been at the beginning of several projects – including .NET, ASP.NET SGBobbleHeadand Silverlight.  It has been a fun ride.

    Q: You are the only techie I’ve ever seen get a standing ovation before his presentation. What do you think has most contributed to the “Gu” phenomenon?

    Scott: It is an odd thing and I’m not really sure what to think about it.  I’m flattered (and kind of embarrassed) by it all. Ultimately it is really the technology people are excited about.  Many, many people enabled the technology – my role in the grand scheme of things is relatively small.  

    Scott’s quote on receiving the bobble-head: “Weird. Very weird.”

     

    Resources

    ScottGu.Com
    Scott’s Blog

     

    Editor’s note: yes, this was quick and light, and the future profiles will, I hope, have a bit more depth, but the goal is not to create a full profile but rather to introduce some folks on the team you may not know.  I’ll try to include the super-stars like Scott, and Mike Harsh, Karen Corby and Brad Abrams, but also some of the developers who do not present and who you may not yet know.

    In any case, I’ll follow up with Scott now that Silverlight 4 is released and try to get a bit more of a look into how he came to do what he does.

     

    [Coming up next week: serious mini-tutorials, both on Silverlight From Scratch and on the HyperVideo project, MEF, and much more]

    Posted in z Silverlight Archives | Comments Off on Geek Profiles – Scott Guthrie