What's New in the .NET Framework 3.5

In this lesson of the Silverlight tutorial, you will learn...
  1. About the XML grammar, the Extensible Application Markup Language (XAML), that new .NET Framework technologies, particularly WPF, utilize heavily
  2. How to create amazing user interfaces by using Windows Presentation Foundation (WPF)
  3. To create distributed applications by using the latest distributed technology, Windows Communication Foundation (WCF)
  4. To document and design complex business processes by using Windows Workflow Foundation (WF)
  5. How sensitive user data can be better protected through Windows CardSpace
  6. About optimizing data access and queries through the use of Language Integrated Query (LINQ)

This lesson will introduce you to the new features available in the .NET Framework version 3.5.

Overview

The .NET Framework is continuously being upgraded and improved both through the introduction of brand new technologies and through the extension and enhancement of existing technologies. The last major update to the .NET Framework was version 2.0. In version 2.0, most of the included technologies received major enhancements. The .NET Framework 3.0 was advertised as including a gamut of new technologies but no significant updates to the existing .NET Framework 2.0 technologies. The new technologies in the .NET Framework 3.0 include:

  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Windows Workflow Foundation (WF)
  • Windows CardSpace

The new technologies are illustrated in the following diagram.

The .NET Framework 3.5 is considered an interim update that does introduce some enhancements to existing technologies in the form of new controls, fixes, etc and does include the integration of two new technologies: Language Integrated Query (LINQ / XLINQ) and ASP.NET AJAX. The figure below illustrates the progression of technologies added through versions 2.0, 3.0, and 3.5.

The Extensible Application Markup Language (XAML)

The Extensible Application Markup Language (XAML - pronounced "zammel") is an XML grammar that is used to define objects and their contained properties and methods that are typically used to construct a user interface. XAML has been made popular through its use in the Windows Presentation Foundation (WPF) that is used to define the Windows Vista user interface. XAML was created by Microsoft and introduced with the .NET Framework version 3.0. XAML can be used to define 2D and 3D graphics and animations.

Elements that are declared in XAML generally represent objects that exist in the .NET Framework. XAML is used most often in either the context of WPF or Silverlight. When a XAML file is read, the XAML parser instantiates .NET Framework objects corresponding to the elements read in the XAML file. Just as elements in a XAML file typically represent objects, attributes of an element generally represent properties of an object. Consider the following XAML fragment.

<TextBlock
  Margin="15,8,98,0"
  TextWrapping="Wrap"
  VerticalAlignment="Top"
  Height="38"
  FontFamily="Segoe UI">
  <Run
    FontSize="14"
    Text="Welcome to my Fantasy League Manager"/>
</TextBlock>

The XAML fragment above is used to define a TextBlock on a WPF Window. When the XAML parser encounters this element, it creates an instance of the System.Windows.Controls.TextBlock class. The TextBlock class is used to display small amounts of flow content, such as text or labels. In the example above, the TextBlock contains a Run child object that accommodates further formatting of contained text. The attributes of the TextBlock and Run elements are declared to set values for the properties of the instantiated TextBlock and Run objects. The XAML shown above declares the header displayed on the window shown in the figure below.

The great part of using XAML to define user interface components is that XAML is programming language, and really development environment, agnostic. Just as with other .NET Framework technologies and Web technologies, you can create XAML documents by using any text editor and can parse and manipulate XAML by using virtually any programming language. WPF is optimized to read, parse, and execute XAML.

Bear in mind when working with XAML:

  • XAML is an XML grammar. XML is case-sensitive; hence XAML is case-sensitive. In most cases, XAML casing must match the casing of underlying objects and properties.
  • Just as with XML, white space in XAML is consolidated into a single space and is, in essence, not significant.
  • All XML documents must have a single root, or document-level, element. The document element for XAML files, when used with WPF, should be either <Window> or <Page>, depending upon the type of application being created. In Silverlight, the document element should be <Canvas>.

Alternate Attribute Syntax

The implementation of XAML illustrated in the example shown above is the simplest and most common XAML configuration for assigning values to attributes and is referred to as, not surprisingly, attribute syntax. When creating an XML grammar, extended data values may be defined through either attributes or child elements. The same applies to the XAML standard. By default, properties are defined for objects through attributes in XAML and this method works great for simple property values. However, some properties require more complex values to be assigned to them, such as child objects (reference types), or, potentially, a property may accommodate multiple values to be assigned to it. In such a scenario, a simple attribute assignment won't suffice.

When determining the appropriate method of assigning property values through XAML, keep relational database design principles in mind; particularly the rules of normalization. XML is used for storing data. If XML, and in this case XAML, is designed with the rules of normalization in mind, object and property relationships should be able to map well to XAML.

Property Element Syntax

When designing XML, with relational database design rules in mind, an attribute typically correlates to a column in a table and this is a logical correlation as Dr. E.F. Codd refers to columns in tables as "attributes". The second normal form of relational database normalization, according to Dr. E.F. Codd, mandates that there should be no repeating groups of attributes and no mutli-value attributes. To break that down, in XML, no attributes should contain multiple values. If multiple values, or complex values, need to be assigned to a property of an object, and, in turn, an attribute in XAML, the values should be identified by using additional elements instead of attributes.

