The mysteries of software development and networking... RSS 2.0



 Saturday, May 10, 2008

I just wasted some of my time figuring out how to do collection initialization in VB9.

C#3.0 has a new feature called collection initializer and according to a (somewhat older) post by Scott Guthrie, VB9 was slated to have it too. I guess it got cut somewhere.

Anyway this is what collection initializers look like in C#3.0:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

The closest thing in VB9 would be to use array initializers:

Dim numbers As New List(Of Integer)

Dim temp() As Integer = {1, 2, 3, 4, 5}

numbers.AddRange(temp)

Saturday, May 10, 2008 9:22:46 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | VB.NET
 Friday, May 09, 2008

Okay, so you read the title of this post. Perhaps you're expecting huge amounts of code, but guess what. As it turns out, this is so ridiculously easy. This will be a very short post.

Step one is to have a method that loads an RSS feed. WCF offers a new class called SyndicationFeed.

private SyndicationFeed Load( string url )

{

  XmlReader reader = XmlReader.Create( url );

  SyndicationFeed feed = SyndicationFeed.Load( reader );

  return feed;

}

 

The above method will take a url and use to load a feed. Now suppose I have a list of urls and I want to take all the items in all the feeds, sort them and use them to generate a new, aggregated feed. Sounds like a fair amount of work, right.

Here is the code:

 

private SyndicationFeed Aggregate( List<string> urls )

{

  var items = from url in urls

              from item in Load( url ).Items

              orderby item.PublishDate descending

              select item;

 

  SyndicationFeed feed = new SyndicationFeed( items );

  return feed;

}

 

Cool!

Friday, May 09, 2008 11:10:19 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | LINQ | WCF

Heroes Happen in Bangor! The BAND is proud to announce we will be putting on a mini-launch event for Microsoft's Heroes Happen Here launch of the 2008 products.  Come to the event at Kominsky Hall at Husson College in Bangor on Tuesday, May 27 at 6:00 pm.

Greg Howe and Jeff Hall, BAND co-leaders, will be talking about Visual Studio 2008 and how it will impact your development efforts.  There will be two 45-minute talks, one focusing on the web world, and one focusing on the IDE.  You will leave this event knowing how you can benefit from the new products, including Windows Sever 2008 and SQL Server 2008.

More info here.

Friday, May 09, 2008 10:42:09 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
General
 Tuesday, May 06, 2008

My blog runs on dasBlog version 2.x and when I started blogging I did all my typing online. Then Office 2007 came along and Word offered the feature of creating a blog entry offline and then upload it to dasBlog using the MovableType API.

This wasn't too great though, since Word markup would end up in the HTML and sometimes the publish process just froze or refused to logon to my web site. Also, uploading pictures was kind of a hack.

Last week I installed Windows Live Writer and this runs as a charm. Definitely a recommendation!

Tuesday, May 06, 2008 12:23:49 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
General

A new quiz on www.justsayhi.com says I'm:

69% Geek
Tuesday, May 06, 2008 12:16:27 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -

I heard about Live Mesh last week and decided to check it out. So I’ve signed up for Live Mesh beta program and it is pretty neat, but still fairly simple. I’ve not (yet) been accepted into the Mesh Developer beta, which is a separate program. As I understand it Live Mesh will allow you to not just share files, but Silverlight applications as well.

 

Current state of Live Mesh

Live Mesh allows you to turn a folder on your machine into a Mesh Folder. This in turn allows you to automatically share the folder across multiple devices. Every account has one default device: the Mesh Live Desktop, an online desktop which acts like a Windows desktop.

Mesh Folders can be shared with any Live Messenger contact. Each Mesh folder will track all changes and allows collaboration my attaching messages to the folder.

 

Picture of Live Mesh Desktop, I've shared the Develop-One folder which sits on my laptop. It shows up as a folder on my Live Mesh desktop.

 

clip_image002

 

Device support will include Windows Mobile and Mac!

 

clip_image004

 

For anyone that knows Office Groove, it'll be interesting to see how the final version of Live Mesh and Groove compare.

Tuesday, May 06, 2008 12:14:11 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -

 Friday, May 02, 2008

