Monday, November 2, 2009

Workflow foundation 4.0 part 4

It’s taken a while to get to this point but based on the changes in beta 2 of Visual Studio 2010 and the .Net Framework 4.0 it was probably prudent to wait.

There are a number of changes in beta 2, for one the designer has been revised again. Also there is only a single workflow. To create the the different workflows, sequence or flow chart, you start by dragging the appropriate activity container onto the design surface. The tool box has also been reorganized. The different components are organized by functionality.

In this post, I’m going to build a simple console workflow to read RSS feeds, in future posts I’ll enable WCF communications and workflow persistence. This workflow will read any number of feeds passed in as a workflow argument and returns the results from the workflow instance to the console.

To get started, open Visual Studio and create a new Workflow console application named RSSReaderWorkflow. You can change the name of the workflow to anything you like or leave it as is. I renamed the workflow to ReaderWorkflow for this project. One thing to note, you may have to open the workflow in xml mode to change the class name. The designer seems to pass this by when you rename from the solution explorer.



Now we need to a couple of container classes. The first, RSSFeeds contains a list of feed uri’s. This is the list of feeds read.

using System;
using System.Collections.Generic;


namespace RSSReaderWorkflow
{
public class RSSFeeds
{
public List<Uri> Feeds { get; set; }
}
}
 
 The second class we need to add is the RSSItem class. This class will contain the news items from the rss feeds that we read.

 
using System;

namespace RSSReaderWorkflow
{
public class RSSItem
{
public string Title { get; set; }

public string Link { get; set; }

public string Description { get; set; }
}
}




With that out of the way, drag a sequence activity from Control Flow section of the tool box. This is going to be a simple sequence workflow, so this activity serves as the container for the other activities we’ll add.


Next we’ll add two arguments one of the input named RssFeeds which is a type of RSSFeeds and is required.



The second argument is an out argument and will be a list of RSSItem. This will contain our feed results which we will display to the console.





Next drag an If activity from the tool box, we’ll add a condition to check that we have at least one feed to read.





Next in the else side of the if activity, we’ll add a throw activity. This activity will throw an argument out of range exception if the feeds count is zero.





Next we need to add a new code activity to read the feeds an populate the results. From the solution explorer right click –> add new item and select workflow and Code activity. Since we want to return the results of the rss feeds we’ll need to derive from TResult and add a bit of code. Here is the ReadFeedActivity class.






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Xml.Linq;

namespace RSSReaderWorkflow
{

public sealed class ReadFeedActivity : CodeActivity<List<RSSItem>>
{
// Define an activity input argument of type string
public InArgument<List<Uri>> FeedUri { get; set; }


// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override List<RSSItem> Execute(CodeActivityContext context)
{
List<RSSItem> results = new List<RSSItem>();

foreach (var f in FeedUri.Get(context))
{
XDocument doc = XDocument.Load(f.ToString(), LoadOptions.None);
results.AddRange( (from i in doc.Descendants("channel").Elements("item")
select new RSSItem()
{
Title = i.Element("title").Value,
Link = i.Element("link").Value,
Description = i.Element("description").Value
}).ToList());
}
// Obtain the runtime value of the Text input argument
return results;
}
}
}
 
Now Build the project and the new activity will be avaliable in the tool box. You can simply drag it to the if activity.


 

 Set the FeedUri Property to the RssFeeds.Feeds argument property.







Set the Result to the Results output argument property.



Now we need to update the main. It will create and pass in the the feeds and display the results.


class Program
{
static void Main(string[] args)
{
// set up a list of input feeds
Dictionary<string,object> wfArgs = new Dictionary<string,object>();

// the workflow is expecting a feed list object
RSSFeeds list = new RSSFeeds()
{
Feeds = new List<Uri>()
{
//usa today
new Uri("http://rssfeeds.usatoday.com/usatoday-NewsTopStories"),
//cnn
new Uri("http://rss.cnn.com/rss/cnn_topstories.rss")
}
};
// add the input to the args dictionary
wfArgs.Add("RssFeeds",list);


try
{
// the workflow will return a dictionary with the rss items
IDictionary<string, object> wfResults = WorkflowInvoker.Invoke(new ReaderWorkflow(), wfArgs);

// loop through the keys
foreach (var item in wfResults)
{
// cast the value as an RSSItem list
List<RSSItem> res = item.Value as List<RSSItem>;

// display the results
res.ForEach(i => Console.WriteLine(i.Title));

}
}
catch(ArgumentOutOfRangeException e) // if you comment out the feeds, you can watch the throw in acction
{
Console.WriteLine(e.Message);
}

Console.Read();
}
}



Now we have a simple workflow that reads RSS feeds.

Monday, October 26, 2009

SKU’d again

Another Visual Studio Release and another round of SKU’s. It seems the marketing folks in Redmond that had a hand in this where the same ones that brought us the Vista and Windows 7 product line up.

