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



 Friday, August 01, 2008

If you're using the xsd.exe tool to generate C# code from an XML Schema you'll find that an attribute defined as an integer is generated into a string field.

The reason is listed on MSDN:

The xs:integer type is specified as a number with no upper or lower bound on its size. For this reason, neither XML serialization nor validation map it to the System.Int32 type. Instead, XML serialization maps the xs:integer to a string while validation maps it to the Decimal type that is much larger than any of the integer types in the .NET Framework.

Friday, August 01, 2008 6:52:45 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#
 Wednesday, June 11, 2008

My article on combining AIM Call Out with geocoding a phone number to display the location of the person you're trying to call has gone live on the AOL Developer Network.

I think it turned into a very cool sample application.

Dial a number and see the location of the person you're calling!

Wednesday, June 11, 2008 10:56:10 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | AOL | C#
 Wednesday, May 21, 2008

Anyone familiar with building applications using .NET Remoting (in .NET 2.0) knows that the DataSet and DataTable classes have a property called RemotingFormat. This could be set to either XML or Binary where Binary would give you a performance boost since it is more compact.

Windows Communication Foundation does not use this property at all. The service binding dictates the serialization format, no matter what you set the RemotingFormat property to be, even if your using a NetHttpBinding.

The following configuration will setup a service to use .NET Binary formatting over Http:

<system.serviceModel>
  <bindings>
    <customBinding>
      <binding name="NetHttpBinding">
        <reliableSession />
        <compositeDuplex />
        <oneWay  />
        <binaryMessageEncoding  />
        <httpTransport />
      </binding>
    </customBinding>
  </bindings>
  <services>
    <service behaviorConfiguration="ServiceBehavior" name="MyService">
      <endpoint address="" binding="customBinding"
        bindingConfiguration="NetHttpBinding" name="HttpBinding" contract="IService" />
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior name="ServiceBehavior">
        <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
        <serviceMetadata httpGetEnabled="true"/>
        <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

So even if your service looks something like this:

public DataSet GetData()
{
    DataSet ds = BuildDataSet();   // retrieve some data here
    ds.RemotingFormat = SerializationFormat.Xml;
    return ds;
}

The DataSet will still get serialized as a .NET binary as defined in the binding ('binaryMessageEncoding').

Wednesday, May 21, 2008 4:04:18 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | WCF
 Tuesday, May 13, 2008

The article I wrote about building a Voice over IP .NET application using AIM Call Out and the AOL Open Voice API has just gone live on the AOL Developer Network. Read it here.

Tuesday, May 13, 2008 2:11:26 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | AOL | C#
 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
 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
 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
 Thursday, March 27, 2008

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
 Monday, March 24, 2008

The 22nd of April the Maine Developer Network is organizing a Geek Lunch. We'll be meeting at the State of Maine offices in Augusta to listen to Chris Bowen present on LINQ & Language Improvements in C# 3.0/VB 9.

Pizza will be provided and attendance is free and open for everyone!

More info and RSVP here.

Monday, March 24, 2008 11:52:01 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | General | LINQ
 Thursday, January 17, 2008

I was writing some code today to map online drive and files to a local objecttree. So I created a custom file and directory object and a directory holds subdirectories and files.

Something like this:

public class File
{
    public string Name { get; set; }
}

public class Directory
{
    public string Name { get; set; }
    public List<Directory> SubDirectories { get; set; }
    public List<File> Files { get; set; }
}

Now I wanted to have a method which tells me how many files are in a folder, including all the subfolders. This is essentially a recursive select of the number of files per directory and then the sum of the files.

So I implemented a LINQ statement:

public int GetNumberOfFiles()
{
    int total = ( from dir in SubDirectories
                  select dir.Files.Count ).Sum();
    return total;
}

Now this will only get the sum of the number of files in the directories immediately below the current. Let's add a little recursion:

public int GetNumberOfFiles()
{
    int total = ( from dir in SubDirectories
                  select dir.Files.Count + dir.GetNumberOfFiles() ).Sum();
    return total;
}

Pretty nifty!

Thursday, January 17, 2008 3:08:35 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#
 Friday, January 11, 2008

Okay, so I'm having a carstarter installed in my car and obviously have nothing better to do than keep tinkering with this DSL stuff.

