90
Object Innovations Course 4020 Student Guide Revision 1.0 Visual Studio 2008 and .NET 3.5 Using Visual Basic

4020 Contents 10€¦ · Visual Studio 2008 and .NET 3.5 Using Visual Basic Rev. 1.0 Student Guide Information in this document is subject to change without notice. Companies, names

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Object Innovations Course 4020

Student Guide Revision 1.0

Visual Studio 2008 and .NET 3.5 Using Visual Basic

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC ii All Rights Reserved

Visual Studio 2008 and .NET 3.5 Using Visual Basic Rev. 1.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Authors: Robert J. Oberg and Julian Templeman Special Thanks: Ernani Cecon, Jr. Copyright ©2008 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Published in the United States of America.

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 Visual Studio 2008 Chapter 2 New Features in Visual Basic 2008 Chapter 3 Language-Integrated Query (LINQ) Chapter 4 Windows Communication Foundation (WCF) Chapter 5 Windows Workflow Foundation (WF) Chapter 6 Windows Presentation Foundation (WPF) Appendix A Learning Resources

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• Install the course software by running the self-extractor Install_NewVb3_10.exe.

• The course software installs to the root directory c:\OIC\NewVb3.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02 and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The Demos directory is provided for performing in-class demonstrations led by the instructor.

• Data files install to the directory c:\OIC\Data.

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1: Visual Studio 2008............................................................................................. 1 Overview of .NET Framework 3.0 ..................................................................................... 3 .NET 3.0 Block Diagram .................................................................................................... 4 .NET Framework 3.5 .......................................................................................................... 5 Visual Studio 2008.............................................................................................................. 6 Visual Studio 2008 Versions .............................................................................................. 7 Visual Studio 2008 Team System....................................................................................... 8 Plan for this Course............................................................................................................. 9 A Tour of Visual Studio 2008........................................................................................... 10 New WPF Project Templates............................................................................................ 11 Creating a New WPF Application .................................................................................... 12 XAML............................................................................................................................... 13 Navigating XAML and Design View ............................................................................... 14 Sample Application........................................................................................................... 15 Editing XAML.................................................................................................................. 16 Sizing the Window............................................................................................................ 19 Adding an Event Handler ................................................................................................. 21 Solutions with Multiple Projects....................................................................................... 23 Class Library Project Demo.............................................................................................. 24 Referencing the Class Library .......................................................................................... 25 Referencing the Class Library .......................................................................................... 26 Project Dependencies........................................................................................................ 27 Build Order ....................................................................................................................... 28 Using the Class Library .................................................................................................... 29 New Web Project Templates ............................................................................................ 30 Reporting Project Templates ............................................................................................ 31 WCF Project Templates.................................................................................................... 32 Workflow Project Templates ............................................................................................ 33 Workflow Designer........................................................................................................... 34 Object/Relational Designer............................................................................................... 35 Lab 1 ................................................................................................................................. 36 Summary ........................................................................................................................... 37

Chapter 2: New Features in Visual Basic 2008 ................................................................ 43 Local Type Inference ........................................................................................................ 45 Local Type Inference – Example...................................................................................... 46 Object Initializers.............................................................................................................. 47 Array Initializers ............................................................................................................... 48 Anonymous Types ............................................................................................................ 49 Partial Methods ................................................................................................................. 50 Partial Method Definition ................................................................................................. 51

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC vi All Rights Reserved

Partial Method Implementation ........................................................................................ 52 Main Program ................................................................................................................... 53 Running the Example........................................................................................................ 54 Extension Methods ........................................................................................................... 55 Extension Methods Example ............................................................................................ 56 Lambda Expressions ......................................................................................................... 57 Named Method.................................................................................................................. 58 Lambda Expression Example ........................................................................................... 59 Language-Integrated Query (LINQ)................................................................................. 60 LINQ Example.................................................................................................................. 61 Using IEnumerable<T> .................................................................................................... 62 Lab 2 ................................................................................................................................. 63 Summary ........................................................................................................................... 64

Chapter 3: Language-Integrated Query (LINQ)............................................................. 71 What Is LINQ?.................................................................................................................. 73 Bridging Objects and Data................................................................................................ 74 LINQ Demo ...................................................................................................................... 75 Object Relational Designer ............................................................................................... 77 IntelliSense........................................................................................................................ 79 Basic LINQ Query Operators ........................................................................................... 80 Obtaining a Data Source ................................................................................................... 81 Basic Query Example ....................................................................................................... 82 Commands ........................................................................................................................ 84 Projection .......................................................................................................................... 85 Filtering............................................................................................................................. 86 Ordering ............................................................................................................................ 87 Grouping ........................................................................................................................... 88 Aggregation ...................................................................................................................... 90 Obtaining Lists and Arrays ............................................................................................... 91 Deferred Execution ........................................................................................................... 92 Inserts................................................................................................................................ 93 Deletes and Updates.......................................................................................................... 94 LINQ Data Stores ............................................................................................................. 95 LINQ to Objects................................................................................................................ 96 LINQ to ADO.NET .......................................................................................................... 97 Creating the Object Model................................................................................................ 98 Demo: Using SQLMetal ................................................................................................... 99 DataContext .................................................................................................................... 100 Performing Inserts via LINQ to SQL.............................................................................. 101 Performing Deletes via LINQ to SQL ............................................................................ 102 Performing Updates via LINQ to SQL ........................................................................... 103 Lab 3A ............................................................................................................................ 104 LINQ to DataSet ............................................................................................................. 105 LINQ to DataSet Demo .................................................................................................. 106 Using the Typed DataSet ................................................................................................ 108

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC vii All Rights Reserved

Full-Blown LINQ to DataSet Example........................................................................... 109 LINQ to XML................................................................................................................. 110 Creating an XML Document .......................................................................................... 111 Querying and Modifying ................................................................................................ 113 Querying and Modifying Example ................................................................................. 114 Removing and Updating ................................................................................................. 115 Lab 3B............................................................................................................................. 116 Summary ......................................................................................................................... 117