So here is the basic break down of the Old versus the New SKU’s for Visual Studio 2010.

  • Visual Studio Standard and Visual Studio Professional become VS 2010 Professional
  • Visual Studio Professional with MSDN Premium and Visual Studio Professional with MSDN Professional become VS 2010 Professional with MSDN
  • Visual Studio Team Dev, Database, Architect and Test become VS 2010 Premium with  MSDN
  • The Visual Studio Team Suite becomes VS 2010 Ultimate with MSDN

  Of course Express is still available as before for the hobbyist, as before one for each language. There is also a combo install for express, but quite frankly I haven’t had time to look at it.

Microsoft is also offering an upgrade offer for MSDN Premium subscribers during the “transition” time, that will allow you to activate a premium subscription now and get Ultimate when Visual Studio 2010 is released in or around March of 2010.

In the end I find these marketing name games a pain, I like the seeming simplification, the names are to Windowy for my taste.

Sunday, October 25, 2009

What's New in EF 4

Julie Lerman has posted a Screen cast – What’s new in the Entity Data Model Designer in VS2010. Defiantly worth a look. She covers Complex Types and the new Foreign Key functionality as well as a slew of other changes. The screen cast runs about 20 minutes and can be found at http://www.screencast.com/users/JulieLerman/folders/EF4

Tuesday, October 20, 2009

Microsoft has released VS 2010 beta 2 to MSDN and Technet subscribers. General availability is set for the 21st of October.

The UI is greatly improved since beta 1, here are a few screens to wet your appetite while you wait.

The Install start screen.



More install




Install process


The start up screen has been greatly enhanced since beta 1.


There are a number of changes, in fact too many to list in a single entry. Look forward to the continuation of the workflow series shortly..

Thursday, October 15, 2009

Practicing Scrum or Doing Scrum?

If your organization is like any other today, they’re looking for ways to cut costs and deliver on time and for many development teams it means Scrum or some variation.

When you ask your peers what methodology they are using many will say Scrum, but the fact of the matter is Scrum is not a methodology it is a wrapper around existing methodologies. Scrum will work with anything from CMM to XP.

  In the company I’m with now we do sprints, planning and daily stand up meetings. Even doing those things we’re not really practicing Scrum, we’re doing Scrum. We’re just going through the motions and when you do that quality is the first thing to suffer followed by moral. Each sprint becomes a death march and the developers don’t really pay much attention to what is on the backlog, it’ll be rolled forward if it’s not finished. You also begin to see backlog fudge, where some pet project or desire is added because someone felt like that’s what they wanted to do. Inevitably we no longer release or demo functionality to the users and owners at the end of the sprint. We’ve gone from Scrum and XP to “Scrumterfall”  Waterfall with a Scrum veneer.

So how do we bring turn around from just going through the motions to reaping the benefits of practicing Scrum?

  The first thing that needs to be addressed is the backlog. The backlog need to be scrubbed and reprioritized. This process needs to happen on a continual basis, otherwise the backlog becomes stale.

  Once we have a well prioritized backlog, we need to plan the sprints. Normally we plan sprints for two or three weeks, which honestly is not enough time, especially in a greenfield project, such as the one we’re currently working on. Sprints should ideally be thirty days. I like thirty work days as opposed to thirty calendar days, that way you know exactly what time you have to plan and execute with. Planning shouldn’t be a one or two hour meeting where you grab enough items off the list to fill the available velocity. Rather planning should last for a whole day. The highest priority backlog items should be broken down enough to give a decent effort. Once you’ve selected and planned the backlog based on releasing working functionality you’re halfway there. It is essential that all the team members buy into the work to be performed and agree that it can be accomplished.

During the sprint the Scrum master needs to play the role of “Heavy” and eliminate interference and remove obstacles from the dev teams goal. He/She needs to insure the backlog doesn’t grow to include “pet” projects or “I feel like doing something else” backlog items. He should lead the daily stand ups using a simple format. What did you do yesterday?, What are you doing today? and What obstacles are preventing you from completing your tasks? The daily stand ups are not optional affairs, they should include everyone always, no excuses.

  The team should work to accomplish all the tasks planned for the sprint, but realize that you may not always complete all of the backlog items for a given sprint. You may also discover during the course of the sprint that the scope of some backlog items were underestimated or impacted more than originally thought.

The sprint should be closed out with a demo of the features implemented during the sprint. Invite users and management to come and try the functionality for themselves. Involving the users is key, if they’re not engaged or see no tangible benefit they’ll be less like to support further development.

Sunday, September 13, 2009

Where’s part 4

It’s been a while since I last posted and to be honest, I simply haven’t had the time to complete part 4 of the windows workflow series. It looks like that will probably be posted once beta 2 is of VS2010 is available. There are several reasons, one, hopefully beta 2 will be more representative of the final release and two, my workload has been pretty hectic these days.