So I'm thinking... If we create a DSL for the person writing the code, then the debug experience should also be DSL-like. Now I'm not about to write my own debugger, but instead of showing a plain DateTime (what kind of datatype is that anyway?!?!?) we're talking animals, persons and real 'talk' date of birth stuff here.

So I create a special DateOfBirth class which overrides the ToString() method and this creates a 'pretty' experience in my debug window. Notice the values for DateOfBirth. This could ofcourse be extended to person, which is still displayed as the same old school type information: 'DSL.Person'.

The complete code comes at the end of this post, but lets have a look at te code complexity when going from

Person p = new Person();
p.DateOfBirth = new DateTime(1972,9,25);

to our DSL :-)

I guess the code is not too bad. Visual Studio still scores it green on the maintainability scale, but it is clear that quite a large amount of code is needed to create a DSL. And DSL's like this get more context sensitive. Imagine if I would also like to support birds with my DSL? Birds get hatched not born. I'd have to expand my extensions class, or maybe create a whole new set of classes and methods, having a class 'HatchedOn'.

Anyway, they just called, my car is done.

Here is the code for the final sample:

namespace DSL
{
    class Program
    {
        static void Main(string[] args)
        {
            Person mark = Person.Named("Mark").BornOn(Day.the25th).Of(Month.September).InTheYear(1972);
            Animal watson = Animal.Named("Watson").BornOn(Day.the2nd).Of(Month.January).InTheYear(2001).AndItIsA(Animal.KindOf.Dog);
        }
    }


    public class DateOfBirth
    {
        public int Year;
        public Month Month;
        public Day Day;

        public static implicit operator DateTime(DateOfBirth dob)
        {
            return new DateTime(dob.Year, (int)dob.Month, (int)dob.Year);
        }

        public override string ToString()
        {
            return "Born on " + Day.ToString() + " of " + Month.ToString() + " in the year " + Year.ToString() + ".";
        }
    }

    public enum Day : int
    {
        the1st = 1,
        the2nd = 2,
        the25th = 25
    }

    public enum Month : int
    {
        January = 1,
        February = 2,
        September = 9
    }

    public interface IDateOfBirth
    {
        DateOfBirth DateOfBirth { get; set; }
    }

    public class Person : IDateOfBirth
    {
        public DateOfBirth DateOfBirth { get; set; }
        public string Name { get; set; }

        public static Person Named(string name)
        {
            Person p = new Person(name);
            p.DateOfBirth = new DateOfBirth();
            return p;
        }

        protected Person(string name)
        {
            Name = name;
        }
    }

    public class Animal : IDateOfBirth
    {
        public enum KindOf
        {
            Dog,
            Cat
        }

        public DateOfBirth DateOfBirth { get; set; }
        public string Name { get; set; }
        public KindOf KindOfAnimal { get; set; }

        public static Animal Named(string name)
        {
            Animal animal = new Animal();
            animal.Name = name;
            animal.DateOfBirth = new DateOfBirth();
            return animal;
        }
        public Animal AndItIsA(KindOf kind)
        {
            KindOfAnimal = kind;
            return this;
        }
    }


    public static class DateOfBirthExtensions
    {
        public static T BornOn<T>(this T p, Day day) where T : IDateOfBirth
        {
            p.DateOfBirth.Day = day;
            return p;
        }

        public static T Of<T>(this T p, Month month)  where T : IDateOfBirth
        {
            p.DateOfBirth.Month = month;
            return p;
        }

        public static T InTheYear<T>(this T p, int year)  where T : IDateOfBirth
        {
            p.DateOfBirth.Year = year;
            return p;
        }
    }

}

 

Friday, January 11, 2008 8:48:37 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#

I've decided working with enumerations beats working with generics. So now I've taken my little DSL experiment back to enumerations and started implementing the DateOfBirth DSL as a generic extension method.

Since the compiler infers the type based on the actual parameters used you don't need to supply the type when using the extensions methods. Very cool!

Now my DateOfBirthExtensions can work on anything that implements the IDateOfBirth interface, be it a person or an animal :-)

 

namespace DSL
{
    class Program
    {
        static void Main(string[] args)
        {
            Person mark = Person.Named("Mark").BornOn(Day.theTwentyFifth).Of(Month.September).InTheYear(1972);
            Animal watson = Animal.Named("Watson").BornOn(Day.theSecond).Of(Month.January).InTheYear(2001).AndItIsA(Animal.KindOf.Dog);
        }
    }