Hence, in scenarios where attribute syntax is not adequate for assigning a value to a property, additional elements should be used to identify the property value(s). When elements are used to identify property values in XAML, it is referred to as "property element" syntax. Furthermore, any property values declared by using attribute syntax should also be able to be declared by using property element syntax, however, the opposite is rarely true.

As an example, the XAML used to define the background of the WPF window shown above utilizes property element syntax as shown in the code snippet below.

<Window.Background>
  <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" SpreadMethod="Pad">
    <GradientStop Color="#FF495B24" Offset="0"/>
    <GradientStop Color="#FFB4C397" Offset="0.416"/>
  </LinearGradientBrush>
</Window.Background>

In the code shown above, the background of the window could optionally be declared by using attribute syntax as <Window Background="<property values...>" />. However, look at the code snippet above. How can a single attribute value summarize the more complex LinearGradientBrush settings? It is not possible. Hence, in order to adequately accommodate more advanced property values, the values must be stated by using elements instead of attributes as shown above.

Markup Extensions

When creating XAML documents, bear in mind that the XAML parser is creating object instances as it encounters XAML elements. In many scenarios, the default XAML parser behavior may result in non-optimal use of memory. For instance, when defining styles, behind the scenes, a formal Style object is created to hold the style information. Style information, in general, will likely be shared across many objects in the user interface. By specifying style information at the element level for each object in the user interface, many style objects are created behind the scenes that hold identical style information. Much fewer resources could be consumed by creating a single Style object and sharing it amongst the user interface objects by referencing it from the user interface objects. Additionally, style information could be managed and updated much easier if it were defined in a single location instead of multiple locations. This is the same premise that lies behind an external style sheet.

The solution to better memory optimization is to declare a Style (or other object) as a global, or shared, resource. A shared resource can then be referenced by other objects in the user interface through markup extensions. A markup extension allows you to define an attribute value as a reference to a shared resource. There are several types of markup extensions with the most common type being a Binding Markup Extension used in data binding, a Static Resource Markup Extension used to reference static shared resources (resources declared and available at compile time), and a Dynamic Resource Markup Extension used to reference dynamic shared resources (resources not available until run time).

A markup extension reference is delimited using opening and closing curly braces ({}). The example below illustrates gradient background colors utilized as window resources and referenced using dynamic resource markup extensions.

<Window.Resources>
 <Color x:Key="myGreenColor">#FFB4C397</Color>
 <Color x:Key="myDarkGreenColor">#FF495B24</Color>
</Window.Resources>
<Window.Background>
 <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" SpreadMethod="Pad">
  <GradientStop Color="{DynamicResource myDarkGreenColor}" Offset="0"/>
  <GradientStop Color="{DynamicResource myGreenColor}" Offset="0.431"/>
 </LinearGradientBrush>
</Window.Background>

The full XAML used to generate the window in the figure above is shown in the code listing below.

Code Sample: WhatsNewNETFramework35/Demos/MyFantasyPicks/MyFantasyPicks/Window1.xaml

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MyFantasyPicks.Window1"
    Title="Fantasy League Manager 2008" Height="216" Width="529" x:Name="DisplayMyPicks" xmlns:d="http://schemas.microsoft.com/expression/blend/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
 <Window.Resources>
  <Color x:Key="myGreenColor">#FFB4C397</Color>
  <Color x:Key="myDarkGreenColor">#FF495B24</Color>
 </Window.Resources>
 <Window.Background>
  <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" SpreadMethod="Pad">
   <GradientStop Color="{DynamicResource myDarkGreenColor}" Offset="0"/>
   <GradientStop Color="{DynamicResource myGreenColor}" Offset="0.431"/>
  </LinearGradientBrush>
 </Window.Background>
    <Grid>
  <TextBlock Margin="10,10,0,0" VerticalAlignment="Top" FontFamily="Segoe UI" Text="Welcome to the Fantasy League Manager" />
  <Path Margin="15,30,15,0" VerticalAlignment="Top" Height="0.5" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M19,32 L469,33" />
  <Button HorizontalAlignment="Left" Margin="15,41,0,0" VerticalAlignment="Top" Width="189" Height="23" Content="Display My Picks" x:Name="btnDisplayPicks" Click="btnDisplayPicks_Click">
   <Button.Background>
    <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
     <GradientStop Color="#FFF3F3F3" Offset="0.005"/>
     <GradientStop Color="#FFEBEBEB" Offset="0.44"/>
     <GradientStop Color="#FFDDDDDD" Offset="0.531"/>
     <GradientStop Color="#FFDAB925" Offset="0.904"/>
    </LinearGradientBrush>
   </Button.Background>
  </Button>
  <Path x:Name="pMiddle" Margin="15,73.5,15,0" VerticalAlignment="Top" Height="0.5" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M19,32 L469,33" Visibility="Visible" />
  <TextBox x:Name="txtPicks" Margin="15,78,15,0" VerticalAlignment="Top" Height="63" Text="" TextWrapping="Wrap" Background="#FFB4C397" FontFamily="Segoe UI" FontSize="11" FontWeight="Normal"/>
     <Path x:Name="pBottom" Margin="15,0,15,33.5" VerticalAlignment="Bottom" Height="0.5" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M19,32 L469,33" d:LayoutOverrides="VerticalAlignment"/>
  <TextBlock x:Name="tbFooter" Margin="15,150,15,0" VerticalAlignment="Top" Height="21" Text="copyright 2007. fantasy league manager" TextWrapping="Wrap" FontSize="11" FontWeight="Normal" FontFamily="Segoe UI"/>
 </Grid>