On the plus side, I’ve spent a great deal of time in Silverlight 3 these days. I’m moving an existing ASPNET app to SL3 and the difference in performance is night and day. Maybe it’s the no post back thing or just the added richness that can be added quickly at any rate I’m now a SL/WPF convert.

Anyhow, stay tuned there is more workflow and some silverlight coming up on the blog as soon as I get caught up.

Friday, July 10, 2009

More on Visual Studio Magazines demise

In the comments to my earlier post on the sad state of Visual Studio Magazine I responded to Matt Morollo VP of Publishing for the Redmond Group. I’d like to take the numbers quoted in my response and compare the current issue to the December 2008 issue, which was before the redesign of the magazine.

  Current Issue December 2008
Pages 32 40
Adverts 13 13
Meaningful articles* 0 3

* A meaningful article is defined as one that contains code samples or demonstrates a technology or language feature.

As you can see we’ve lost 8 pages, 3 articles and manages to keep the same number of advertisements.

At the end of the day the advertisers are the real losers here. The subscribers will seek out and find new sources of information either through print or on the internet while the advertisers who are footing the bill for the shiny anemic new look will not see much return in terms of revenue.

Silverlight 3 tools released

Silverlight 3 tools have been released. Unfortunately Blend 3 hasn’t been released to manufacturing yet. You can grab the bits at http://silverlight.net/GetStarted/

Tuesday, July 7, 2009

Windows Workflow Foundation 4.0 (Part 3 Activities)

On of the most visible areas of change in WF 4.0 is the out of the box activities. In this article we’ll take a look at the out of the box activities that are included in beta 1. The in the following articles we’ll begin to use these activities as well as custom activities to write a functional workflow that I’ll use to demonstrate some of the other features of WF 4.0.

Activities

  The out of the box activities are divided into five categories.

  • Procedural – These are the core workflow activities including activities such as the ForEach activity, While activity and a number of others described below.
  • Flowchart – As the name implies these are the core flowchart activities.
  • Messaging – These are the WCF workflow activities that include Send and Receive activities as well as several others.
  • Power Shell – These are a new set of activities for working with Windows Power Shell from WF.
  • Interop – There is only one activity in this category.

Activity

Description

Collection Management

AddToCollection<T>

Adds an Item to a Collection.

RemoveFromCollection<T>

Removes an Item from a Collection.

ClearCollection<T>

Clears a Collection, removing all items stored in it.

ExistsInCollection

Verifies if an Item exists in a Collection. If the item exists, its Result argument will yield True.

Control of Flow

If

The If activity selects a child activity for execution based on the value of a Boolean expression.

If the Boolean expression Condition yields True (and “Then” activity is configured), the “Then” activity is scheduled. If the expressions yields False (and “Else” activity is set), the “Else” expression is scheduled.

DoWhile

Executes its Body until the Condition evaluates to True. The Body will be executed at least once.

ForEach / ForEach<T>

ForEach activity contains a list of Values and a Body. At runtime, the list is iterated and the body is executed for each value in the list.

Pick

The Pick Activity provides event-based control flow modeling in WF. The only valid children for a Pick activity are PickBranches.

At the beginning of a Pick execution, all the Trigger activities from all its Branches are scheduled. When the first Trigger completes its corresponding Action activity is scheduled, and all other Trigger activities are canceled.

PickBranch

PickBranch represents a branch in a Pick. It consists of a Trigger and Action. PickBranch can only be added to a Pick activity.

Sequence

The Sequence activity allows for the execution of one or more Activities in order.

Switch<T>

Switch activity is similar to switch statement in C#. It contains an Expression and a set of Cases (each case has a key and an activity). After the expression is evaluated, the Switch activity looks for a Case with a key that matches the result of the expression and if found, it schedules the activity associated with that Case.

While

The While activity executes it's Body while a Boolean Condition is True.

Parallel Execution

Parallel

Parallel activity allows parallel execution of its children. It operates by scheduling each WorkflowElement in its Branches collection at the beginning of its execution.  It completes when all of its Branches complete or when its CompletionCondition property evaluates to true.

ParallelForEach /  ParallelForEach<T>

The ParallelForEach activity enumerates the elements of a collection(Values) and executes an Activity for each element of the collection, in a similar way than the ForEach activity does. The main difference is that the embedded statement is executed in a parallel fashion.

Just like the Parallel Activity, ParallelForEach has a CompletionCondition, so that the ParallelForEach activity could complete early if the evaluation of the CompletionCondition returns true. The CompletionCondition is evaluated after each iteration is completed.

Error Handling

TryCatch