    public enum Day : int
    {
        theFirst = 1,
        theSecond = 2,
        theTwentyFifth = 25
    }

    public enum Month : int
    {
        January = 1,
        February = 2,
        September = 9
    }

    public interface IDateOfBirth
    {
        DateTime DateOfBirth { get; set; }
    }

    public class Person : IDateOfBirth
    {
        public DateTime DateOfBirth { get; set; }
        public string Name { get; set; }

        public static Person Named(string name)
        {
            Person p = new Person(name);
            return p;
        }

        protected Person(string name)
        {
            Name = name;
        }
    }

    public class Animal : IDateOfBirth
    {
        public enum KindOf
        {
            Dog,
            Cat
        }

        public DateTime DateOfBirth { get; set; }
        public string Name { get; set; }
        public KindOf KindOfAnimal { get; set; }

        public static Animal Named(string name)
        {
            Animal animal = new Animal();
            animal.Name = name;
            return animal;
        }
        public Animal AndItIsA(KindOf kind)
        {
            KindOfAnimal = kind;
            return this;
        }
    }


    public static class DateOfBirthExtensions
    {
        public static T BornOn<T>(this T p, Day day) where T : IDateOfBirth
        {
            p.DateOfBirth = new DateTime(p.DateOfBirth.Year, p.DateOfBirth.Month, (int)day);
            return p;
        }

        public static T Of<T>(this T p, Month month)  where T : IDateOfBirth
        {
            p.DateOfBirth = new DateTime(p.DateOfBirth.Year, (int)month, p.DateOfBirth.Day);
            return p;
        }

        public static T InTheYear<T>(this T p, int year)  where T : IDateOfBirth
        {
            p.DateOfBirth = new DateTime(year, p.DateOfBirth.Month, p.DateOfBirth.Day);
            return p;
        }
    }

}

Friday, January 11, 2008 7:55:53 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#

Inspired by Pinku Surana's blog about DSL's and after reading the presentation from Neal Ford I felt compelled to experiment with a little DSL style programming.

My goal was to get as close as possible to something like:

Person mark = Person.Named("Mark").BornOn(theTwentyFifth).Of(September).InTheYear(1972);

As it turns out the linking of methods is pretty easy. Where you might be inclined to create a property, just create a method which returns the base object, in this case Person.
The hardest part I found was trying to come up with something decent for 'theTwentyFifth' and 'September'. My first try was to create enumerations, but then you have to name the enum and you get something like:

Person mark = Person.Named("Mark").BornOn(Day.theTwentyFifth).Of(Month.September).InTheYear(1972);

Which is good because the intellisense in C# is great, but having to prefix it messes it up just a little. An Alternative implementation is to 'abuse' generics and do it like this:

Person mark = Person.Named("Mark").BornOn<theTwentyFifth>().Of<September>().InTheYear(1972);

The draw back to this is that intellisense is less useful and it is messy to be using generics for BornOn and Of, but not for InTheYear.
The implementation is below. I'm still thinking about which solution is more useful.


namespace DSL
{
    class Program
    {
        static void Main(string[] args)
        {
            Person mark = Person.Named("Mark").BornOn<theTwentyFifth>().Of<September>().InTheYear(1972);
        }
    }

    public abstract class CalenderMonth
    {
        public int Month { get; private set; }

        protected CalenderMonth(int month)
        {
            Month = month;
        }
    }

    public class September : CalenderMonth
    {
        public September()
            : base(9)
        {
        }
    }


    public abstract class DayOfMonth
    {
        public int Day { get; private set; }

        protected DayOfMonth(int day)
        {
            Day = day;
        }
    }

    public class theTwentyFifth : DayOfMonth
    {
        public theTwentyFifth()
            : base(25)
        {
        }
    }

    public class Person
    {
        DateTime _dob = new DateTime();
        string _name;


        public const int theFirst = 1;
        public const int theTwentyFifth = 25;

        public static Person Named(string name)
        {
            Person p = new Person(name);
            return p;
        }

        protected Person(string name)
        {
            _name = name;
        }