Chapter 4: Windows Communication Foundation (WCF)........................................... 127 What Is WCF?................................................................................................................. 129 WCF Services ................................................................................................................. 130 Service Orientation ......................................................................................................... 132 WCF and Web Services .................................................................................................. 133 WCF = ABC ................................................................................................................... 134 Address, Binding, Contract............................................................................................. 135 Example – Hello WCF.................................................................................................... 136 Hosting Services ............................................................................................................. 137 Demo – Hello WCF ........................................................................................................ 138 Testing the Service.......................................................................................................... 140 Implementing the Host.................................................................................................... 142 A Client Program ............................................................................................................ 145 Data Contracts................................................................................................................. 147 Data Contract Example ................................................................................................... 148 Testing the Service Library............................................................................................. 150 Host ................................................................................................................................. 151 Client............................................................................................................................... 152 Adding a Service Reference ........................................................................................... 153 WCF Architecture........................................................................................................... 156 WCF Architecture........................................................................................................... 157 Addresses ........................................................................................................................ 158 Transports ....................................................................................................................... 159 Bindings .......................................................................................................................... 160 Message Exchange Patterns (MEPs) .............................................................................. 162 Security ........................................................................................................................... 163 Lab 4 ............................................................................................................................... 164 Summary ......................................................................................................................... 165

Chapter 5: Windows Communication Workflow (WF)................................................ 175 What Is Workflow?......................................................................................................... 177 Windows Workflow Foundation..................................................................................... 178 Workflows....................................................................................................................... 179 Activities ......................................................................................................................... 180 Standard Activities.......................................................................................................... 181 Runtime Services ............................................................................................................ 182 Workflow Business Scenario.......................................................................................... 183

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC viii All Rights Reserved

High Level Workflow..................................................................................................... 184 Details of While Activity ................................................................................................ 185 Orders Folder .................................................................................................................. 186 Manual Step in the Verification...................................................................................... 187 Main Console Display .................................................................................................... 188 Issues Folder ................................................................................................................... 189 Invoices Folder ............................................................................................................... 190 Learning Microsoft’s WF ............................................................................................... 191 Hello Workflow .............................................................................................................. 192 Hello Workflow Demo ................................................................................................... 193 IfElseActivity.................................................................................................................. 198 Implementing a Branch................................................................................................... 199 While Activity................................................................................................................. 201 High-Level Workflow..................................................................................................... 202 Sequence Activity ........................................................................................................... 203 Condition in While Activity ........................................................................................... 204 Parallel Activity .............................................................................................................. 205 Parallel Activity Workflow Diagram.............................................................................. 206 Lab 5 ............................................................................................................................... 207 Summary ......................................................................................................................... 208

Chapter 6: Windows Presentation Foundation (WPF) ................................................. 213 WPF and .NET Framework 3.5 ...................................................................................... 215 Core Types and Infrastructures....................................................................................... 216 XAML............................................................................................................................. 217 Controls........................................................................................................................... 218 Data Binding ................................................................................................................... 219 Appearance ..................................................................................................................... 220 Layout and Panels ........................................................................................................... 221 Graphics .......................................................................................................................... 222 Media .............................................................................................................................. 223 Documents and Printing.................................................................................................. 224 Application and Window ................................................................................................ 225 FirstWpf Example Program ............................................................................................ 226 Using a Button ................................................................................................................ 227 Device-Independent Pixels ............................................................................................. 228 Class Hierarchy............................................................................................................... 229 Content Property ............................................................................................................. 230 Handling an Event .......................................................................................................... 231 What Is XAML? ............................................................................................................. 232 Default Namespace ......................................................................................................... 233 Elements and Attributes.................................................................................................. 234 XAML in Visual Studio 2008......................................................................................... 235 Demo: One Button via XAML ....................................................................................... 236 Panels .............................................................................................................................. 241 Layout in WPF................................................................................................................ 242

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC ix All Rights Reserved

Controlling Size .............................................................................................................. 243 Margin and Padding........................................................................................................ 244 Thickness Structure......................................................................................................... 245 Children of Panels........................................................................................................... 246 Example – TwoControls ................................................................................................. 247 TwoControls – XAML.................................................................................................... 248 Automatic Sizing ............................................................................................................ 249 TwoControls – Code ....................................................................................................... 250 Orientation ...................................................................................................................... 251 Items Controls................................................................................................................. 252 Selector Controls............................................................................................................. 253 Using a ListBox .............................................................................................................. 254 Storing Objects in List Controls ..................................................................................... 255 Grid ................................................................................................................................. 256 Customizing a Grid ......................................................................................................... 257 GroupBox and RadioButton Controls............................................................................. 259 BankGrid Example.......................................................................................................... 260 Lab 6A ............................................................................................................................ 261 Menus in WPF ................................................................................................................ 262 Menu Controls ................................................................................................................ 263 Menu and Dialogs Example............................................................................................ 264 File Menu........................................................................................................................ 265 The Menu Using XAML................................................................................................. 266 Handling the Click Event................................................................................................ 267 Closing a Form................................................................................................................ 268 Other Controls on Menus................................................................................................ 269 Dialog Boxes in WPF ..................................................................................................... 270 MessageBox.................................................................................................................... 271 MessageBox Show Method ............................................................................................ 272 Common Dialog Boxes................................................................................................... 273 FileOpen Example .......................................................................................................... 274 FileOpen Example Code ................................................................................................. 275 Custom Dialogs............................................................................................................... 276 Modal Dialogs................................................................................................................. 277 Modal Dialog Example ................................................................................................... 278 XAML for New Item Dialog .......................................................................................... 279 Code for New Item Dialog.............................................................................................. 280 Bringing up the Dialog ................................................................................................... 281 Lab 6B............................................................................................................................. 282 Summary ......................................................................................................................... 283

Appendix A: Learning Resources.................................................................................... 299

Rev. 1.0 Copyright ©2008 Object Innovations Enterprises, LLC x All Rights Reserved

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Visual Studio 2008

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 2 All Rights Reserved

Visual Studio 2008

Objectives

After completing this unit you will be able to:

• Outline the features of .NET 3.0.

• Describe the additional capabilities of .NET 3.5.

• Explain the role of Visual Studio 2008 in providing tooling support for .NET 3.5 applications.

• List the versions of Visual Studio 2008 and understand which version is appropriate for specific tasks.

• Describe the new project templates and designers in Visual Studio 2008.

• Implement simple WPF programs by editing XAML markup and using the WPF Designer.

• Create multiple-project solutions, which are used extensively with .NET 3.5 applications.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 3 All Rights Reserved