TryCatch activity is similar to the try..catch construct in C#: all activities in the Try block are executed and if an exception occurs, it will schedule the Catch block that best matches that exception (if no matching catch is found, the workflow is aborted). All Catch blocks are contained in a collection called Catches.

TryCatch activity also has a Finally block that is executed after the Try (and any eventual Catch).

A note on unhandled exceptions:

TryCatch provides exception handling at the workflow level. When an unhandled exception is thrown, the workflow is aborted and therefore the Finally block won’t be executed. This behavior is consistent with C#.

Catch<T>

Represents one catch block to be used in a TryCatch activity. If an exception is thrown within a Try Element, the TryCatch will attempt to find a matching Catch element based on the type of the thrown exception.

Catch<T> can only be used inside a TryCatch activity

Throw

Throw activity throws an exception within a workflow. Throw activity has an Exception property that contains the exception that will be thrown at execution time.

Utilities

Assign

The Assign activity assigns the value of its Value argument to its To argument.

The types of both arguments must be compatible. This compatibility is verified at runtime.

Delay

Delay Activity, as its name suggests, will block the current workflow execution path for a Duration specified by user. After the duration expires, the workflow continues execution as expected. The duration of the delay is set using a TimeSpan.

InvokeMethod / InvokeMethod<T>

InvokeMethod is the activity that allows you to call an existing CLR instance or static method. To invoke a method all you need to do is provide the owner of the method (TargetType for static methods, TargetObject for instance methods), the MethodName, and its Parameters.

InvokeMethod supports the following method invocation scenarios:

· Public instance and static methods

· Parameter passing by value and by reference

· Support for parameter arrays

· Support for generic parameters

· Asynchronous method invocation

WriteLine

Writes text to the configured output console.

Writing beyond the System.Console

WriteLine has a TextWriter argument can be configured to write to different outputs. For example, we can configure the TextWriter property to send the text to an ASP.NET page. If the TextWriter is not set, it will be set by default to the System Console.

Advanced (Cancellation, Compensation, Transactions, and Persistence)

CancellationScope

The CancellationScope activity consists of two main parts, the Body and the CancelHandler. The body is the code path that normally executes. If the activity gets canceled, then the cancel handler is called.

CompensatableActivity

CompensableActivity is used to define a potentially long running activity with accompanying Compensation and Confirmation logic.

Compensation allows the user to specify corrective action to be taken on an activity based upon activity which occurs after the successful completion of the Body of the activity.

Compensate

Compensate is used to explicitly invoke the compensation handler of a CompensableActivity.

Confirm

Confirm is used to explicitly invoke the confirmation handler of a CompensableActivity.

Persist

Persists the workflow instance. Persistence will be done using the configuration of the WorkflowInstance that is being executed (this activity doesn’t have any arguments).

TransactionScopeActivity

The TransactionScopeActivity provides the mechanism for initializing a new transaction, making the transaction handle ambient (a workflow execution property) and calling complete on the transaction once the Body of the TransactionScope activity has completed.

TransactionScopeActivity supports “Requires” semantics. If there is already an ambient transaction it is used, else a new one is created.

Nested transaction scopes:

TransactionScopeActivity can be nested in another TransactionScopeActivity. A TransactionScopeActivity nested in another TransactionScopeActivity will use the existing transaction.

Flowchart

Activity

Description

Flowchart

This is the root for a Flowchart. Since Flowchart is an activity like any other, it can be composed inside any container activity.

For example, we can add a Flowchart inside of a Sequence or a Flowchart inside another Flowchart.

The green ball in the image at the right represents the start node of the Flowchart.

FlowDecision

FlowDecision models conditional forks within a Flowchart. It can be seen as the equivalent of the procedural If activity in the Flowchart world.

This activity contains a Boolean expression Condition. If the expression evaluates to “True”, the true path is executed (otherwise, the false path is scheduled).

FlowSwitch

FlowSwitch activity selects a next node depending on the value of an expression. FlowSwitch can be seen as the equivalent of the procedural Switch activity in the Flowchart world.

Messaging

Activity

Description

Receive

Models one way receive of a message. It can receive data of the following types: Message, DataContract types, XmlSerializable types, and MessageContracts.

ReceiveAndSendReply

This activity template represents a correlated Receive activity and SendReply activity.

By using this template you can wait for an incoming message and then send a reply to the sender.

Since the Receive and the SendReply are inside a sequence, you can add any activity between them.

Send

Models one way send of a message. It can receive data of the following types: Message, DataContract types, XmlSerializable types, and MessageContracts.

This activity can be used in two ways:

1. Client: this activity can be used to send a request to a service. This is equivalent to a WCF client calling a service operation. No contract inference is performed on the client side.

2. On the server side the Send activity can be used to send a reply to a previous Receive. In this case the Send and Receive activities must have the same OperationName, Action and CorrelationHandle.

SendAndReceiveReply