</Window>

XAML Namespaces

XAML documents created by using Microsoft tools will typically contain two namespace declarations. The first namespace declaration, the default namespace, xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation", is a direct reference to the WPF framework. The second namespace declaration, generally identified by the "x" prefix, xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml", is a reference to the XAML standard. XAML may be implemented by many technologies as a mean of defining application objects and properties. The second namespace declaration should exist in all XAML documents. However, the first namespace declaration, referencing WPF, may differ depending upon the technology that is utilizing XAML.

Events

XAML documents, as implemented by Microsoft technologies, are built around the same basic architecture as ASP.NET documents (Web forms, Web services, Web user controls, etc). XAML documents have associated code behind files. The XAML document is a text-based document that contains the XAML markup. A code behind file is an associated file that contains a class, properties, methods, etc in a particular .NET-compliant programming language and is used to handle events initiated by objects declared in the XAML markup. Code behind files are generally compiled into a .NET assembly and are associated with the XAML markup file through the x:Class attribute in the document element of the XAML markup file.

In the sample XAML above, the x:Class attribute identifies the Window1 class residing in the MyFantasyPicks namespace as the class that will handle events initiated by objects in the Window1 XAML file.

Routed Events

XAML elements correlate to .NET Framework objects. .NET Framework objects are fully object oriented. One characteristic of objects is that they define behavior. Behavior is generally defined through function members. The most common type of function member is a method. Methods perform functionality through programming language code through constructs such as functions and subroutines. A method can be called directly by another piece of code of can be identified as functionality to be performed in response to a user-initiated event. The most common user-initiated event in a graphical user interface (GUI) is a click event carried out by the user clicking on UI elements with the mouse.

Any XAML element that correlates to a .NET Framework object that contains a particular event can directly assign a handler to handle that event. For instance, a XAML Button element correlates to a .NET Framework Button object. The .NET Framework Button object contains an OnClick event. As such, the XAML Button element can assign an event handler to handle the Click event as shown in the Button element declaration below.

<Button
 Click="btnDisplayPicks_Click" 
 HorizontalAlignment="Left"
 Margin="15,41,0,0"
 VerticalAlignment="Top"
 Width="189"
 Height="23"
 Content="Display My Picks"
 x:Name="btnDisplayPicks" />

The associated event handler, btnDisplayPicks_Click, resides in the code behind file. In this example, the code behind is written by using C#. The event handler opens the XML file and displays the stored picks as shown in the code listing below.

Code Sample: WhatsNewNETFramework35/Demos/MyFantasyPicks/MyFantasyPicks/Window1.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace MyFantasyPicks
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// This method opens the XML file and displays the stored picks.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDisplayPicks_Click(object sender, RoutedEventArgs e)
        {

            // Create an XMLDocument object.
            XmlDocument xmlDoc = new XmlDocument();

            // Load the XML file.
            xmlDoc.Load(@"FantasyPick.xml");

            // We should have error handling
            // and more elaborate code in here
            // but this works for an example.

            // Reference the first pick element.
            XmlAttributeCollection pickElementAttributes = xmlDoc.DocumentElement.FirstChild.Attributes;
            XmlNodeList pickElementChildren = xmlDoc.DocumentElement.FirstChild.ChildNodes;

            // Display my picks.
            txtPicks.Text = "My fantasy picks for week number " + pickElementAttributes[0].Value + " are:\r\n";

            // Iterate through the picks.
            for (int i = 0; i < pickElementChildren.Count; i++)
            {

                txtPicks.Text +=
                    pickElementChildren[i].Attributes[0].Value +
                    " playing " +
                    pickElementChildren[i].Attributes[1].Value +
                    "\r\n";
            }

            // Clean up.
            pickElementChildren = null;
            pickElementAttributes = null;
            xmlDoc = null;
        }
    }
}

XAML is an XML grammar and, as such, it is built in a hierarchy. Most objects that contain events are nested inside of a containing object when represented in XAML.

One classic user interface design practice declared a central event handler at the container object level that would handle events for all contained child objects. This design practice required the container object to also implement the event handled. For example, a centralized click event handler could be created at a window level. Due to the bubbling up behavior of events, the click events for all contained child controls would then be handled at the window level. This practice was possible in classic Windows development because the Window object implemented a click event handler.

Controls and objects in XAML have been streamlined and optimized so that container objects contain very few event handlers. However, just about any object represented by XAML may fire an event contained by another object. In particular, a container object can easily fire events of contained objects even if the container object does not directly implement the event. This behavior is possible through XAML routed events.