Overview of .NET Framework 3.0

• The Microsoft .NET Framework 3.0 (formerly called WinFX) introduced a new managed code programming model for Windows.

• NET Framework 3.0 includes .NET Framework 2.0 along with API’s for four new technologies.

− Windows Presentation Foundation (WPF, formerly “Avalon”) is a unified programming model for user interfaces, graphics, documents and media.

− Windows Communication Foundation (WCF, formerly “Indigo”) is a unified programming model to build service-oriented architecture (SOA) applications on the Windows platform.

− Windows Workflow Foundation (WF) is a programming model, engine and tools for building workflow applications on the Windows platform.

− Windows CardSpace (WCS, formerly “InfoCard”) is a new set of Windows technologies that provides a standards-based solution for managing digital identities.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 4 All Rights Reserved

.NET 3.0 Block Diagram

• .NET Framework 3.0 layers on top of .NET Framework 2.0 and has the components shown in the diagram.

WindowsPresentationFoundation

(WPF)

WindowsCommunication

Foundation(WCF)

WindowsWorkflow

Foundation(WF)

WindowsCardSpace

(WCS)

.NET Framework 2.0

WindowsForms ASP.NET ADO.NET

Base Class Libraries

Common Language Runtime

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 5 All Rights Reserved

.NET Framework 3.5

• The .NET Framework 3.5 adds a number of important features beyond those of .NET 3.0.

− Perhaps the most important is integration with the tooling support provided by Visual Studio 2008, which we’ll discuss later in the chapter.

• Language Integrated Query (LINQ) extends query capabilities to the syntax of the C# and Visual Basic programming languages.

− The technology can be extended to almost any data store, and out of the box includes support for objects, the file system, SQL Server and XML.

• Enhancements to the Visual Basic programming language, largely to support LINQ.

• Integration of ASP.NET AJAX into the .NET Framework.

• Many other enhancements, including:

− A powerful Add-In infrastructure

− Peer-to-peer networking support

− Integration of WCF and WF

− Enhancements to both WPF and Windows Forms

− Enhancements to ASP.NET, including new controls and a Web Application project.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 6 All Rights Reserved

Visual Studio 2008

• Visual Studio 2008 provides effective tooling support for .NET Framework 3.5.

− Although .NET 3.0 add-ins for Visual Studio 2005 were available, full tool support only comes with Visual Studio 2008.

• Enhancements in Visual Studio 2008 include:

− Improvements in the Integrated Development Environment (IDE), such as better navigation and easier docking.

− Automatic settings migration from Visual Studio 2005 (but third-party add-ons must be manually migrated).

− Multi-targeting to .NET 2.0, .NET 3.0 or .NET 3.5.

• There are many new project templates:

− ASP.NET AJAX projects

− WPF projects

− WCF projects

− WF projects

− Reporting projects

• There are a number of new designers, including WPF Designer, an object/relational designer, and a workflow designer.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 7 All Rights Reserved

Visual Studio 2008 Versions

• The Express Editions provides a lightweight IDE, with separate versions for C#, Visual Basic, Visual C++, and for Web application development.

− These versions provide a simplified environment and are permanently free.

• Visual Studio 2008 Standard Edition provides a fully integrated environment for all the supported languages and project types.

− Numerous additional features are provided for debugging, refactoring, XML programming, WCF development, and other tasks.

− It provides most of the features of the Professional Edition at a lower price point.

− Everything covered in this course works fine with the Standard Edition.

− Visual Studio 2008 Professional Edition supports development for a wider range of platforms, including Microsoft Office, smart devices, and Windows CE.

− It also includes automated support for unit testing.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 8 All Rights Reserved

Visual Studio 2008 Team System

• Visual Studio 2008 Team System contains numerous tools for Application Lifecycle Management (ALM).

• There are four versions, supporting specific development roles in large projects.

− Architecture Edition

− Database Edition

− Development Edition

− Test Edition

• Team Suite is a bundle containing all four editions of Team System.

• Visual Studio 2008 Team Foundation Server is the collaboration server at the hub of the whole Team System, including support of:

− Project management

− Work item tracking

− Version control

− Reporting and business intelligence

− Build management

− Process guidance

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 9 All Rights Reserved

Plan for this Course

• The scope of .NET 3.5 and Visual Studio 2008 is daunting!

− There is no way we can do justice to this rich technology in three days.

• Our plan is to cover some of the most important topics in a hands-on manner.

− In the rest of this chapter we’ll take a brief tour of Visual Studio 2008, including a first look at WPF.

− In Chapter 2 we’ll cover the new language features in Visual Basic.

− Chapter 3 introduces LINQ.

− Chapter 4 introduces WCF.

− Chapter 5 introduces WF.

− We’ll conclude with additional coverage of WPF.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 10 All Rights Reserved

A Tour of Visual Studio 2008

• Visual Studio 2008 opens up with an appearance very similar to Visual Studio 2005.

• Our tour will include the following:

− New project templates

− Some of the new designers

− Creating a simple solution with two projects, a WPF Windows application and a class library.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 11 All Rights Reserved

New WPF Project Templates

• Bring up the New Project dialog:

− File | New | Project.

• You’ll see four new templates for Visual Basic Windows project type.

− WPF Application

− WPF Custom Control Library

− WPF Browser Application

− WPF User Control Library

− Note the dropdown at top specifying target .NET version.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 12 All Rights Reserved

Creating a New WPF Application

• As illustrated on the preceding page, let’s create a new WPF Application.

1. Select the WPF Application template.

2. Navigate to the \OIC\NewVb3\Demos directory.

3. Type in HelloWpf as the name of the new project.

4. Check “Create directory for solution” and click OK.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 13 All Rights Reserved

XAML

• The most conspicuous new feature is a split window, showing XAML markup language in the lower pane and a visual design view in the upper pane.

• Extensible Application Markup Language (XAML, pronounced “zammel”) provides a declarative way to define user interfaces.

− The topmost UI element is Window, which is shown highlighted in the XAML pane and selected in the Property window.

− Change the Title to “Hello WPF”.

− The new title is now shown in both XAML and the design view.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 14 All Rights Reserved

Navigating XAML and Design View

• A tabbed UI with various buttons lets you switch between Design and XAML view.