This activity template represents a correlated Send activity and ReceiveReply activity.

By using this template you can send a message and then wait for a reply from the destination.

Since the Send and the ReceiveReply activities are inside a sequence, you can add any activity between them.

PowerShell

Activity

Description

InvokePowerShell

Invokes a PowerShell cmdlet that does not have a return value. InvokePowerShell can be used to invoke simple cmdlets and scripts. We can also pass parameters and input objects to the cmdlet. After execution, the activity provides a set of errors (if any occurred).

InvokePowerShell<T>

An activity that invokes and retrieves the resultant output from a PowerShell cmdlet. This flavor of the activity has all the same arguments than the non-generic version plus an InitializationAction.

The InitializationAction is used to map the results of the execution of the cmdlet to variables in our workflows.

Migration

Activity

Description

Interop

The Interop activity is a WF4 activity that wraps a WF3 activity (a non-abstract CLR type that derives from System.Workflow.ComponentModel.Activity) thus allowing the WF3 activity to be used in WF4 workflows.  Note that the WF3 activity can be a single leaf activity, or an entire compiled workflow (tree of activities).

The Interop activity bridges the WF4 and WF3 activity execution models, facilitates data flow across the interop boundary, and enables persistence and tracking of WF3 activity instances within WF4 workflow instances.

The Interop activity allows WF developers to move to the WF4 model in an incremental fashion:

· Quickly experiment with WF4 using existing WF3 activity artifacts

· Wrap WF3 activities the developer isn’t ready to redesign on the WF4 model

· Wrap WF3 activities for which the developer doesn’t own or possess the source code (e.g. they purchased the activity from a third party)

Overall this is quite an impressive list of activities when you consider the WF 3.5 came with a total of 30 out of the box activities. Missing are the event driven activities, code activity and web service activities to name a few.

Credits

  The descriptions in the beta documentation on MSDN are pretty weak. I was able to find  more complete descriptions on the .Net endpoint blog, which I’ve used because of the detail in descriptions.

Thursday, July 2, 2009

Visual Studio Magazine

Is now the number one most useless trade magazine published. It had been marginal at best up until it’s merger with Redmond Developer news, since the merger it has become utter garbage. The majority of the magazine is comprised of advertisements and very little in the way of articles. The commentary in articles is always that of a select group of perceived industry “heavy weights” who are in fact industry has-bens. These are the same people that crippled VB.Net from it’s inception and convinced hundreds of developers to stick with VB 6. Now the extol the virtues of the .Net framework and their pet technology in articles that are at best two pages long and absolutely worthless. All in an effort to keep relevant and sell you books and training.

If you’re considering a subscription to this magazine, do your self a favor and skip it.

Sunday, June 28, 2009

Windows Workflow Foundation 4.0 (Part 2 The Designer)

In part two of this series we’ll look at the project types available in Visual Studio 2010 and take look at the feature changes in the workflow designer.

Project Templates


There have been a number of changes in the available projects between WWF 3.5 and WWF 4.0. Below is a screen shot of the Visual Studio 2008 new Workflow project dialog.



As you can see in addition to the empty workflow project, there are several variations of the Sequential workflow and the State machine workflow. These variations include SharePoint 2007, library and console workflow applications. All of these workflows are built on designer functionality that has been available in Visual Studio since Visual Studio .Net was released in 2002.

The Visual Studio 2010 new Workflow project dialog contains a lot less clutter, some new project types and some that are missing. There may potentially be more project types available upon release, but for now we’ll concentrate on what’s available in beta 1. Below is a screen shot of the Visual Studio 2010 new Workflow project dialog.



The projects listed in the new project dialog are Activity Designer Library, Activity Library, Flowchart workflow console application and the Sequential workflow console application. All of the projects in the dialog are new for workflow with the exception of the Sequential workflow, missing is the State Machine workflow. All of the workflows in the WWF 4.0 are based on xaml or extensible markup language. This is the same technology that is used in WPF and Silverlight just to name a few.


Here is a quick overview of the project templates that are available in Visual Studio 2010.

The Activity Designer Library template provides a way to create a user interface for a custom or standard activity.

The Activity Library template provides a way to create custom activities visually.

The Sequential template creates a workflow that executes activities in sequence, one after another.

The Flowchart template creates a workflow that executes activities one after another, but allows the flow to return to an earlier step. This template replaces the State Machine workflow and is much more flexible.

Workflow Designers

There is a visual difference between the new Workflow designer and the Visual Studio 2008 designer. Below is the Visual Studio 2008 designer for a sequential workflow.


Below is the Visual Studio 2010 designer with a sequential workflow opened up.


The Visual Studio 2010 designer has some noticeable changes from the previous designer in that now, rather than creating variables and arguments in code, the designer now provides facilities for creating them from the designer.