A routed event is an event call that can be routed through an object separate from the object that contains the event. When a container object declares a routed event for child contained objects, such as a StackPanel that handles Click events for child contained Button objects, the declaration is made at the container object level and the type of object for which the event is being handled qualifies the event name. In the example below, the StackPanel contains a Button. The StackPanel does not implement a Click event, however the StackPanel handles the click event for all contained Button objects by declaring the Button.Click as a routed event.

    <StackPanel Button.Click="Button_ClickHandler" >
  <Button HorizontalAlignment="Left" Margin="15,41,0,0" VerticalAlignment="Top"
    Width="189" Height="23" Content="Display My Picks" x:Name="btnDisplayPicks">
   <Button.Background>
    <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
     <GradientStop Color="#FFF3F3F3" Offset="0.005"/>
     <GradientStop Color="#FFEBEBEB" Offset="0.44"/>
     <GradientStop Color="#FFDDDDDD" Offset="0.531"/>
     <GradientStop Color="#FFDAB925" Offset="0.904"/>
    </LinearGradientBrush>
   </Button.Background>
  </Button>
</StackPanel>

The full XAML associated with the event handler shown above is shown in the code listing below.

Code Sample: WhatsNewNETFramework35/Demos/MyFantasyPicks/MyFantasyPicks/Window1.xaml

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MyFantasyPicks.Window1"
    Title="Fantasy League Manager 2008" Height="216" Width="529" x:Name="DisplayMyPicks" xmlns:d="http://schemas.microsoft.com/expression/blend/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
 <Window.Resources>
  <Color x:Key="myGreenColor">#FFB4C397</Color>
  <Color x:Key="myDarkGreenColor">#FF495B24</Color>
 </Window.Resources>
 <Window.Background>
  <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5" SpreadMethod="Pad">
   <GradientStop Color="{DynamicResource myDarkGreenColor}" Offset="0"/>
   <GradientStop Color="{DynamicResource myGreenColor}" Offset="0.431"/>
  </LinearGradientBrush>
 </Window.Background>
    <Grid>
  <TextBlock Margin="10,10,0,0" VerticalAlignment="Top" FontFamily="Segoe UI" Text="Welcome to the Fantasy League Manager" />
  <Path Margin="15,30,15,0" VerticalAlignment="Top" Height="0.5" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M19,32 L469,33" />
  <Button HorizontalAlignment="Left" Margin="15,41,0,0" VerticalAlignment="Top" Width="189" Height="23" Content="Display My Picks" x:Name="btnDisplayPicks" Click="btnDisplayPicks_Click">
   <Button.Background>
    <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
     <GradientStop Color="#FFF3F3F3" Offset="0.005"/>
     <GradientStop Color="#FFEBEBEB" Offset="0.44"/>
     <GradientStop Color="#FFDDDDDD" Offset="0.531"/>
     <GradientStop Color="#FFDAB925" Offset="0.904"/>
    </LinearGradientBrush>
   </Button.Background>
  </Button>
  <Path x:Name="pMiddle" Margin="15,73.5,15,0" VerticalAlignment="Top" Height="0.5" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M19,32 L469,33" Visibility="Visible" />
  <TextBox x:Name="txtPicks" Margin="15,78,15,0" VerticalAlignment="Top" Height="63" Text="" TextWrapping="Wrap" Background="#FFB4C397" FontFamily="Segoe UI" FontSize="11" FontWeight="Normal"/>
     <Path x:Name="pBottom" Margin="15,0,15,33.5" VerticalAlignment="Bottom" Height="0.5" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M19,32 L469,33" d:LayoutOverrides="VerticalAlignment"/>
  <TextBlock x:Name="tbFooter" Margin="15,150,15,0" VerticalAlignment="Top" Height="21" Text="copyright 2007. fantasy league manager" TextWrapping="Wrap" FontSize="11" FontWeight="Normal" FontFamily="Segoe UI"/>
 </Grid>
</Window>

The WPF form rendered from the XAML shown above and post the button being clicked and the event handler being executed is shown in the figure below.

Complete coverage of the Extensible Application Markup Language (XAML) is beyond the scope of this course.

XAML Tools

The XAML created above was created by using Microsoft development tools. XAML was created by Microsoft, however, due to the popularity of XAML, there are many third party XAML editors and utilities now being offered. The primary XAML tools from Microsoft are described below.

Visual Studio 2008

Visual Studio is Microsoft's premiere integrate software development environment. Visual Studio now hosts management utilities as well as development tools. The figure below shows Visual Studio 2008.

Expression Blend

Microsoft has introduced a whole new line of cutting edge tools designed for use by designers, Microsoft Expression Suite. Microsoft Expression Suite includes a tool, Microsoft Expression Blend, that is a XAML development tool targeting designers. In a brilliant move, Microsoft designed the Expression suite of tools to integrate nicely with Visual Studio. This comes close to completing the cycle of tools needed to work with the .NET Framework technologies and architectures. ASP.NET, for instance, was redesigned with code behind files containing compilable code so that developers could work on programming language code and components while designers could work on the markup and user interface.

XAMLPad