• The button collapses to a single view. You can select which single view you want displayed by selecting the Design or XAML tab.

• You can go back to horizontal split with the button and to a vertical split with the button.

• You can flip the two views with the tab.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 15 All Rights Reserved

Sample Application

• As a demo we’re going to create a simple WPF Windows application.

− User enters name.

− User clicks Greet button.

− A message box appears with a greeting.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 16 All Rights Reserved

Editing XAML

• The UI can be completely specified in the text XAML file and edited as text.

• Continuing with the HelloWpf application we’ve created in the Demos directory, do the following:

1. Collapse to just the XAML view.

2. Remove the Width and Height attributes from the Window element.

3. Change the <Grid> to <StackPanel>, a simpler kind of panel.

4. Within the <StackPanel> provide a <WrapPanel>. Note how IntelliSense makes your entry easier.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 17 All Rights Reserved

Editing XAML (Cont’d)

5. After you select <WrapPanel> from the yellow IntelliSense popup, type a closing > and you’ll see the following XAML code.

<StackPanel> <WrapPanel> </WrapPanel> </StackPanel> 6. Now enter a <Label> and a <TextBox>, providing a suitable

Name attribute for the text box.

<StackPanel> <WrapPanel> <Label>Name:</Label> <TextBox Name="txtName"/> </WrapPanel> </StackPanel> 7. Next, after the <WrapPanel> provide a <Button>.

<StackPanel> <WrapPanel> <Label>Name:</Label> <TextBox Name="txtName"/> </WrapPanel> <Button Name="btnGreet">Greet</Button> </StackPanel>

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 18 All Rights Reserved

Sizing the Elements

8. Switch to Design view. Some tweaking is required!

9. Drag the text box wider. Note that the window, panels, and button also expand.

10. Drag the button to be more narrow.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 19 All Rights Reserved

Sizing the Window

11. Build and run your little app. The main window opens to a default size, which is not what you want!

12. Back in Design View, nudge the size of the window a little in each dimension.

13. Now build and run again. Better!

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 20 All Rights Reserved

Editing XAML (Cont’d)

14. Back in XAML view, place margins around the wrap panel and button. Also, provide a Background for the window. You can choose a color with the help of IntelliSense.

<Window ... Title="Hello WPF" Height="111" Width="187" Background="Beige"> <StackPanel> <WrapPanel Margin="10"> <Label>Name:</Label> <TextBox Name="txtName" Width="126" /> </WrapPanel> <Button Name="btnGreet" Width="62" Margin="10">Greet</Button> </StackPanel> </Window> 15. Back in Design view, the margin has thrown off the sizing of

the window. Resize the window again.

16. Back in XAML view, you can see the new dimensions of the window.

<Window ... Title="Hello WPF" Height="122" Width="216" Background="Beige"> ...

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 21 All Rights Reserved

Adding an Event Handler

17. Finally, we’ll provide a handler for the Click event of the button. In XAML you can use IntelliSense to find the Click event.

18. Selecting the Click event, you are now able to add a new event handler.

19. Here is the XAML after the event handler has been added:

<Button Name="btnGreet" Width="62" Margin="10" Click="btnGreet_Click">Greet</Button> 20. A stub for the event handler is generated in the “code behind”

file Window1.xaml.vb.

Private Sub btnGreet_Click( _ ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) End Sub

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 22 All Rights Reserved

Adding an Event Handler (Cont’d)

21. Provide the following code to retrieve the name entered in the text box and use it to display a greeting in a message box.

Private Sub btnGreet_Click( _ ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) MessageBox.Show("Hello, " & txtName.Text, _ "Hello WPF") End Sub 22. Build and run. We’ve completed the application we set out to

create!

• The application at this point is saved in the Chap01 folder.

− See \OIC\NewVb3\Chap01\HelloWpf\Step1.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 23 All Rights Reserved

Solutions with Multiple Projects

• Visual Studio makes it easy to manage solutions with multiple projects.

− We’ll use this feature extensively in later chapters.

• As a small demo, let’s create a class library GreetLib with a method GetGreeting() that returns a greeting.

1. In Solution Explorer, right-click over the solution and select Add | New Project ... from the context menu.

2. The Add New Project dialog comes up. Choose ClassLibrary as the template, and type in GreetLib as the name of your new class library.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 24 All Rights Reserved

Class Library Project Demo

3. In Solution Explorer, change the name of the file Class1.vb to Greet.vb. Note that the name of the class changes too.

4. Provide the following code for a shared method GetGreeting().

Public Class Greet Public Shared Function GetGreeting( _ ByVal name As String) As String Return "Hello, " & name End Function End Class

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 25 All Rights Reserved

Referencing the Class Library

5. To use this class library from the HelloWpf project, we’ll need to add a reference.

6. Right-click over References and choose Add Reference ... from the context menu. (Add Service Reference ... is a new feature in Visual Studio 2008 and refers to a WCF service.)

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 26 All Rights Reserved

Referencing the Class Library

7. In the Add Reference dialog select the Projects tab. Note that the GreetLib project has been selected for you.

8. Click OK.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 27 All Rights Reserved

Project Dependencies

9. Add a project reference in this way automatically sets up correct project dependencies. To see this, right-click on the solution and select Project Dependencies ... from the context menu.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 28 All Rights Reserved

Build Order

10. The build order is right too.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 29 All Rights Reserved

Using the Class Library

11. To simplify using the class library in the file Window1.xaml.vb, we provide a Imports statement for GreetLib.

Imports GreetLib ... 12. Finally, we modify the code in the event handler to call the

shared GetGreeting() method.

Private Sub btnGreet_Click( _ ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) MessageBox.Show( _ Greet.GetGreeting(txtName.Text), _ "Hello WPF") End Sub 13. Build the solution. This will build both projects, the class

library first.

14. Run the program. The first project in the solution, HelloWpf, is by default the startup project, so HelloWpf.exe will run. The program should behave the same as before.

• The program is now at Step 2.

− See Chap01\HelloWpf\Step2.

− You’ll create a Step 3 in a lab!

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 30 All Rights Reserved

New Web Project Templates

• Continuing our tour, there are three new Web project templates:

− ASP.NET AJAX Server Control

− ASP.NET AJAX Server Control Extender

− WCF Service Application

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 31 All Rights Reserved