An important part of LINQ and C# 3.0 is the concept of deferred execution. What does this mean?

Let's have a look at the following code:

static void Main( string[] args )
{
   List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   var evenNumbers = numbers.Select( x => ( x % 2 == 0 ) );
 

   foreach ( int i in evenNumbers )
   {
     if ( i == 6 )
         numbers.Add( 12 ); // add a number to the list of numbers
     Console.WriteLine( i );
   }
   Console.ReadLine();
}

public static List<int> Select( this List<int> numbers, Filter filter )
{
   List<int> result = new List<int>();
   foreach ( int i in numbers )
   {
      // call the filter method/delegate to see if this
      // number needs to be in the result
      if ( filter( i ) == true )
      {
         // if i matches the filter then add it to the result
         result.Add( i );
      }
   }
   return result;
}

In the code above the extension method 'Select' will apply a filter and return a subset of the original collection of numbers. When the numbers are printed we add the number '12' to the original collection. Since the Select method created a new collection with the subset we will not see the number 12 being printed to the console. If we want a more dynamic interaction we can rewrite the Select method to return an enumerator rather than a List.

public static IEnumerable<int> Select( this List<int> numbers, Filter filter )
{
    for ( int n = 0; n < numbers.Count; n++ )
    {
        if ( filter( numbers[n] ) == true )
        {
            // if numbers[n] matches the filter then yield the value
            yield return numbers[n];
        }
    }
}

The code above shows that instead of returning a List of numbers we now yield the value of each number as it passes through the filter. Now when we run the same Main we will see that the value '12' is included in our output.  If we put a breakpoint inside the application we can inspect the type of 'evenNumbers'.

As you can see it point to the Select methods and the Lambda has been compiled into an anonymous delegate. Rather than having a fixed result the Select method keeps being called until there are no more numbers being 'yielded'. You can preview the results by opening the 'Results View', but that will only provide a view of the iterator at that specific point in time.

Friday, May 02, 2008 1:33:43 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#

There are three key things that you need to understand in order to understand Lambda expressions in C#3.0.

1. Delegates,
2. Delegates,
3. ... delegates.