XAMLPad is a component included with the .NET Framework 3.0 software development kit which is available for download at http://www.microsoft.com/downloads/details.aspx?familyid=7614FE22-8A64-4DFB-AA0C-DB53035F40A0&displaylang=en. XAMLPad is a very simple XAML editor that quickly displays the results of XAML markup. The figure below shows some XAML in XAMLPad.

Windows Presentation Foundation (WPF)

The Windows Presentation Foundation (WPF), as its name implies, is the new Microsoft standard for presenting software to users. WPF is a consolidation of previously used presentation technologies including Windows Forms, GDI+, Windows Media Player, and DirectX. WPF provides the following benefits:

  • A common platform and environment for developing cutting edge user interfaces that combines all previously used Microsoft presentation technologies. WPF is capable of interacting with all of the previous technologies to aid in progressive application upgrades. All presentation development going forward, utilizing Microsoft technologies, should occur using WPF or the subset of WPF, Silverlight.
  • The ability for developers and designers to work together, simultaneously on projects. This was described in the previous section on tools as well. Due to the proper division of markup from code and the correct utilization of tools, a utopia-esque environment between developers and designers is within reach.
  • A common and standardized technology that can be utilized for both Windows and Web applications. WPF offers the ability to create standalone WPF applications which are analogous to Windows Forms applications and the ability to create XAML Browser Applications (XBAPs) which are the same WPF applications that are hosted in a Web browser and are subject to more stringent security settings.

The technologies included in the WPF standard are:

  • A complete application framework integrated into the .NET Framework 3.0
  • Layout control and user interface controls
  • Complete support for styles and templates
  • Advanced text formatting and display capabilities (through ClearType) that greatly improve text readability
  • Support for both fixed layout and flow layout documents and the introduction of a brand new fixed document format standard known as the XML Paper Specification (XPS) document standard
  • Easy display and integration of all image formats, video, audio, 2D graphics, 3D graphics as well as graphics transformations and effects and animations
  • Advanced data binding capabilities

The figure below illustrates the WPF architecture.

We'll forgo an example of WPF as we illustrated WPF above in our coverage of XAML. However, for more in depth coverage of WPF, visit the Windows client Web site located at http://windowsclient.net/Default. The figure below illustrates the WindowsClient.NET Web site.

Windows Communication Foundation (WCF)

From its inception, the .NET Framework has included functionality for creating distributed applications. A distributed application includes components that reside in different locations that come together to form an integrated application. From the get-go, the .NET Framework has included advanced support for creating, hosting, and consuming Web services. A Web service is a component that is created in accordance with the Service Oriented Architecture (SOA). SOA, and Web services, are an industry standard that are utilized by far more companies than Microsoft, however, as with most technologies used on the Web, some primary vendors introduce the concept and a consortium manages it as a standard. Microsoft was one of the primary vendors that introduced and developed Web services and continues to be a guiding force in developing related technologies.

In a nutshell, a Web service is a component, similar to a procedure file or an object with methods, that is callable over the Web by using Web protocols. Just as a procedure file or object with methods is called from code to provide a service or benefit to the calling code, a Web service functions in the same way. Code with access to the Web service calls the Web service in order to provide some type of additional functionality. Web services use HTTP as a communication protocol, by default, and an XML grammar called the Simple Object Access Protocol (SOAP), to transport data, again, by default. Just as any client with a Web browser can view a Web page, due to the use of the Web standards, a single Web service can be called by any programming language that is capable of working with open Web standards. Additionally, due to the use of HTTP as a communication protocol, Web services are generally accessible through firewalls.

The use of SOAP and HTTP make a Web service broadly available, however, by making a Web service available as they are, the communication mechanisms are not optimized for any particular environment. As such, if you had control of both the client and the server in a distributed environment, you can utilize more efficient means of communicating between them. The .NET Framework offered .NET remoting as a solution to creating a distributed application where you controlled both the client and the server. .NET remoting utilize more efficient protocols and transport mechanisms but was also more complex to implement.

The .NET Framework also included functionality for working with other distributed technologies.

Web Service Technologies

As with most popular Web technologies, Web services include many additional technologies that enhance and extend the basic functionality of a Web service. Furthermore, the technologies surrounding Web services have been evolving at an astronomical rate and its been tough for development environments to keep up with the supported technologies. Supporting technologies include enhancements to security, the ability to manage messages being sent to and from a Web service and ensure reliability, and the functionality for working with messages in transactions.

Windows Communication Foundation (WCF)

As a new, consolidated solution to creating distributed systems, Microsoft introduced Windows Communication Foundation (WCF) with the .NET Framework version 3.0. WCF encompasses all preceding distributed application development technologies offered by Microsoft and is capable of continuing to intercommunicate with those technologies for backward compatibility. WCF simplifies distribute application development while being extensible in order to keep up with and incorporate the latest technologies and advances. The following figure shows the WCF architecture.

WCF provides:

  • An advanced system for configuring endpoints in a distributed environment
  • The ability to configure communication protocols to be used between endpoints
  • A reliable system for sending and receiving messages between endpoints
  • Messages may be sent asynchronously, secured, and managed through transactions
  • Functionality for serializing and deserializing primitive, complex, and binary data