        public Person BornOn<T>() where T : DayOfMonth, new()
        {
            T d = new T();
            _dob = new DateTime(_dob.Year, _dob.Month, d.Day);
            return this;
        }

        public Person Of<T>() where T : CalenderMonth, new()
        {
            T m = new T();
            _dob = new DateTime(_dob.Year, m.Month, _dob.Day);
            return this;
        }

        public Person InTheYear(int year)
        {
            _dob = new DateTime(year, _dob.Month, _dob.Day);
            return this;
        }
    }

}

 

Friday, January 11, 2008 7:24:33 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#

If you want to dynamically want to load a form and you only know the classname then the following snippet may be of use:

Type t = Type.GetType("ConsoleApplication1.Form1");
if (t != null)
{
    System.Windows.Forms.Form f = (System.Windows.Forms.Form) Activator.CreateInstance(t);
    f.ShowDialog();
}

Now, if you'd want to load the form from a different assembly, let's say, some library assembly with forms, then you need to specifiy an AssemblyQualifiedName.

Like:

Type t = Type.GetType("ClassLibrary1.Form1, ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
if (t != null)
{
    System.Windows.Forms.Form f = (System.Windows.Forms.Form)Activator.CreateInstance(t);
    f.ShowDialog();
}

This will dynamically load the form and show it. So no compiletime binding needs to be done.

 

Friday, January 11, 2008 10:33:31 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#
 Thursday, January 10, 2008

I'm beginning to appreciate the power of extension methods. At first I thought: "Who wants this?". Doesn't this 'break' the encapsulation of object oriented programming?

Well yes it does, but it makes for some darn pretty code when building utility methods. Right now I'm working on some stuff with the DataContractJsonSerializer and this class has a ReadObject method which takes a stream as a parameter. When writing unit test (and regular code) I'm quite frequently going from a string to a stream. So I figured I'd create an extension method called ToMemoryStream(). This is what is looks like:

using System;
using System.IO;

namespace DevelopOne.Framework.Serialization
{
    /// <summary>
    /// Class with extension methods which are helpful when working
    /// with serialization.
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// Converts a string to a memory stream and sets the position of the stream to
        /// the beginning of the stream.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static MemoryStream ToMemoryStream(this string s)
        {
            MemoryStream ms = new MemoryStream();
            byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(s);
            ms.Write(bytes, 0, bytes.Length);
            ms.Position = 0;
            return ms;
        }
    }
}

Now calling this method can be done by simply including the namespace DevelopOne.Framework.Serialization and calling ToMemoryStream() on a string.

Like this:

string json = "{\"exceptions\":[{\"type\":\"ExceptionObject\",\"errorMessage\":\"Calls to member.login must be secure.\",\"errorInfo\":null,\"errorCode\":513}]}";
MemoryStream ms = json.ToMemoryStream();

 

 



The best web hosting service is the one that not only provides cheap web hosting, but comes with perks like email hosting as well. This and the added benefits of hosting more than one domain names of course adds to the entire package. Thanks to the extensive promotion of online marketing, now anyone with access to computers knows of this. This has contributed effectively to the popularity of home business setups as well.

Thursday, January 10, 2008 8:09:58 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#
 Monday, November 19, 2007

The last couple of weeks I've been working on migrating an ASP.NET application from using a Visual FoxPro database to using SQL Server 2005. My application has it's logic in library DLL and with some layering uses Typed DataSets to connect to the database.

Typical code within the data access layer looks like this:

internal ViewDataSet.RequestViewDataTable GetViewByPrimaryUser( string user )
{
    using ( ViewDataSetTableAdapters.RequestViewTableAdapter _adapter 
            
= new ViewDataSetTableAdapters.RequestViewTableAdapter() )
    {
        ViewDataSet.RequestViewDataTable table;
        table = _adapter.GetByPrimaryUser( user.Trim() );
        return table;
    }
}

The method 'GetByPrimaryUser' is defined on the TableAdapter and using the GUI designer in Visual Studio I manage my typed datasets. All SQL is stored within the Typed DataSets. There is very limited use of stored procedures.