Reporting Project Templates

• There is a new Reporting project type with this template:

− Reports Application.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 32 All Rights Reserved

WCF Project Templates

• WCF is another new project type, with these templates:

− Sequential Workflow Service Library

− Syndication Service Library

− State Machine Workflow Service Library

− WCF Service Library

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 33 All Rights Reserved

Workflow Project Templates

• Finally, a new Workflow project type has six templates:

− Empty Workflow Project

− Sequential Workflow Library

− State Machine Workflow Library

− Sequential Workflow Console Application

− State Machine Workflow Console Application

− Workflow Activity Library

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 34 All Rights Reserved

Workflow Designer

• Workflows can be visually created using the new Workflow Designer.

− Workflows will be discussed in Chapter 5.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 35 All Rights Reserved

Object/Relational Designer

• Another new designer in Visual Studio 2008 is the Object/Relational Designer.

− This tool enables you to automatically create entity classes that represent the relational data your program interacts with.

− This tool will be discussed in Chapter 3.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 36 All Rights Reserved

Lab 1

An Enhanced WPF Application and Class Library

In this lab you will enhance both the user interface and the class library in the HelloWpf solution. In the new version, the user will be able to choose a language for the greeting.

Detailed instructions are contained in the Lab 1 write-up at the end of the chapter.

Suggested time: 30 minutes

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 37 All Rights Reserved

Summary

• .NET 3.0, layered on .NET 2.0, introduced these technologies:

− Windows Presentation Foundation (WPF)

− Windows Communication Foundation (WCF)

− Windows Workflow Foundation (WF)

− Windows CardSpace (WCS)

• .NET 3.5 provides new language features in C# and Visual Basic and introduces Language Integrated Query (LINQ).

• Visual Studio 2008 provides tooling support for .NET 3.5 applications.

• Visual Studio 2008 comes in Express, Standard, Professional and Team System editions.

• Visual Studio 2008 provides new project templates and designers.

• You can implement WPF programs by editing XAML markup and using the WPF Designer.

• An important capability of Visual Studio is multiple-project solutions, which are used extensively with .NET 3.5 applications.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 38 All Rights Reserved

Lab 1

An Enhanced WPF Application and Class Library

Introduction In this lab you will enhance both the user interface and the class library in the HelloWpf solution. In the new version, the user will be able to choose a language for the greeting.

Suggested Time: 30 minutes Root Directory: OIC\NewVb3 Directories: Labs\Lab1\HelloWpf (do your work here) Demos\HelloWpf (alternate working directory) Chap01\HelloWpf\Step2 (backup of starter code) Chap01\HelloWpf\Step3 (answer) A clean starting solution, backed up in Chap01\HelloWpf\Step2, is provided in the lab working directory. Alternatively, if you prefer, you may continue with your own work done in the Demos directory. Part 1. Enhance the User Interface In Part 1 we’ll add a dropdown combo box to let the user specify a choice of language for the greeting. 1. Build and run the starter program. Notice that if you make the window more narrow,

the text box “wraps” rather than becomes partially or totally obscured (as it would in a normal Windows Forms application).

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 39 All Rights Reserved

2. In XAML view add a <ComboBox> between the <WrapPanel> and the <Button>.

<StackPanel> <WrapPanel Margin="10"> <Label>Name:</Label> <TextBox Name="txtName" Width="126" /> </WrapPanel> <ComboBox> </ComboBox> <Button Name="btnGreet" Width="62" Margin="10" Click="btnGreet_Click">Greet</Button> </StackPanel> 3. In Design view adjust the size of both the window (you need to increase the height)

and the combo box (make it more narrow).

4. Select the combo box, and in the Properties window find the Items property.

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 40 All Rights Reserved

5. Click on the button. The Collection Item Editor comes up. Add three ComboBoxItem elements. Make the Content of these three items “English”, “French” and “Texan”.

6. Click OK, and examine the XAML markup.

<ComboBox Width="125"> <ComboBoxItem>English</ComboBoxItem> <ComboBoxItem>French</ComboBoxItem> <ComboBoxItem>Texan</ComboBoxItem> </ComboBox> 7. Build and run. Nothing is selected originally, but you can drop down the combo box

and select something, e.g. “English”.

8. To make “English” automatically selected as the default, you can set the IsSelected property to True. Also, assign the Name property of the combo box itself to cmbLanguage.

<ComboBox Width="125" Name="cmbLanguage"> <ComboBoxItem IsSelected="True">English</ComboBoxItem> <ComboBoxItem>French</ComboBoxItem>

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 41 All Rights Reserved

<ComboBoxItem>Texan</ComboBoxItem> </ComboBox> 9. Build and run, verifying that “English” is indeed shown as the default selection.

10. Temporarily show another message box in the handler of the Greet button to display the selected item.

Private Sub btnGreet_Click(ByVal sender As System.Object, ByVal e As _ System.Windows.RoutedEventArgs) MessageBox.Show(cmbLanguage.SelectedItem.ToString()) MessageBox.Show(Greet.GetGreeting(txtName.Text), _ "Hello WPF") End Sub 11. Build and run, and click Greet. The result is disappointing.

12. The items in the combo box are stored as type object. To get what we want, we need to perform a cast to ComboBoxItem and take the Content property. Use this code instead:

Private Sub btnGreet_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim cbi As ComboBoxItem = _ CType(cmbLanguage.SelectedItem, ComboBoxItem) MessageBox.Show(cbi.Content.ToString()) MessageBox.Show(Greet.GetGreeting(txtName.Text), _ "Hello WPF") End Sub 13. Build and run. Now we get what we want!

Part 2. Enhance the Class Library In Part 2 we’ll add a second method to the Greet class in the class library. This method will take a second string, the name of the language to be used in the greeting. 1. In the GreetLib project, provide an overloaded version of the GetGreeting() method.

In the code, you simply test the value of the language parameter and return the appropriate greeting. Return an error message if the language is something unexpected.

Public Class Greet Public Shared Function GetGreeting(ByVal name As String) As String

NewVb3 Chapter 1

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC 42 All Rights Reserved

Return "Hello, " & name End Function Public Shared Function GetGreeting(ByVal name As String, _ ByVal lang As String) As String If lang = "English" Then Return "Hello, " & name ElseIf lang = "French" Then Return "Bonjour, " & name ElseIf lang = "Texan" Then Return "Howdy, " & name Else Return "Language not supported" End If End Function End Class 2. In the HelloWpf project, modify the code of the button handler to call this new