The WCF architecture, as illustrated in the figure above:

  • Includes contracts for describing all communication terms, protocols, and the overarching agreement and description between endpoints
  • Provides a service runtime that includes classes and functionality in the .NET Framework to initiate the communication process
  • Provides a messaging system that includes the functionality that carries out the packaging and handling of messages. Messages are processed through channels. There are two types of channels: transport channels and protocol channels. A transport channel reads and writes messages to the network once the messages are packaged. A protocol channel implements the various WS protocols when messages are being read and written and packaged
  • Provides activation and hosting of services. A WCF service must be activated or hosted to be of any use. Services are created by using .NET programming languages and compiled into .NET assemblies. The methods available for hosting or activating a service correlate to the two types of assemblies created by using .NET: out-of-process (.exe) and in-process (.dll). An out-of-process assembly must be called directly and resides in its own memory space. This type of service assembly is said to be activated. An in-process assembly must be loaded into the memory space of a host application such as Internet Information Services (IIS). This type of service assembly is said to be hosted.

WCF is an elaborate system for creating distributed systems by using the .NET Framework 3.0.

WCF Example

In this module, we will illustrate creating a hosted WCF service by using Visual Studio 2008. If you are using a different development environment or editor, the steps involved will differ. When using Visual Studio 2008, if you choose to create a Web application WCF service, the service will be hosted by using IIS. If you choose to create a WCF application project type, it will be a self-activated service.

The examples used in this course, thus far, have been utilizing the same, or similar, functionality as other examples as to illustrate how to implement the same functionality across different technologies. In this example, we will get our fantasy picks from a WCF hosted service and display them on a WPF form.

The Service

The first step in the process of illustrating WCF is to create a WCF service. As stated in the introduction above, when using Visual Studio 2008, a WCF service can be created in one of two ways. If you want to create a WCF service that is hosted by IIS and fulfills the same role as a standard Web service, select the New Web Site option from the File menu. When prompted with the New Web Site dialog, select the option to create a WCF service as shown in the figure below.

If you choose to create a self-activating WCF service, select the New Project option from the File menu. When prompted with the New Project dialog, under the language of your choice, select the WCF Service Library option as shown in the following figure.

Once the option is selected for creating a WCF service, the first step in the process is to configure the interface. The interface for the service determine the data members and function members that the service will use. The name of an interface generally started with an uppercase "I" as a standard to signify that it is an interface when referencing it in code.

The code above is fairly straightforward as long as you understand .NET programming and object oriented concepts. The items in this code listing to point out are the reference to the System.ServiceModel namespace. The System.ServiceModel namespace includes the WCF service functionality. Next, notice the ServiceContract attribute on the interface declaration. This identifies the interface as a service contract. In standard Web services, a WSDL document is used to identify the service contract for a Web service. In WCF, an interface is used. Finally, notice the OperationContract attribute on the GetPicks method. In standard ASP.NET Web services, any method that should be exposed over the Web is marked up by using the WebMethod attribute. In WCF, any method that should be exposed over the Web is marked up by using the OperationContract attribute.

The next step of the process in creating a WCF service is to create the service class. The service class must implement the service interface. The service class used in this example is shown in the code listing below.

Code Sample: WhatsNewNETFramework35/Demos/FantasyLeagueService/App_Code/FantasyLeagueService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Xml;
using System.Web.Hosting;

public class FantasyLeagueService : IFantasyLeagueService
{
    public string GetPicks()
    {

        // Declare the return string.
        string returnValue = "";

        // Create an XMLDocument object.
        XmlDocument xmlDoc = new XmlDocument();

        // Load the XML file.
        xmlDoc.Load(HostingEnvironment.ApplicationPhysicalPath + @"App_Data\FantasyPick.xml");

        // We should have error handling
        // and more elaborate code in here
        // but this works for an example.

        // Reference the first pick element.
        XmlAttributeCollection pickElementAttributes = xmlDoc.DocumentElement.FirstChild.Attributes;
        XmlNodeList pickElementChildren = xmlDoc.DocumentElement.FirstChild.ChildNodes;

        // Display my picks.
        returnValue = "My fantasy picks for week number " + pickElementAttributes[0].Value + " are:\r\n";

        // Iterate through the picks.
        for (int i = 0; i < pickElementChildren.Count; i++)
        {

            returnValue +=
                pickElementChildren[i].Attributes[0].Value +
                " playing " +
                pickElementChildren[i].Attributes[1].Value +
                "\r\n";
        }

        // Clean up.
        pickElementChildren = null;
        pickElementAttributes = null;
        xmlDoc = null;

        return returnValue;
    }
}

In the code listing above, again, it should be completely straightforward if you understand .NET programming and object oriented concepts. The only items to point out are the reference to the System.ServiceModel namespace and that the service class implements the IFantasyLeagueService interface.

If you run the WCF service application from within Visual Studio 2008, you will be given a page showing you that the service is running successfully. However, unlike classic ASP.NET Web services, you cannot test the WCF service from this page. The Visual Studio 2008 WCF service output page is shown in the figure below.