Since Lambda has come to town (or C#) I've discovered that a lot of people use delegates, but quite a few developers don't really know what a delegate is.
Understanding delegates is key to understanding what Lambdas are.

Wikipedia has the following definition:
A delegate is a form of type-safe function pointer used by the .NET Framework.  Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners.

Here is my rule of thumb definition:
A delegate definition is a signature description for a method. 

It helps me to think of it as an interface definition for methods. An interface defines a number of methods, properties and/or events that need to be implemented by a class. You can use an interface definition as a type for a parameter in a method. Similarly a delegate definition defines the return type and parameters that a method needs to 'implement' (match is a better word). And a delegate can also be used as a type for a parameter in a method.

Still a lot of mumbo jumbo?
Okay, let’s take the journey from ‘traditional’ programming to C#3.0 syntax.

Consider the following program. Traditionally if you wanted to select a subset from a collection you would iterate over the collection and copy the items you're interested in into a new collection.

static void Main(string[] args)
{
    List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    List<int> evenNumbers = GetEvenNumbers( numbers );
    foreach ( int i in evenNumbers )
    {
        Console.WriteLine( i );
    }
    Console.ReadLine();
}

static List<int> GetEvenNumbers( List<int> numbers )
{
    List<int> result = new List<int>();
    foreach ( int i in numbers )
    {
        if ( i % 2 == 0 )
        {
            // if i matches the filter then add it to the result
            result.Add( i );
        }
    }
    return result;
}

The above code will select all the even numbers and print them to the console. Just a foreach and no delegates yet.

Instead of implementing a 'GetEvenNumbers' method, lets create a generic Select method. The method will be generic and will loop over the numbers and select only those which are selected by a filter. But how to define the filter? Lets first look at what we want our Select method to look like:

static List<int> Select( List<int> numbers, Filter filter )
{
    List<int> result = new List<int>();

    foreach ( int i in numbers )
    {
        // call the filter method/delegate to see if this
        // number needs to be in the result
        if ( filter( i ) == true )
        {
            // if i matches the filter then add it to the result
            result.Add( i );
        }
    }
    return result;
}

We want to create a method which takes a reference to another method as a parameter. This is what is known as a delegate. In our case the delegate needs to be a method which takes an Int32 as a parameter and returns a Boolean. In C# the delegate is defined using the 'delegate' keyword:

delegate bool Filter( int x );

Now, any method that takes an Integer as a parameter and returns a Boolean matches this delegate. So both methods shown below match the delegate:

static public bool IsEvenNumber( int number )
{
    return ( number % 2 == 0 );
}

 private bool IsOddNumber( int z )
{
    return ( z % 2 == 0 );
}

Notice that the name of the method does not matter, nor does the name of the parameter, nor does the accessibility of the method. Types of the parameter(s) and the return type is all that matters when it comes to matching with the delegate.

We can now rewrite Main to use the Select method:

static void Main( string[] args )
{
    List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
     List<int> evenNumbers = Select( numbers, IsEvenNumber ); 

    foreach ( int i in evenNumbers )
    {
        Console.WriteLine( i );
    }
    Console.ReadLine();
}

In C# 3.0 it has become easier to create a delegate, all you need to do is provide the name of the method, the compiler infers that you wish to create a delegate.

The old syntax was:

static void Main( string[] args )
{
    List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    List<int> evenNumbers = Select( numbers, new Filter( IsEvenNumber ) );

    foreach ( int i in evenNumbers )
    {
        Console.WriteLine( i );
    }
    Console.ReadLine();
}

The syntax is shorter, and arguably more readable, but hides the fact that a delegate is in fact an object and not just a reference as the new syntax seems to suggest.

Ok, now our IsEvenNumber method is quite simple, right? So to create a whole method for that method, which will likely never be reused is a little much. This is where anonymous delegates come in. Rather than specify a method which matches the delegate we can create an anonymous delegate which also matches with the Filter delegate.

Consider the following code:

static void Main( string[] args )
{
    List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    List<int> evenNumbers = Select( numbers, delegate( int x ) { return ( x % 2 == 0 ); } );

    foreach ( int i in evenNumbers )
    {
        Console.WriteLine( i );
    }
    Console.ReadLine();
}

The reference to IsEvenNumber has now been replaced by the creation of an anonymous delegate. The creation and implementation of the delegate is all done in a single line.

You'll probably agree that this does not do much for readability.

Remember how I started this blog post? Lambdas are delegates. So let’s replace the delegate with a lambda.

static void Main( string[] args )
{
    List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    List<int> evenNumbers = Select( numbers, ( x => ( x % 2 == 0 ) ) );

    foreach ( int i in evenNumbers )
    {
        Console.WriteLine( i );
    }
    Console.ReadLine();
}

So what is happening here? Let’s look at the Lambda:

x => ( x % 2 == 0 )

We are expressing that there is an input 'x' which we want to mod by two. Since this Lambda expression is only a single line the return statement is implied and automatically applied to the last statement, most Lambda expressions contain only one line of code, but any number is possible. If you want more that one line you need to use the { } to denote the scope of the block and use the return statement (if your delegate return anything other than void).
If we were to change the expression to:

x => ( x % 2 )

Then the result of the Lambda would be a integer and the code would not compile since the return type Int32 does not match with the Filter delegate.
There is quite a bit of 'magic' going on for the compiler to decide which delegate the Lambda maps onto, the intellisense will help you, because (in this sample) it will know that 'x' is of type Int32.

So to summarize:
Lambdas are a concise notation for defining delegates.

 

 

 

 

Friday, May 02, 2008 9:55:30 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
C#
 Thursday, April 24, 2008

I'm currently doing some work with MapQuest and ran into the situation that I need to define styles for point of interest. From a code point of view I would like an enumeration, but the MapQuest API defines a series of strings to specify the style you wish to use. With C#3.0 I can now add a method to an enumeration using an extension method.

The sample below shows an enumeration for stars and an extension method for getting the value of that enumeration as a string:

public enum Stars : int
{
    Red = 31,
    Green = 32,
    Blue = 33,
    Yellow = 34,
    Orange = 35,
    Purple = 36,
    White = 37,
    Black = 38,
    Gray = 39,
    Gold = 40
}

public static class StarsExtension
{
    public static string Value( this Stars enumerator )
    {
        int v = (int) enumerator;
        return "MQ000" + v.ToString();
    }
}

I can now use this as follows:

string s = Stars.Gold.Value();

Thursday, April 24, 2008 11:11:49 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
AOL | C#
 Wednesday, April 23, 2008

Array conversion, or reshaping of objects, seems like a cool thing to do with LINQ and C# 3.0.
I've played around a little with the following:

sbyte[] imageBytes = GetImage();

// convert using extension method / Lambda syntax 
byte[] y = imageBytes.Select( s => (byte) s ).ToArray();

// convert using LINQ syntax
byte[] x = ( from b in imageBytes select (byte) b).ToArray() ;

// convert using the Cast extension method
byte[] z = imageBytes.Cast<byte>().ToArray();

So what is the difference? Actually approach 1 and 2 lead to the same IL.
The Cast method works quite different and in my case I got an exception from approach 3 saying the sbyte would not fit in the byte.

But of course LINQ is not needed for this simple conversion:

// convert by casting to array to byte[]
byte[] bytes = (byte[])(Array)imageBytes;

I did a quick perf check and the last option is 500 to 800 times faster.

 

Wednesday, April 23, 2008 11:10:52 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#
 Monday, April 21, 2008

The Maine Developer Network is hosting a Geek Lunch tomorrow at the State of Maine, Harlow Building at 18 Elkins Ave in Augusta.
Chris Bowen will be presenting on LINQ & Language Improvements in C# 3.0/VB 9.
Sign up here.

LINQ (Language Integrated Query) is a unified approach for querying data using coding syntax that remains consistent regardless of the data source. It WILL change the way you work as a developer and architect and this session will help you on your way to using it effectively. To understand how LINQ works, we'll first navigate the new features of C# 3.0 and VB 9.0 that enable LINQ functionality. Then, we'll dive into .NET 3.5 and Visual Studio 2008 to explore the various realms of LINQ: Datasets, XML, Database/SQL, in-memory objects, and more. By the end of this session, you'll have a solid understanding of how LINQ works and what it can do for your applications.

Monday, April 21, 2008 8:50:10 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | General | LINQ
 Wednesday, April 09, 2008

Background: Assume we have workflow which is hosted as a WCF service. Every workflow instance is identified by the workflow instanceId. When a remote call comes into the workflow runtime the runtime needs to identify which workflow instance the caller wants to communicate with. If no identification is provided the runtime will assume a new workflow instance needs to be created.

Consider the following piece of client side code which calls a workflow service called FirstOperation() which is handled by a ReceiveActivity on the server:

ClientProxy proxy = new ClientProxy();
proxy.Open();
proxy.FirstOperation(); //creates a new workflow
proxy.Close();

Now assume a second call needs to be made and the second call needs to be handled by the same workflow because in this workflow there is second ReceiveActivity waiting for the SecondOperation to be called.
The following piece of code will do just that:

ClientProxy proxy = new ClientProxy();
proxy.Open();
proxy.FirstOperation(); //creates a new workflow
//.. more code, keep the WCF channel open
proxy.SecondOperation();
proxy.Close();

The above code will work because the ReceiveActivity in combination with the WorkflowServiceHost automatically adds information to the WCF context. The instanceId of the workflow has been added to the context. The above code is bad design. The connection to the server is a valuable resource and should be closed as soon as possible. The following code snippet show how the context manager is used to retrieve the context from the call which initiates the workflow and is then reused when a new client proxy is created.

ClientProxy proxy = new ClientProxy();
proxy.Open();
proxy.FirstOperation(); //creates a new workflow
IContextManager manager = proxy.InnerChannel.GetProperty();
IDictionary context = manager.GetContext();
proxy.Close();

//.. more code, the WCF channel is now closed

proxy = new ClientProxy();
IContextManager manager = proxy.InnerChannel.GetProperty();
manager.SetContext(context);
proxy.SecondOperation();
proxy.Close();

The IContextManager has been added in .NET 3.5 to help with correlation. The code needed in .NET 3.0 to achieve the similar functionality is much less elegant.

Note 1: Server side both the ReceiveActivity as well as the SendActivity have a Context property allowing for easy access to the context. A common pattern for implementing a callback is to set the context of the SendActivity to the value of the context of the ReceiveActivity. In the scenario illustrated above the context would consist of just the instanceId. In scenarios where the workflow is using send and receive activities within a parallel activity the context will automatically get extended to include a conversationId, allowing the WorkflowServiceHost to correlate an incoming call to the correct receive activity.

Note 2: If you want manually add the instanceId to a context, have a look at this post by Maurice de Beijer.


Wednesday, April 09, 2008 1:59:06 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
WF
 Monday, April 07, 2008

The Boston Code Camp 9 is over and done with. It was a great two day event and kudos to Chris, Chris and all the presenters that put their time and effort into making this an excellent happening!

Here are the two presentations from the session that I did:

04-06-2008 CC9 - Building a State Machine Workflow.zip (231.61 KB)
04-06-2008 CC9 - Building applications with logic.zip (1.78 MB)
Monday, April 07, 2008 10:20:18 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Architecture | C# | General | WF
 Tuesday, April 01, 2008

If you're interested in playing around and testing VSTS 2008 and TFS 2008, but don't want to waste too much time getting the software installed? Good news! The trial Virtual PC images have been updated! Download your play area right here.

The image will not expire until December 31st 2008.

"This virtual machine is running Windows Server 2003 Enterprise Edition, SP2. It contains a full installation of Team Foundation Server 2008, Team Build 2008, Team Explorer 2008, Visual Studio Team System 2008 Team Suite and all necessary prerequisites. In addition, it has been updated with Office 2007 SP1, current Windows Updates as of March 25, 2008, and the December Release of the TFS Power Tools. Team Foundation Server is installed in workgroup authentication mode and thus does not require a domain controller. "

Tuesday, April 01, 2008 11:48:24 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Team System

The Bangor Area .NET Developers are meeting tonight at the Hampton Inn, Bangor (directions).

Converting VB6 Apps to .NET – Eric Burdo

You feel stuck in VB6 land...there is all this .NET stuff people are talking about.  You know you want to get there, but what does it take?  Eric will show you!  Come learn how to make the jump from VB6 to .NET and find out some of the pros and cons to converting your older apps.

Plus there's a random drawing for your own wireless desktop (keyboard and mouse), among other cool door prizes!

If you haven't done so already: Register For This Gig.

Tuesday, April 01, 2008 9:39:15 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
General

Today is a good day for a laugh... I love this one.

:-)