overloaded method. You may comment out showing the first message box.

Private Sub btnGreet_Click(ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) Dim cbi As ComboBoxItem = _ CType(cmbLanguage.SelectedItem, ComboBoxItem) 'MessageBox.Show(cbi.Content.ToString()) Dim language As String = cbi.Content.ToString() Dim greeting As String = Greet.GetGreeting(txtName.Text, language) MessageBox.Show(greeting, "Hello WPF") End Sub 3. Build and test. The program should now be fully operational!

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

175

Chapter 5

Windows Workflow Foundation (WF)

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

176

Windows Workflow Foundation (WF)

Objectives

After completing this unit you will be able to:

• Explain what a workflow is and how Windows Workflow Foundation supports workflow applications.

• Describe a typical business scenario for workflow and illustrate with a WF application.

• Create workflow applications using Visual Studio 2008 and the Workflow Designer.

• Explain what an activity is and use typical activities in your workflow applications:

− Code

− IfElse

− While

− Sequence

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

177

What Is Workflow?

• In general terms, a workflow can be thought of as a flow of processes or tasks that produce some result.

• Workflows are often concerned with documents that flow through various activities and may spawn other documents as they are processed.

• Workflows can be manual, with paper documents being transmitted among people working at different desks in an office, each person performing defined tasks according to specified rules.

• We are concerned with workflows as software systems that define the flow of work, the activities performed, and the rules that are employed.

− Rules can be expressed declaratively or in code.

− Activities may be entirely automated or may involve human interaction.

− Workflows may be distributed among multiple computers in diverse locations.

− Workflows are typically represented in a graphical manner.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

178

Windows Workflow Foundation

• Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms.

− WF consists of a programming model, an engine, and tools.

− The tools include designers for Visual Studio.

• WF provides a consistent development experience with other .NET 3.0/3.5 technologies, including WCF and WPF.

• The WF API contains support for both C# and Visual Basic, a special workflow compiler, workflow debugging support, and a visual workflow designer.

• Workflows can be developed completely in code or created in conjunction with XAML markup.

• The WF model and designer are extensible, enabling developers to create custom activities to encapsulate particular workflow functionality.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

179

Workflows

• A workflow is a set of activities that are stored in a model describing a business (or other real-world) process.

• A workflow describes the order of execution and relationships between units of work.

− The units of work may run for a short time or a long time.

− Activities may be performed by people or the computer.

• A workflow instance is created and maintained by the workflow runtime engine.

− There can be several workflow engines within an application domain.

− Each instance of the engine can support multiple workflow instances.

• A compiled workflow model can be hosted inside any Windows process, including a console application, a Windows Forms application, a WPF application, a Windows service, an ASP.NET Web application, and a Web service.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

180

Activities

• The units of work of a workflow are called activities.

• When a workflow instance starts, activities are executed in an order as defined by the workflow model.

− Both parallel and sequential orders of execution are supported.

− Conditional and looping behavior of activities is supported.

− Execution continues until the last activity completes, and the workflow then terminates.

• Activities can be reused within a workflow and in other workflows.

• Activities usually have properties that are configurable.

• WF provides many standard activities out-of-the box, and custom activities can be created.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

181

Standard Activities

• The Visual Studio toolbox contains many standard activities that can be dragged onto the surface of the Workflow Designer.

− The Code activity can be used to represent any desired

custom code.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

182

Runtime Services

• WF provides a number of out-of-the box runtime services that are available in the workflow engine.

• Persistence services enable a developer to easily save a WF instance to external storage, such as a database or XML file.

− This capability enables workflow applications to maintain state and be long-running, surviving application restarts.

• Transaction services enable you to maintain transactional integrity in workflow applications.

• Tracking services support monitoring and recording workflow execution.

• Scheduling services enable you to control how the WF runtime manages threads in your application.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

183

Workflow Business Scenario

• To illustrate workflows consider the following business scenario:

− As orders are created they are specified in XML files placed in the folder Orders.

− Each order in the Orders folder is processed, beginning with getting the order information from the XML file.

− The order is verified, which is done by a person who checks each item in the order for consistency (description furnished by customer matches the description in the vendor database or has a trivial error such as a misspelling). The system also does some verification, making sure that the item ID is found in the database.

− If the order is valid, it is processed and an invoice is created. The invoice is specified in an XML, stored in the Invoices folder.

− If the order is not valid, the issue with the order is specified in another XML file, stored in the Issues folder. (A customer service representative can follow up on such orders by emailing the customer.)

• This scenario is implemented by a workflow application.

− See Chap05\OrderWF. See the file Workflow1.vb in the OrderWF project for a diagram of the workflow.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

184

High Level Workflow

• Open up the file Workflow1.vb.

− The Workflow Designer opens up, showing a diagram of the workflow.

− Examine the workflow at a high level by collapsing the whileMoreOrders activity. (Where a portion of the diagram can be collapsed you will see a little button showing a minus sign that can be clicked.)

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

185

Details of While Activity

• The heart of the workflow is a loop that gets and verifies orders.

− If order is valid, it is processed.

− If order is not valid, an issue is processed.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

186

Orders Folder

• The Orders folder contains XML files representing orders. The loop goes through all the files in this folder.

− As an example, consider 1002.xml. This order is basically valid, but one of the items is slightly questionable.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Order> <OrderId>1002</OrderId> <Customer> <Name>Mary Smith</Name> <Email>[email protected]</Email> </Customer> <Item> <ItemId>104</ItemId> <Description>Sofa</Description> <Quantity>1</Quantity> </Item> <Item> <ItemId>102</ItemId> <Description>Tabel</Description> <Quantity>2</Quantity> </Item> <Item> <ItemId>103</ItemId> <Description>Lamp</Description> <Quantity>2</Quantity> </Item> </Order>

• An automated verification might reject item 102 because of the misspelling of the description.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

187

Manual Step in the Verification

• As is typical in workflow applications, steps in the workflow can be carried out either by the computer or a person.

• As part of the processing of the VerifyOrder activity a message box will be displayed for a human to verify each item.

• Build the solution, which consists of four projects.