The Client

Once a service is in place, the service is ready to be consumed by a client application. Any application type created by using Visual Studio 2008 should be able to serve as a WCF client. Once a client application is open in WCF, right-click the project in the Solution Explorer and select Add Service Reference. The Add Service Reference dialog should appear as shown in the following figure.

The code necessary in our WPF client code behind is now surprisingly short. With the Service Reference in place, the click event handler in the Window1.xaml.cs code behind file has now been consolidated to that shown in the following snippet.

Code Sample: WhatsNewNETFramework35/Demos/FantasyLeagueClient/MyFantasyPicks/Window1.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace MyFantasyPicks
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// This method opens the XML file and displays the stored picks.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDisplayPicks_Click(object sender, RoutedEventArgs e)
        {

            // Go get the picks from the fantasy league service.
            // Call the method synchronously for now.
            FantasyLeagueService.FantasyLeagueServiceClient fantasyManager = new FantasyLeagueService.FantasyLeagueServiceClient();
            txtPicks.Text = fantasyManager.GetPicks();
        }
    }
}

Windows Workflow Foundation (WF)

Windows Workflow Foundation (WF) is used to document workflows, both system-based and human-based as well as a combination of both. A workflow is a real world set of activities that can be documented in their order of precedence. WF is a layer on top of the .NET Framework version 3.0 and is created and maintained by using .NET programming languages. Visual Studio 2008 provides a designer for WF and all future Microsoft products that implement a workflow of some type (this includes most products) will utilize and benefit from WF. Workflows are documented graphically by using the WF designer and WF then mostly automates the creation of the underlying objects, code, and services.

In many scenarios, a workflow will represent a process that may require human interaction at one or more points along the process in order to continue the process. Human interaction is an unknown activity. For example, in the fantasy league manager, when users are drafting players to be on their fantasy teams, the workflow has a process to carry out in order to place a player on a user's fantasy team. However, the workflow cannot carry out this process without a user making a player selection (drafting a player). A fantasy draft typically takes a few hours to an entire day, depending upon the intensity of the users involved. As such, it will take the workflow an unknown amount of time before it can proceed due to waiting upon human interaction. If the fantasy league manager were servicing many teams, each team should have a separate workflow instantiated in memory. If a workflow is waiting in limbo for hours on users to make draft decisions before moving on, it would be beneficial to system performance if a workflow could go into a sleep state and not consume memory while waiting.

WF includes the ability to put a workflow to sleep for an indefinite amount of time. When a workflow is put to sleep, it is serialized to a data store, where it can persist indefinitely and even survive system reboots. When a workflow is sleeping, WF will listen for requests for the workflow. When a request is initiated, the workflow is awaken and reinstantiated to resume right where it left off when it was put to sleep.

The figure below illustrates the WF architecture.

WF provides:

  • Runtime engine and services for managing workflows. Workflow process steps may be represented by objects and services as well
  • Advanced design tools and modeler through Visual Studio 2008
  • Indefinite persistence of workflows
  • Workflow management through transactions, tracking, timing, and threading

The figure below shows the Visual Studio 2008 WF designer with a workflow for the Fantasy League Manager in process.

The code listing shown below correlates to the events that would be fired in conjunction with the workflow shown above.

Code Sample: WhatsNewNETFramework35/Demos/FantasyLeagueManagerWF/FantasyLeagueManagerWF/FantasyLeagueProcess.Designer.cs

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Reflection;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;

namespace FantasyLeagueManagerWF
{
 partial class FantasyLeagueProcess
 {
  #region Designer generated code
  
  /// <summary> 
  /// Required method for Designer support - do not modify 
  /// the contents of this method with the code editor.
  /// </summary>
        [System.Diagnostics.DebuggerNonUserCode]
  private void InitializeComponent()
  {
      this.CanModifyActivities = true;
      this.StatsNotification = new System.Workflow.Activities.CodeActivity();
      this.UpdateStats = new System.Workflow.Activities.WebServiceOutputActivity();
      this.CallUpdateStats = new System.Workflow.Activities.WebServiceInputActivity();
      this.SelectNewPlayer = new System.Workflow.Activities.CodeActivity();
      this.ReviewCurrentStats = new System.Workflow.Activities.CodeActivity();
      this.UserAuthentication = new System.Workflow.Activities.CodeActivity();
      // 
      // StatsNotification
      // 
      this.StatsNotification.Name = "StatsNotification";
      this.StatsNotification.ExecuteCode += new System.EventHandler(this.StatsNotification_ExecuteCode);
      // 
      // UpdateStats
      // 
      this.UpdateStats.InputActivityName = "CallUpdateStats";
      this.UpdateStats.Name = "UpdateStats";
      // 
      // CallUpdateStats
      // 
      this.CallUpdateStats.InterfaceType = typeof(FantasyLeagueManagerWF.FantasyLeagueService);
      this.CallUpdateStats.MethodName = "GetStats";
      this.CallUpdateStats.Name = "CallUpdateStats";
      this.CallUpdateStats.InputReceived += new System.EventHandler(this.UpdateStats_InputReceived);
      // 
      // SelectNewPlayer
      // 
      this.SelectNewPlayer.Name = "SelectNewPlayer";
      this.SelectNewPlayer.ExecuteCode += new System.EventHandler(this.SelectNewPlayer_ExecuteCode);
      // 
      // ReviewCurrentStats
      // 
      this.ReviewCurrentStats.Name = "ReviewCurrentStats";
      this.ReviewCurrentStats.ExecuteCode += new System.EventHandler(this.ReviewCurrentStats_ExecuteCode);
      // 
      // UserAuthentication
      // 
      this.UserAuthentication.Name = "UserAuthentication";
      this.UserAuthentication.ExecuteCode += new System.EventHandler(this.UserAuthentication_ExecuteCode);
      // 
      // FantasyLeagueProcess
      // 
      this.Activities.Add(this.UserAuthentication);
      this.Activities.Add(this.ReviewCurrentStats);
      this.Activities.Add(this.SelectNewPlayer);
      this.Activities.Add(this.CallUpdateStats);
      this.Activities.Add(this.UpdateStats);
      this.Activities.Add(this.StatsNotification);
      this.Name = "FantasyLeagueProcess";
      this.CanModifyActivities = false;

  }