When defining arguments from the argument window, you provide a name, type, default value and a direction. Valid directions are In, Out, In/Out and property. We’ll discuss these later after we discuss the available Out of the box activities and start to build a work flow.

Variables are much like arguments in definition except that instead of defining the direction we define the scope of the variable.

Navigation to activities and child activities is provided via bread crumbs. This was a feature of the State Machine workflows in WWF 3.5 that has carried over into WWF 4.0. The bread crumb navigation makes it easy to drill into the activities in a workflow to set the properties.

Overall the Workflow designer in Visual Studio 2010 is an evolution of the designer in Visual Studio 2008. Variable and Argument dialogs go a long way toward reducing the coding chores. And bread crumb navigation makes moving within activities and child activities a breeze. In the Next part we’ll look at the huge list of Out of the box activities.

Sunday, June 21, 2009

Windows Workflow Foundation 4.0 (Part 1)

Windows Workflow Foundation (WWF) has undergone a radical face lift in the .Net 4.0 framework. This face lift includes new out of the box activities, the designer, workflow types and persistence to name a few of the changes.

  WWF was first released as part of the .Net 3.0 framework and version 2 was released with the .Net 3.5 framework. While most successful among ISV’s (Independent Software Vendors), it hasn’t really taken hold with enterprise. WWF 4.0 is intended to change that and make a core part of every developers toolbox much like the way WCF has become the defacto communications technology in the .Net framework.

As with any beta release, documentation is nearly non existent. So with that in mind I’m going to break this down into a series of articles on WWF 4.0, learning what’s new and sharing my discoveries along the way.

Over the next several articles I intend to cover a lot of ground. I’ll spend time discovering and discussing the following topics

  • Designer changes – What’s new in the designer
  • Workflow types – New workflow types and what’s gone
  • Out of the Box Activities – New activities and what they provide
  • Custom Activities = How to create custom activities in WWF 4.0
  • Workflow Activation – Activating workflows from ASP.Net and Windows applications
  • Hosting – The new “Dublin” IIS hosting capabilities
  • Persistence – The WWF 4.0 persistence model

Thursday, June 18, 2009

Entity Framework V2 and POCO

There is a rally good series of post at the ADO.Net team blog covering POCO (Plain Old CLR Objects). They cover enhancements such as Lazy loading, Change Tracking and best practices.

If you’re planning to use the Entity Framework or poking around at the beta, this series provides some good background and guidance.

VS 2010 MVC 1.1

The latest update for ASP.Net MVC  is available here for Visual Studio 2010 beta 1.

The App that cried wolf

We’ve all read the story about the little boy who cried wolf. Time and again he cried wolf and one day when there was a real wolf no one listened.

Applications that send emails for error after error are a lot like the boy in the story. At first we investigate each error and try to come up with corrective measures to eliminate the issue, but eventually we just create a junk mail filter and simply ignore them.

So what is the root cause of the wolf app? The primary cause lies in how we define and handle exceptions. Exceptions are just that, exceptional cases that we hadn’t specifically planned for. We know during design and implementation that the potential exists for an exception. For example we may read a file and that file may be corrupt.   But the way that it is usually handled is by throwing it up the chain and eventually the whole app screeches to a halt and the spam machine kicks into overdrive.

Since we already know the potential for an exception exists in a particular piece of code, we should handle it where it happens and degrade gracefully. Additionally not every error or exception should be the subject of an email. Errors should be classified and dealt with accordingly. For many errors this means logging to a file or a database for later review. Many times the logs will show a pattern of problematic methods that continually raise the same errors. These can then be prioritized for rework during a maintenance cycle. Critical errors on the other hand should be identified by an email or an entry in the application event log. These critical errors should be dealt with immediately because the have a direct correlation to the up time of the application.

By taking some time to plan and design the way in which errors and exceptions are dealt with could mean the difference between delivering an app that cries wolf or one that matures of the course of time.

Saturday, June 6, 2009

Blog coding

I’ve recently noticed a new trend in coding that I find troublesome. I’ll call it Blog Coding. Blog coding is a condition where programmer X doesn’t know how to implement a certain technology or needs to solve a real or perceived issue, searches for answers by typing phrases in (insert your favorite search engine) and then spending hours reading through the results.

More often than not the code found in blogs is designed to solve a particular problem the author has encountered in his/her domain and may only provide a partial solution to the problem faced by the blog coder. Even more common, the samples are text book style code snippets that really don’t apply to real world issues at all. But the blog coder will diligently work with various samples and snippets combining code from multiple blogs to create a Frankenstein solution. The solution may or may not work or it may work on the blog coders local machine. When confronted for an explanation of how the code works or why it was written a certain way (you can always spot blog coder code by the variation in coding styles present in single methods or classes).