− Start the Host project, which must be running because VerifyOrder invokes a WCF service.

− Then start the OrderWF project.

− As orders are verified, a message box will pop up for each item of each order.

• Here is the message box for item 102 of order 1002.

• The person viewing this will clearly see that this is benign and will click Yes to approve this item.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

188

Main Console Display

• As the workflow is executed, a running report on each item is displayed on a main console.

• Here is the display for order 1002: C:\OIC\NewVb3\Demos\OrderWF\Orders\1002.xml OrderId = 1002 Verification message = OK OrderId = 1002 CustomerName = Mary Smith CustomerEmail = [email protected] ItemId Description Quantity ... Price Extension 104 Sofa 1 ... $500.00 $500.00 102 Tabel 2 ... $200.00 $400.00 103 Lamp 2 ... $50.00 $100.00 Total = $1,000.00 File 1002.xml has been created in folder Invoices

• And here is the display for orders 1003 and 1004 for which there were genuine issues.

file = 1003.xml C:\OIC\NewVb3\Demos\OrderWF\Orders\1003.xml OrderId = 1003 Verification message = Description does not match Create issue: Description does not match File 1003.xml has been created in folder Issues file = 1004.xml C:\OIC\NewVb3\Demos\OrderWF\Orders\1004.xml OrderId = 1003 Verification message = Item Not Found Create issue: Item Not Found File 1004.xml has been created in folder Issues Press Enter to exit

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

189

Issues Folder

• The Issues folder will contain an XML file for each order having a genuine issue.

• Our example illustrates two kinds of problems.

− The item is not found in the database, a problem that can be detected automatically, illustrated in order 1004.

− The item’s description indicates a genuine question, such as an ambiguity that should be verified with the customer, illustrated in order 1003.

− The human verifier will reject this item, because the company has several bookshelves having different numbers of shelves, and the customer should be queried to make sure she gets the desired bookshelf.

− Here is the generated issue file 1003.xml: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <Issue> <OrderId>1003</OrderId> <CustomerName>Bill Jones</CustomerName> <CustomerEmail>[email protected]</CustomerEmail> <Message>Description does not match</Message> </Issue>

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

190

Invoices Folder

• For valid orders an XML file is created from which an invoice can be generated.

− The actual invoice that will be sent to the printer is created by a separate subsystem, which could be another workflow, whose input is the files in the Invoices folder.

• As an example, here is the invoice XML file for order 1002.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Invoice> <OrderId>1002</OrderId> <CustomerName>Mary Smith</CustomerName> <CustomerEmail>[email protected]</CustomerEmail> <LineItem> <ItemId>104</ItemId> <Description>Sofa</Description> <Quantity>1</Quantity> <Price>500.0000</Price> <Extension>500.0000</Extension> </LineItem> <LineItem> <ItemId>102</ItemId> <Description>Table</Description> <Quantity>2</Quantity> <Price>200.0000</Price> <Extension>400.0000</Extension> </LineItem> <LineItem> <ItemId>103</ItemId> <Description>Lamp</Description> <Quantity>2</Quantity> <Price>50.0000</Price> <Extension>100.0000</Extension> </LineItem> <Total>1000.0000</Total> </Invoice>

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

191

Learning Microsoft’s WF

• There are two main challenges in learning to use Windows Workflow Foundation.

• The first challenge is to understand the nature of workflow applications, which are quite different in structure from conventional applications.

− For this purpose studying a miniature example illustrating an actual business scenario is invaluable.

− The program OrderWF is such an example.

• The second challenge is to understand the classes and tools in the actual framework.

− For this purpose studying small standalone examples, divorced from the complexities of a business situation, will be most helpful.

− We’ll follow this approach in the remainder of the chapter, beginning with a simple “Hello Workflow” example that we’ll build from scratch using Visual Studio 2008.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

192

Hello Workflow

• Let’s use Visual Studio 2008 to create a simple workflow that will do the following:

− Prompt the user for a name.

− Display a greeting.

− Prompt for exit.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

193

Hello Workflow Demo

1. In Visual Studio create a new project of type Workflow using the Sequential Workflow Console Application template. Provide the Name HelloWF and location C:\OIC\NewVb3\Demos.

2. In Solution Explorer, change the name of the file Workflow1.vb to GreetingWorkflow.vb and click the View Code button.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

194

Hello Workflow Demo (Cont’d)

3. Examine the starter code:

Public Class GreetingWorkflow Inherits SequentialWorkflowActivity End Class

− The key class is SequentialWorkflowActivity in the System.Workflow.Activities namespace.

4. Click the View Designer button.

5. Examine the starter workflow in the Workflow Designer.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

195

Hello Workflow Demo (Cont’d)

6. Drop a Code activity between the start and end icons. In the Properties window, change the Name to PromptForName.

7. The exclamation point icon indicates that this activity has not yet been completely specified. You need to specify the ExecuteCode property.

8. Name the method PromptForUserName. (It has to be different from the name of the activity.)

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

196

Hello Workflow Demo (Cont’d)

9. You will be brought to the Code View, where you can enter code for the method. Also, provide a public property UserName to hold the string that the user enters.