  #endregion

        private CodeActivity ReviewCurrentStats;
        private CodeActivity SelectNewPlayer;
        private WebServiceInputActivity CallUpdateStats;
        private WebServiceOutputActivity UpdateStats;
        private CodeActivity StatsNotification;
        private CodeActivity UserAuthentication;
  }
}

Comprehensive coverage of WF is beyond the scope of this course.

Windows CardSpace

Windows CardSpace is Microsoft's new digital identity management system. CardSpace is client-side software that is included with the .NET Framework 3.0. CardSpace stores a user's digital identities and presents them to users in the form of visual cards as shown in the following figure.

CardSpace is used to identify users over the Web. Users can create their own identities and verify those identities through third party vendors. When a Web site needs to authenticate a user, it can make a request of CardSpace. At that time, CardSpace will display the user's identities to the user as well as information on the Web site making the request. The user can then select the identity to use for authentication at the Web site. CardSpace can then contact the third party vendor who issued the digital identity to the user to verify that the user identity is valid and, in turn, acquire a digitally signed XML token to send to the Web site for authenticating the user. The figure below illustrated the overall process of CardSpace authentication.

CardSpace is built on the latest Web Service (WS-) protocols and provides:

  • A unified, secure, private, and interoperable method for managing digital identities
  • Support for any digital identity system
  • User control of digital identities
  • Replacement of password-based Web login mechanisms
  • Improved user confidence in Web security and authentication

For a greater understanding of the design concepts that Microsoft had in mind when crafting CardSpace, read the Laws of Identity located at http://msdn2.microsoft.com/en-us/library/ms996456.aspx. CardSpace is being quickly adopted by vendors industry-wide, however, extensive coverage of CardSpace is beyond the scope of this course.

Language Integrated Query (LINQ)

The final major addition to the .NET Framework in version 3.5 is Language Integrated Query (LINQ). Most seasoned developers have mastered or are adequately familiar with the Structured Query Language (SQL). SQL is used to query relational database data. However, in many cases, SQL queries that pull data from a relational database schema are abstracted away from business logic and middle-tier code. Furthermore, data is generally represented at the business logic and code level through objects, arrays, and collections. Developers regularly have to search these constructs by using tailor-made loops.

Many programmers have long requested a language for querying data stored in programming constructs and object oriented mechanisms. SQL is a stable and well-entrenched industry standard. It would be an insurmountable task to attempt to extend SQL so that it could be used to query programming constructs. However, Microsoft was determined to make things easier for programmers by creating a standard for querying data stored in coding constructs. The result of their efforts was a new query language that targets data stored in objects and collections, Language Integrated Query (LINQ). LINQ was also extended to be able to query relational data stored in databases, XML data, and other data sources. However, data queried by using LINQ must be stored as objects. If data is queried from a relational data source using LINQ, it must first be represented using an object model.

LINQ is covered in more detail in a module later in this course.

LAB: Training Tool Using WPF and WCF

In this exercise, you will create a version of the online training tool by using:

  • Visual Studio 2008
  • Optionally, Expression Blend
  • XAML
  • WPF
  • WCF

This module has introduced new technologies available as of the .NET Framework version 3.0 and version 3.5. We'll continue in this lab with the online training tool theme but will recreate the training tool from scratch using WPF and WCF. We haven't covered data access yet at this point so we'll stick with pulling training data from the standalone XML file.

What's New in the .NET Framework 3.5 Conclusion

In this lesson of the Silverlight tutorial, you

  • Explored the Extensible Application Markup Language (XAML)
  • Created an alternate user interface for the training portal by using WPF
  • Learned about how WCF has replaced and improved earlier .NET Framework distributed technologies
  • Reviewed documenting a simple business process by using WF
  • Learned about storing user credentials and digital information using Windows CardSpace
  • Briefly familiarized yourself with Language Integrated Query (LINQ)
To continue to learn Silverlight go to the top of this page and click on the next lesson in this Silverlight Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.