So how do we as developers help eliminate blog coding? The first and most important thing to do is to encourage fellow programmers take the time to learn the tools and frameworks that we work with. Managers should insure learning time is set aside during the work week. Write some code! Nothing is better for learning than writing some real working code. If all else fails, post a question on a programming specific Q&A site like Stackoverflow.

Sunday, May 31, 2009

Visual Studio 2010 IDE

I’ve now had a little over a week to play with the beta of Visual studio 2010. Overall I think the improvements are a step in the right direction. I like the new WPF editor, although it seems sluggish in the beta, I hope that Microsoft will address it before release.

One of the nicest IDE enhancements is the Call Hierarchy browser. This window allows you to see all of the calls in and out of a method. It’s definitely helpful during refactoring and debugging.



Another interesting window I stumbled upon is the debug history window. The debug history window gives you a view of calls made made during debugging.



The biggest issue I think in the near term will be with third party vendors since the underlying visual studio extension API has been completely changed. I know that Code Rush will not work and according to a post in their forum, it will be a total rewrite to get it working in VS2010. So it will be some time before we see third party vendor offerings for Visual Studio.

Thursday, May 14, 2009

Visual Studio 2010

On Monday, May 18th, Visual Studio 2010 Beta 1 (Professional, Suite and Team Foundation Server) will be available to MSDN Subscribers through MSDN Subscriber Downloads and to the general public on Wednesday, May 20th through Microsoft Downloads.

Saturday, May 9, 2009

Windows 7 XP Mode supported processors

There has been a lot of discussion surrounding the Intel chipsets that support XP Mode. Essentially the CPU must support hardware virtualization. There are several ways to see if your CPU supports hardware virtualization, the easiest way I’ve found is the Intel CPU ID Utility, which you can grab from here. After installing and running the utility you’ll have no doubts a to whether your CPU supports hardware virtualization.

Thursday, May 7, 2009

WCF and WWF 4.0

I’m really looking forward to getting my hands on the beta of Visual Studio 2010, which I hope they’ll release during Tech-Ed in LA this month. In the meantime I ran across this post on Cliff Simpkins blog about the upcoming features.

The workflow service host’s durable delay functionality is a great feature. Currently this is nearly impossible to implement out of the box with WWF 3.5. I really needed this on a recent project and ended up rolling a different solution. May be time to revisit it  when the beta is released.

The WCF routing is another interesting feature. Rather than have dozens of services hosted you can use a single routing service to filter and route messages to the correct service.

Although I won’t be able to attend tech-ed this year I’ll be closely watching for the beta release.

Windows 7 XP Mode Follow Up

Well Windows 2008 works just fine with Windows 7 Virtual PC. The integration components installed and worked fine. Although that was not the case with Windows 2003, it’s not listed as supported so no big deal.

I did encounter a blue screen when connecting to an external USB drive, but I wasn’t able to make it happen a second time.

So far so good…

Wednesday, May 6, 2009

Windows 7 XP Mode

I’ve just got done installing the Windows 7 XP Mode updates. This appears to be more than windows in windows, more like a supped up Virtual PC. I configured it as per the instructions on the Windows 7 site and it started XP as advertised. I attempted to add a Windows 2003 virtual machine, which was fine until I tried to add the integration features. The integration features do not play well on Windows 2003. Issues included corrupt graphics, a max resolution of 1027x 768 and failure to install drivers. To be honest though the setup clearly states Window XP, Vista and Windows 7 are the only supported OS’s.

Right now I’m trying a Windows 2008 virtual machine, we’ll see how that goes. At least initially it seems to be installing without problem. I’d really like to see this work, from a dev standpoint it would be nice to have an integrated Virtual PC given the torrent of CTP’s and beta’s coming out of Redmond these days. I’ll post my luck (or lack of) with Windows 2008.

Saturday, April 25, 2009

Scrum and Stand ups

My organization is currently using Scrum as a development methodology. We recently increased the sprint length to 4 weeks which seems to be a little better than 2 or 3 weeks, but one of the nagging points, for me at least, is the daily standup. Every day we get together and and discuss backlog items and tasks worked on the previous day. The meeting invariably digresses into details or discussions that don’t really pertain to the status or “look at the cool thing I did”. 

As I was listening  to Patrick Hynds discuss Why projects fail on the .Net Rocks podcast, it occurred to me that he had some valid points on tracking status and more over those principals could be applied directly to the daily standup. The general point of the daily standup is to know where you are in relation to the project schedule and what is getting in the way of the schedule. Pat’s status points where:

  1. What Task/Tasks did you work on yesterday?
  2. What Task/Tasks did you work on yesterday that were not part of a backlog?
  3. What do you plan to work on today?
  4. What Roadblocks do you have?

These questions should be answered without any additional details or ego pumping. The second question is one we don’t ask in our stand-ups, but it occurs on a daily basis and should be addressed. It definitely distracts from the planned backlog items and has a huge impact on what’s accomplished during a sprint.