Migrating the .NET code from using a Visual FoxPro database to using SQL Server 2005 has involved the following:

  • Change the connection string property on every datatable to use the SQL Server connection string instead of the FoxPro connection string.
  • Opening every single query and changing the SQL parameters from question marks '?' to named parameters like '@user'.
  • Rechecking the mapping of the columns in the datatable, sometimes these would get messed up. Especially in cases where non-database columns where added to the datatable.
  • Rechecking column expressions.
  • Some areas of the code accessed the OleDbDataAdapter and OleDbConnection within the typed dataset, this had to be replaced with SqlDataAdapter and SqlConnection.
  • FoxPro does not support the .NET light weight transactions, so code to custom manage the transaction could be deleted and a simple 'using( TransactionScope tx = new TransactionScope() )' could be implemented.
  • There where several areas where 'adapter.Update(row)' did not work with FoxPro, so the Insert/Update/Delete had to be called manually in the data access layer. With SQL Server there are no problems and this 'fix-it' code could be removed.

After following these steps some of the datatables would generate unexplicable validation errors. Not wanting to waste too much time I just re-created those typed tables and re-added the queries on those tables.

 



Since the advent of cheap web hosting, we have had more development in the field of SEM. Thanks to features like internet phone, managing internet network marketing is a lot more feasible now. Marketing strategies like cpc, ppi and pay per click can be managed with much more comfort now. Usually regular advertising agencies miss out on this since they concentrate more on building links through email marketing.

Monday, November 19, 2007 7:23:49 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | C#

Visual Studio 2008 Team Suite has just become available on MSDN Subscriber Downloads.

Monday, November 19, 2007 6:41:32 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | C# | General | Team System
 Monday, November 12, 2007

Another gem in .NET 2.0. Parsing a string to get a datetime used to be pretty complex. But now with the DateTime.ParseExact(...) method you can specify the exact format of your string.

string s = "20071231T214559";
DateTime d = DateTime.ParseExact( s, "yyyyMMddTHHmmss", null );
this.textBox2.Text = d.ToString();  // this will print: 31-12-2007 21:45:59

Steve Tibbet has a post describing all the options for specifying the format.

Monday, November 12, 2007 8:54:54 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | C#

The .NET Framework is huge and I still frequently find new things in .NET 2.0 which I had not seen before. Last week I stumbled across the update in Math.Round(...).
In .NET 1.x the .NET Framework would only support the American way of rounding numbers. This means that:

decimal y = 2.5M;
decimal x = Math.Round(y, 0);     // x = 2

For Dutch people this wrong. We would expect x to be '3'.
In .NET 2.0 there is a new overload, allowing you to specify how the Round method should work.

decimal y = 2.5M;
decimal x = Math.Round(y, 0, MidpointRounding.AwayFromZero);     // x = 3!

Monday, November 12, 2007 8:24:02 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | C#
 Sunday, November 11, 2007

Earlier this year the C# team implemented a change in the design of anonymous types. It used to be possibly to create an anonymous type and then change a property on the anonymous type. The code would look like this:

var x = new { Name = "Mark", Age = 0 };
x.Age = 35;

In Visual Studio 2008 beta 2 this is however no longer possible since anonymous types are now immutable. There are apparently good reasons for doing this and Sree explains it in this post and there is an issue on MSConnect where Mads from the C# team explains the reasoning. Must say I don't completely get the reasoning, especially since VB.NET does not have this restriction.

Sunday, November 11, 2007 11:23:02 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | LINQ

Yesterday I spoke at the iSDC and Ronua Community Workshop. We had a great day and it was a pleasure meeting the people at iSDC, meeting the developers in Cluj and surroundings (some drove over 200km to make it to the meeting) and Petru Jucovschi (the DPE for Microsoft Romania).

Here are the two presentations that I did:

11-09-2007 - Developing Windows Vista gadgets.pptx (431.43 KB)

11-10-2007 - 2008.NET.pptx (252.91 KB)

In the Visual Studio 2008 presentation I also talked about the work I've done for AOL. The AOL developer site can be found at http://dev.aol.com and for more reference material on Vista gadgets you can visit my AOL blog.

Sunday, November 11, 2007 3:32:20 AM (Eastern Standard Time, UTC-05:00)  #    Comments [2] -
C# | General | LINQ | Vista | WCF
 Wednesday, October 31, 2007

I just finished my sample of the week for my AOL blog. This week I created code to upload a file to XDrive using the HttpWebRequest object. The sample is also useful if you're trying to find out more about uploading a file using C# (or the .NET Framework).