Private privateUserName As String Public Property UserName() As String Get Return privateUserName End Get Set(ByVal value As String) privateUserName = value End Set End Property Private Sub PromptForUserName(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Console.Write("Your name: ") UserName = Console.ReadLine() End Sub 10. In a similar manner drop a second activity. For Name specify

DisplayGreeting and for Execute code specify GreetUser.

11. Finally, drop a third activity. Specify PromptForExit for Name and PromptUserForExit for ExecuteCode.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

197

Hello Workflow Demo (Cont’d)

12. Implement the two additional methods.

Private Sub GreetUser(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Console.WriteLine("Hello, " + UserName) End Sub Private Sub PromptUserForExit(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Console.WriteLine("Press Enter to exit") Console.ReadLine() End Sub 13. Build and run. The program at this point is saved in

Chap05\HelloWF\Step1.

14. Examine the workflow in the Workflow Designer.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

198

IfElseActivity

• Typically a workflow will consist not only of sequential statements but will also contain some flow control statements.

• WF provides two activities supporting flow control:

− IfElse activity

− While activity

• See Chap05\IfElseWF for an example of an IfElse activity.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

199

Implementing a Branch

• To implement a branch you must specify a Condition, which can be either a Code condition or a Declarative Rule condition.

• Our example uses a Code condition, which is implemented by the method CheckLeapYear().

• Here is the code for CheckLeapYear(): Private Sub CheckLeapYear(ByVal sender As Object, _ ByVal e As ConditionalEventArgs) e.Result = IsALeapYear(Year) End Sub

• This code uses the property Year, which is set in the ReadYear() method.

Public Property Year() As Integer ... End Property Private Sub ReadYear(ByVal sender As Object, _ ByVal e As EventArgs) Console.Write("Enter year: ") Year = Convert.ToInt32(Console.ReadLine()) End Sub

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

200

Implementing a Branch (Cont’d)

• The second branch may or not be implemented.

• Our example implements the second branch, and both branches rely on a helper method IsALeapYear().

Private Sub CheckNotLeapYear(ByVal sender As _ Object, ByVal e As ConditionalEventArgs) e.Result = Not IsALeapYear(Year) End Sub Private Function IsALeapYear(ByVal year _ As Integer) As Boolean If year Mod 400 = 0 Then Return True ElseIf year Mod 100 = 0 Then Return False ElseIf year Mod 4 = 0 Then Return True Else Return False End If End Function

• Inside a branch is an activity, which will or will not be executed depending on the truth of the Condition.

• Here is the code for the activity inside the first branch:

Private Sub DisplayLeapYear( _ ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("{0} is a leap year", Year) End Sub

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

201

While Activity

• The While activity supports looping using the normal “while” syntax.

• We’ll illustrate with an improvement of our leap year example, letting the user test multiple years in a single run of the workflow.

− See Chap05\WhileIfElseWF.

− Here is a typical run of the workflow:

Enter year (-1 to exit): 2008 2008 is a leap year Enter year (-1 to exit): 2007 2007 is not a leap year Enter year (-1 to exit): 2000 2000 is a leap year Enter year (-1 to exit): 1900 1900 is not a leap year Enter year (-1 to exit): -1 Press Enter to exit

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

202

High-Level Workflow

• As with our earlier OrderWF example, we first show a high-level view of the workflow, with one of the nodes collapsed.

• The node that is collapse is HandleAYear, which is a Sequence activity.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

203

Sequence Activity

• A While node can contain only a single activity.

• At first, this may seem like a severe limitation, but one of the standard activities is a Sequence, which as the name suggests may contain multiple activities in sequence.

• In our example, the sequence consists of an IfElse activity followed by a Code activity.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

204

Condition in While Activity

• As with IfElse, a While activity has a Condition.

• Our example uses a Code Condition, whose method CheckForEof uses -1 as a sentinel for the end of file.

Private Sub CheckForEof(ByVal sender As Object, _ ByVal e As ConditionalEventArgs) If (Year = -1) Then e.Result = False Else e.Result = True End If End Sub

• Note that a condition of true means that there will be more iterations of the loop.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

205

Parallel Activity

• With a Parallel activity you can schedule two or more branches to execute in parallel.

− Each branch consists of a sequence of activities.

• There is not true parallelism, because a workflow instance executes on a single thread.

• Instead, each branch will execute one activity and then surrender execution to the next branch.

− The branches are scheduled in a round-robin fashion.

• See Chap05\Parallel for a simple example.

− Here is a run of the workflow:

Sequence #1 First Sequence #2 First Sequence #3 First Sequence #1 Second Sequence #3 Second Sequence #3 Third Press Enter to exit

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

206

Parallel Activity Workflow Diagram

• Here is a diagram showing the example workflow:

• A Parallel activity by default show two Sequences, but you can easily drop additional Sequences.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

207

Lab 5

Verifying Names in Hello Workflow

In this lab you will enhance the Hello Workflow program to validate names. A name is considered valid if each character in the name is a letter.

Detailed instructions are contained in the Lab 5 write-up at the end of the chapter.

Suggested time: 30 minutes

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

208

Summary

• A workflow can be thought of as a flow of processes or tasks that produce some result.

• Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms.

• You can create workflow applications using Visual Studio 2008 and the Workflow Designer.

• The units of work of a workflow are called activities. Typical activities include:

− Code

− IfElse

− While

− Sequence

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

209

Lab 5

Verifying Names in Hello Workflow

Introduction In this lab you will enhance the Hello Workflow program to validate names. A name is considered valid if each character in the name is a letter. Suggested Time: 30 minutes Root Directory: OIC\NewVb3 Directories: Labs\Lab5\HelloWF (do your work here) Chap05\HelloWF\Step1 (backup of starter code) Chap05\HelloWF\Step2 (answer) Instructions 1. Build and run the starter workflow.

2. Open GreetingWorkflow.vb in the WorkFlow Designer. Examine the starting workflow.

3. Drop a While activity between the PromptForName and DisplayGreeting activities. The result is shown on the next page.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

210

4. Provide the Name whileNameNotValidated for the While activity.

5. Specify a Code Condition with method ValidateName.

6. Implement ValidateName(). You want to set e.Result to true if there is to be another iteration of the while loop, i.e. the name is not valid. A name is considered valid if each character in the name is a letter. You can check an individual character for being a letter with the static Char.IsLetter() method. And you can convert a string to an array of characters with the ToCharArray() method. The complete code is shown on the following page.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

211

Private Sub ValidateName( _ ByVal sender As System.Object, _ ByVal e As System.Workflow.Activities.ConditionalEventArgs) Dim repeat As Boolean = False For Each ch As Char In UserName.ToCharArray() If Not Char.IsLetter(ch) Then repeat = True End If Next ch e.Result = repeat End Sub 7. Drop a Code activity inside the While activity. Call this new Code activity

RepromptForName.

8. Note the red exclamation point icon, telling you must finish specifying the new activity. Assign the name RepromptUserForName to ExecuteCode.

9. Provide the following code for the method:

Private Sub RepromptUserForName(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Console.WriteLine("Name must be all letters") Console.Write("Your name: ") UserName = Console.ReadLine() End Sub 10. Build and run. Your enhanced workflow should now be fully operational! Test with

both an invalid and a valid name.

NewVb3 Chapter 5

Rev. 1.0 Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

212

Your name: R2D2 Name must be all letters Your name: FriendlyRobot Hello, FriendlyRobot Press Enter to exit