Using this question format during the standup should allow us to better gauge were we are and what distractions are keeping us from achieving our sprint objectives.

Tuesday, April 21, 2009

Visual Studio 2010 Enhancements for ASP.NET

Mike Ormond posted a piece on the ASP.Net enhancements in Visual Studio 2010.  Web design snippets are cool, but the web.config transformations are huge. It will be a lot easier too deploy to different environments. I hope we’ll see beta 1 around the Tech Ed timeframe in mid May, for now you can read the entire article here

Sunday, April 12, 2009

Lambda Expressions as methods

Many of the Lambda expressions samples demonstrate Selects and Order By but I recently discovered the ability of Lambda expressions to be used as delegate methods. You can use Func<T> for methods that return a result which provides a very concise shorthand notation. In addition to Func<T> you can use Action<T> and Predicate<T>

Here is an example that uses Func<T,TResult> to add two numbers together

// Lambda Function that adds two numbers
Func<int, int, int> add = (int val1, int val2) => val1 + val2;

// add 200 and 100
Console.WriteLine(add(200, 100));



In this case the Func<int, int,int> indicates that the method takes two integers and returns an integer.



Action<T> allows you to capture behavior:



// Action<T> to echo input
Action<string> echo = (s) => Console.WriteLine(s);

// invoke echo
echo("Hello");


Predicate<T> allows you to filter:



// Create fibonacci sequence
List<int> fi = new List<int>();
fi.AddRange(new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 });

// select the matches
Predicate<int> matches = num => num % 2 == 1;
var odd = fi.FindAll(matches);

// use array Foreach<T> to display the results
Array.ForEach<int>(odd.ToArray(),x=>Console.WriteLine(x));


In the example above I use Array.ForEach<T> to display the results instead of a foreach loop.



You can download the sample code here.




Friday, February 13, 2009

Source Control Follow up

It’s been about 3 1/2 months since I made the switch to Source Gear Vault as my primary home source control. In the time that I’ve been using it it has performed superbly.  I recently did an upgrade, simple, quick and painless. All totaled it took probably ten minutes to upgrade the server using a single setup executable. Contrast that to the day it took a co-worker to upgrade subversion and the fact that he had to compile the  new server GUI functionality and it quickly becomes apparent that subversion is more of a road block than an asset.

A couple of weeks ago I ran across this Source Control How To by Eric Sink, one of the Source Gear Co-Founders. Even if you’re a source control expert it’s a good read.

Sunday, February 8, 2009

LINQ to DataSets

There are tons of LINQ 2 SQL and LINQ to object examples out there but not many LINQ 2 DataSet examples. Here is a quick sample that creates a table, adds three rows and queries the rows.

The key parts of the query are casting the table as enumerable using the AsEnumerable() extension and the generic Field<T>() method.

 

   1: static void Main(string[] args)
   2:       {
   3:           // create a table with three columns
   4:           DataTable table = new DataTable();
   5:           table.Columns.Add(new DataColumn("ID", typeof(System.Int32)));
   6:           table.Columns.Add(new DataColumn("ContactName", typeof(System.String)));
   7:           table.Columns.Add(new DataColumn("CompanyName", typeof(System.String)));
   8:  
   9:           // add three rows
  10:           DataRow row = table.NewRow();
  11:           row["ID"] = 1;
  12:           row["ContactName"] = "James Smith";
  13:           row["CompanyName"] = "Petes Hardware";
  14:           table.Rows.Add(row);
  15:  
  16:           DataRow row2 = table.NewRow();
  17:           row2["ID"] = 2;
  18:           row2["ContactName"] = "Jon Jones";
  19:           row2["CompanyName"] = "Rodgers Travel";
  20:           table.Rows.Add(row2);
  21:  
  22:           DataRow row3 = table.NewRow();
  23:           row3["ID"] = 3;
  24:           row3["ContactName"] = "Jeff Jones";
  25:           row3["CompanyName"] = "Rodgers Travel";
  26:           table.Rows.Add(row3);
  27:  
  28:           // create a data set, not needed but it's more common
  29:           DataSet dataSet = new DataSet();
  30:           // add the table
  31:           dataSet.Tables.Add(table);
  32:  
  33:           // get the jones brothers
  34:           var jones = (from r in dataSet.Tables[0].AsEnumerable()
  35:                        where r.Field<string>("ContactName").Contains("Jones")
  36:                        select r).ToList();
  37:  
  38:           // list the results
  39:           foreach (var item in jones)
  40:           {
  41:               Console.WriteLine(String.Format("Found {0} working for {1}",
  42:                   item.Field<string>("ContactName").ToString(),
  43:                   item.Field<string>("CompanyName").ToString()));
  44:           }
  45:  
  46:           Console.Read();
  47:       }