Tuesday, April 01, 2008 9:21:48 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
General | Team System
 Friday, March 28, 2008

Chris just posted the schedule for Boston Code Camp 9!

Go to: http://blogs.msdn.com/cbowen/archive/2008/03/28/code-camp-9-the-schedule.aspx.

See you next week!

Friday, March 28, 2008 11:26:28 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
General
 Thursday, March 27, 2008

I've blogged before about the availability of design specs on the next version of Visual Studio Team System. Well, another group of Rosario specs have been recently published on the Rosario Specs website:

 

·         TFS Bug Submission Portal

·         Send Mail from TFS

·         Work Item Tracking Linking

  

If you feel like participating visit the spec discussion forum.

Thursday, March 27, 2008 1:34:06 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Team System

Since I was looking at books today anyway I thought I'd research what is available C# 3.0, I haven't read any of these yet, but check them out:

Thursday, March 27, 2008 12:34:28 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | LINQ

A friend of mine asked me about what book I'd recommend for learning Windows Communication Foundation.

I've read 'Learning WCF' from Michele Leroux Bustamante and think it's great and I still use it as reference material.

Thursday, March 27, 2008 10:40:50 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
WCF
About
This blog is run by Mark Blomsma.
© Copyright 2008
Develop-One
Sign In
Statistics
Total Posts: 305
This Year: 49
This Month: 2
This Week: 1
Comments: 36
All Content © 2008, Develop-One
DasBlog theme 'Business' created by Christoph De Baene (delarou)