Sam Gentile - CodeBetter.com

Syndicate content This Feed Powered by FeedBurner.com
Connected Systems Lead East at Neudesic - Service-Oriented Architecture, Connected Systems, Enterprise Architecture, and Software Architecture from an experienced INETA Speaker and Solutions Architect MVP - Software Architecture, SOA, .NET Framework 3.5 WCF, Connected Systems, LINQ, VSTS, Windows Vista, Smart Clients, CLR, Rotor
Updated: 51 min 54 sec ago

Great new intro article on SOA in Plain English

May 24, 2010 - 3:13pm

There are a lot of definitions of SOA out there, most very dry and verbose. Dan Fornes, CEO of Software Advice, just recently wrote a nice intro article on SOA's: Service Oriented Architectures (SOAs): A Plain English Guide that cuts through all that and explains terms in plain English. I especially like his simple definition: "A new and better way to get a bunch of different software programs to work together so people can do things that require information from each of those systems." Especially valuable is a Glossary of terms that he provides definitions for in plain English. A recomended read! 

 

C# 4.0/BCL 4 Series:SortedSet<T> in Framework 4

May 22, 2010 - 7:06pm

This is part of a series. To add to 3.5's new HashSet<T>, there is now SortedSet<T> new in 4.0. Both have the following distinguishing features:

  • Their Contains methods execute quickly using a hash-based lookup
  • They do not store duplicate elements and silently ignore requests to add duplicates
  • You cannot access an element by position

SortedSet<T> keeps elements in order, whereas HashSet<T> does not. HashSet<T> is implemented wuth a hashtable that just stores keys;SortedSet<T> is implemented with a red/black tree.

You can consult MSDN for the definition of HashSet but SortedSet<T> adds:

  • public virtual SortedSet<T> GetViewBetween(T lowerValue, T upperValue)
  • public IEnumerable<T> Reverse()
  • public T Min( get; )
  • public T Max( get; )

Let's see how to use some of SortedSet<T>:

style="background-color: #FBFBFB; font-family: consolas,'Courier New',courier,monospace; font-size: 12px; width: 100%; margin: 0em"> // SymmmetricExcerptWith removes all but the elements

  // that are unique to one set or other var letters3 = new SortedSet<char>("the quick brown fox"); letters3.SymmetricExceptWith("the lazy brown fox"); foreach(char c in letters3) Console.Write(c); } } }    

C# 4.0/BCL 4 Series:Dynamic Primitive Type Part 2

May 22, 2010 - 4:36pm

This is part of a series. Last time I started talking about the new dynamic type in C# 4, I covered why they were introduced to the language (scenarios), then some deep discussion of how they are implemented with the DLR, call-sites, and bindings, how internally they are represented as System.Object and the equivalence relationships as well as implicit and explicit conversions. This time, I am going to go deeper into the bindings and show some code.

First a little more review and generalities. Don't forget the concept that dynamic is a type in the C# type system. It has special meaning but it's definetly a type, and it's important to treat it as such. You can indicate dynamic as the the type as the type of the variable you declare, the type of items in a collection or the return value of a method. You can also use dynamic as the type of a method parameter.

Also, to review...

A dynamic type is declared with the keyword dynamic:

      dynamic d = GetSomeObject();

      d.Quack();

A dynamic type tells the complier to relax. We expect the runtime type of d to have a Quack method but we just can't prove it statically. Since d is dynamic, the compiler defers binding Quack to d until runtime. When your code invokes a member using a dynamic expression/variable, the compiler generates special IL code describing the desired operation, known as the payload. So, instead of emitting an IL instruction to Quack(), which the compiler cannot clearly do since there is no type with that definition, the compiler emits a "dynamic call site" that manages that operation at runtime, using the C# runtime Binder, and in conjunction with the DLR. At runtime, the payload code determines the exact operation to invoke based on the actual type of the object now referenced by the dynamic expression/variable.

There are actually four kinds of Binding:

  1. Using reflection against an underlying CLR type
  2. Invoking a custom IDynamicMetaObjectProvider, which makes available a DynamicMetaObject
  3. Calling through IUnknown and IDispatch interfaces of COM
  4. Calling type defined by dynamic languages such as IronPython

editing.....at work....

Windows Server AppFabric RC (formerly Dublin) and BizTalk Server 2010 and Beta!

May 21, 2010 - 11:29am

Cliff Simpkins has one of the many announcement posts. Today, at the Virtual Application Infrastructure virtual event, the announcement was made first of the official launching Windows Server AppFabric, with the immediate availability of the Windows Server AppFabric Release Candidate (RC); the final RTM release will be available for download in June. Also the firstBizTalk Server 2010 Beta, which now seamlessly integrates with Windows Server AppFabric, was announced.

C# 4.0/BCL 4 Series: C# 4 Named Parameters

May 19, 2010 - 5:29pm

This is part of a series. I really should have combined Named Parameters when I wrote about Optional Parameters last time since they are similar and go well together. Again, nothing thrilling here to speak about in C# 4 (especially since VB has had these forever) but they do address some hardships in working with COM from C#. So, rather than identifying an argument by position, named parameters let you identify an argumment ny name explictly, rather than relying only on parameter order. A trivial example is as follows:

void foo(int x, int y) { Console.WriteLine(x + ", " + y); } void Test() { foo(x:4, y:2); // 4.2 }

 

Named arguments can occur in any order. The following calls to foo are semantically identical:

      foo(x:4, y:2);

      foo(x:2, y:4);

You can mix named and positional parameters:

      foo(4, y:2);

However you should note that positional parameters must come before named parameters. So we couldn't do this:

     foo(x:4, 2);     // Compile time error

Named arguments are particuarly useful together with optional parameters:

     void Bar(int a = 0, int b = 0, int c = 0, int d = 0) {...}

We can then call this supplying only a value for d as follows:    Bar(d:3);

This is particuarly useful when calling COM APIs, which I'll leave out for later.

C# 4.0/BCL 4 Series: C# 4 Optional Parameters

May 17, 2010 - 5:15pm

This is part of a series.  C# 4 allows you to declare optional parameters in methods, constructors, and indexers. A parameter is optional if it specifies a default value in its declaration:

     void Foo(int x = 42) { Console.WriteLine(x); }

Optional parameters may be omitted when calling the method:

      Foo();      // 42

The default argument of 42 is actually passed to the optional parameter x - the compiler bakes the value 42 into the compiled code at the calling side. The previous call to Foo is semantically identical to:

      Foo(42);

because the compiler simply substitutes the default value of an optional parameter whenever it is used. The default value of an optional parameter must be specified by a constant expression. Optional parameters cannot be marked with ref or out.

Mandatory parameters must occur before optional parameters in both the method declaration and the method call. In the following example, the explicit value of 1 is passed to x and the default value of 0 is passed to y:

     void Foo(int x = 0, int y = 0) {Console.WriteLine(x + "," + y);  }

     void Test()

     {

          Foo(1);             // 1, 0

     }

C# 4.0/BCL 4 Series:Dynamic Primitive Type Part 1

May 13, 2010 - 1:59pm

This is part of a series. I have to admit. I am non-excited about C# 4 features, including the dynamic type. While C# 3,  introduced many neccessaary features, especially for LINQ, but very useful in their own right, C# 4 seems more like a solution looking for a problem. IMHO, it seems like the language was finished a few years ago in 3.0 and it's taking on un-needed complexity. Part of the attraction of C# used to be how simple a language it was. Blending a static type-safe language with dynamic features seems unnatural to me. If I want to do dynamic programming, I'll just use Ruby or IronRuby.

That being said, there are occassions when a program has to act on information that it doesn't know until runtime. While you can use C# or other typesafe languages, the syntax tends to be clumsy and full of a lot of string processing. Some examples of compnents you may want to communicate with C# are:

  1. .NET Dynamic Lanaguages like Ruby or Python
  2. COM components that support the IDispatch interface (possibly implemented in native C/C#)
  3. HTML DOM objects (implemented using various languages and technologies.

To make it easier for developers using reflection or communicating with other components like above, the C# compiler allows you a way to mark an expression's type as dynamic. You can also put the result of an expression into a variable and you can mark a variable's type as dynamic.

A dynamic type is declared with the keyword dynamic:

      dynamic d = GetSomeObject();

      d.Quack();

A dynamic type tells the complier to relax. We expect the runtime type of d to have a Quack method but we just can't prove it statically. Since d is dynamic, the compiler defers binding Quack to d until runtime. When your code invokes a member using a dynamic expression/variable, the compiler generates special IL code describing the desired operation, known as the payload. At runtime, the payload code determines the exact operation to invoke based on the actual type of the object now referenced by the dynamic expression/variable.

At runtime, if a dynamic object implements IDynamicMetaObjectProvider, that interface is used perform to perform the binding. If not, binding occurs in almost the same way as it would have had the complier known the dynamic object's runtime type and uses reflection. These alternatives are called custom binding and language binding, and I'll get to that later.

Runtime Representation of Dynamic

I first want to talk about that there is a deep equivalence between the dynamic and object types. The runtime treats the following as true:

      typeof(dynamic) == typeof(object)

This is because when the type of a field, method parameter, method return type, or local variable, is specified as dynamic, the complier converts this type to the the System.Object type and applies an instance of System.Runtime.CompilerServices.DynamicAttribute to the field, parameter, or return type in metadata. Before I get to dynamic conversions, let's get back to the runtime trearing the typeof dynamic as eqivalent to the typeof object, This principle extends to constructed types and array types:

     typeof(List<dynamic>) == typeof(List<object>)

     typeof(dynamic[]) == typeof(object[])

Like an object reference, a dynamic reference can point to an object of any type (except pointer types):

     dynamic x = "Sam";

    Console.WriteLine(x.GetType().Name);       // String

     x = 42;                             // No error, despite same variable

     Console.WriteLine(x.GetType().Name);       // Int32

Structurally, there is no difference between an object reference and a dynamic reference. A dynamic reference simply enables dynamic operations on the object it points to. You can can convert from object to dynamic to perform any dynamic operation you want on an objectL

      object o = new System.Text,StringBuilder();

      dynamic d = o;

      d.Append("hello");

      Console.WriteLine(o);      // hello

Conversions

Any expression can be implicitly be cast to dynamic since all expressions result in a type that result in a type that is derived from Object. Normally, the compiler does not allow to write code that implictly casts an expression from Object to another type you must use explicit cast syntax. However, the compiler does allow you to cast an expression from dynamic to another type using the implicit cast syntax:

      Object o1 = 123;                               // OK, Implicit cast from Int32 to Object (boxing)

      Int32 n1 = o;                                      // Error: No implicit cast from Object to Int32

      Int32 n2 = (Int32) o;                           // OK: Explicit cast from Object to Int32 (unboxing)

      dynamic d1 = 123;                             // OK: Implicit cast from Int32 to dynamic (boxing)

      Int32 n3 = d;                                       // OK: Implicit cast from dynamic to Int32 (unboxing)

The dynamic type has implcit conversions to and from all types. For the conversion to succeed, the runtime type of the dynamic object must be implictly convertable to the target static type:

     int i = 42;

     dynamic d = i;

     int j = d;                    // No cast required (implicit conversion)

The following example throws a RuntimeBinderException because an int is not implicitly convertable to a short:

     int i = 7;

     dynamic d = i;

     short j = d;                // throws RuntimeBinderException

That's it for now. There will have to be a Part2 that covers CustomBinding versus LanguageBinding,  Dynamic Expressions as well as some more meaningful examples.

New and Notable 415

May 11, 2010 - 2:10pm

A collection of links, not all "new"

AppFabric/BizTalk/Identity

VS2010

C# 4.0/BCL 4 Series: Complex numeric type

May 10, 2010 - 11:32am

This is part of a series. Note: This material is from C# 4.0 In A Nutshell Page 239.

Like BigInteger, the Complex struct is another specialized numeric type new to Framework 4.0 and is for representing complex numbers with real and imaginary components of type double. It also lives in the System.Numerics.dll assembly. To use Complex, instantiate the struct, specifying the real and imvar  aginary values:

     var c1 = new Complex(2, 3.5);

     var c2 = new Complex(3, 0);

There are also implicit conversions from the standard numeric types.

The complex struct exposes properties for the real and imaginary values, as well as the phase and magnitudeL

     Console. WriteLine(c1.Real);             // 2

     Console.WriteLine(c1.Imaginary);      // 3.5

     Console.WriteLine(c1.Phase);           // 1.05165021254837

     Console.WriteLine(c1.Magnitude);    // 4.03112887414927

You can also construct aq Complex number by specifying the magnitude and phase:

     Complex c3 = Complex.FromPolarCoordinates(1.3, 5);

The standard arithmetic operators are overloaded to work on Complex numbers:

     Console.WriteLine(c1 + c2);      // (5, 3.5);

     Console.WriteLine(c1 * c2);       // (6, 10.5)

The Complex struct exposes static methods for more advanced functions, including:

  • Trigonometric (Sin, Asin, Tan, etc.)
  • Logorithms and exponentiations
  • Conjugate

 

C# 4.0/BCL 4 Series: BigInteger

May 10, 2010 - 11:03am

This is part of a series.

Another new type in Framework 4.0 os the BigInteger specialized numeric type. It lives in the new System.Numerics namespace and lets you represent an arbitrarily large integer without any loss of precision,

Since C# does not provide native support for BigInteger, there's no way to represent BigInteger literals. What you can do, however, is implicitly cast from any other integral type to a BigInteger:

      BigInteger theSecretOfLife = 42;

That's not too useful. To represent a bigger number, such as one gooogol (10 to 100th), you can use one of BigInteger's static methods, such as PoW (raise to the power):

      BigInteger googol = BigInteger.Pow(10, 100);

Alternatively, you can Parse a string:

      BigInteger googol = BigInteger.Parse("1".PadRight(100, '0'));

You can implicitly cast a BigInteger to a standard numeric type and explictly cast in the other direction:

       double g1 = 1e100;           // implicit cast

       BigInteger g2 = (BigInteger) g1;    // explicit

Calling ToString() on the googol variable prints every digit:

       BigInteger googol = System.Numerics.BigInteger.Pow(10, 100);Console.WriteLine(googol.ToString());

10000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000
Press any key to continue . . .

System.Numerics.

 

C# 4.0/BCL 4: What's New Series

May 10, 2010 - 2:05am

Might as well make this a series. I mentioned in the first post, "I have been spending quite a bit of time re-focusing and reviewing C# (and some BCL) fundamentals, with an eye to what's different in C# 4.0/BCL 4.0. The reason for this, is though C# 1.0 was so simple in it's day that it only required a 28 page spec, C#3 and 4 have really gotten away from me such that I'm only making average use of 3.0. I'll write a comparison review of the books I have been using, but for my money, the best and definitive book (as it was in 3.0) is C# 4.0 In A Nutshell (Disclaimer: I was a reviewer for V3 of this book and mentioned in the acknowledgements for this edition as well.

So, it goes something like this:

  1. Framework 4.0: StructuralComparisons Type
  2. Framework 4.0: System.Tuple
  3. More on System.Tuple and Prefer Query Syntax to Loops
  4. BigInteger class
  5. Complex class
  6. New SortedSet collection
  7. C# 4: Dynamic primitive type
  8. C# 4: Optional Parameters and Named Arguments
  9. Code Contracts
  10. Generics Covariance and Contravariance
  11. Direct support for memory-mapped files
  12. Review: C# 4.0/BCL 4,0 Books
  13. Lazy file and directory I/O methods that return IEnumerable<T> instead of arrays
  14. TPL and PLINQ

Now, if only I could get my code to format for the blog!! LiveWriter (and its plug-ins) refuse to recognize and work with this Grafitti blog style. Any ideas? I also need to get help in getting Graffitti from using the Vista DB file system to SQL Server. Your ideas on the series? Helpful?

Framework 4.0: System.Tuple

May 4, 2010 - 4:03pm

I mentioned, in my last post, that I was using  C# 4.0 In A Nutshell to better my C# 3 and to come up to speed with C# 4/BCL 4. Another cool thing in Framework 4.0 is the generic set of classes for holding a set of differently typed objects called tuples. Like the Func<> and Action<> delegates, tuples also take up to 8 parameters:

public class Tuple<T1>

up to:

public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>

While C# and VB.NET do not have the concept as part of the core language, many functional languages have tuples as common features. Also many teams have built their own. The BCL 4 System.Tuple is the one definition to rule all others and there is one interoperable type.

Above, each of the tuples has read-only properties called Item1, Item2 and so on (one for each type parameter). You can instantiate a tuple either via it's constructor:

var t = new Tuple<int, string> (123, "Hello");

or via the static helper method Tuple.Create:

Tuple<int, string> t = Tuple.Create(123, "Hello");

which can be made:

var t = Tuple.Create(123, "Hello");

You can then access the properties as (Note: each is statically typed):

Console.WriteLine(t.Item1 * 2);                     // 246

Console.WriteLine(t.Item2.ToUpper());         // HELLO

You may ask what Tuples are good for? They are really convenient in returning more than one value from a method or creating collections of value pairs. You could use object arrays but then you lose static type safety, incur the cost of boxing/unboxing for value types, and require clumsy casts that cannot be validated by the compiler.

Now to return to the subject of the last post, comparisons. Tuples are classes so they are reference types. This means, comparing two distinct instances with the equality operator returns false. Unlike arrays however, the Equals method is overridden to compare each individual element instead:

var t1 = Tuple.Create(123, "Hello");

var t2 = Tuple.Create(123, "Hello");

Console.WriteLine(t1 == t2);                        // False

Console.WriteLine(t1.Equals (t2));               // True

Last time, I talked about the StructuralComparison type. Well, tuples implement IStructuralEquatable, so you can pass in a custom equality comparer.

If you want to learn a lot more about System.Tuple, you can look at the excellent MSDN article: "CLR Inside Out: Building Tuple" http://msdn.microsoft.com/en-us/magazine/dd942829.aspx

 

Framework 4.0: StructuralComparisons Type

April 28, 2010 - 2:44pm

I have been spending quite a bit of time re-focusing and reviewing C# (and some BCL) fundamentals, with an eye to what's different in C# 4.0/BCL 4.0. I'll write a comparison review of the books I have been using, but for my money, the best and definitive book (as it was in 3.0) is C# 4.0 In A Nutshell (Disclaimer: I was a reviewer for V3 of this book and mentioned in the acknowledgements for this edition as well.

So back, to this cool new BCL 4.0 thing. This comes write out of the book on Page 275. As we all know, arrays are reference types, so that the statement arrayb = arraya results in two variables that reference the same array. Simarly, two distinct arrays will always fail an equality test - unless you use a custom equality comparer. Framework 4.0 provides one for the purpose of comparing elements in arrays or tuples which you can access via the StructuralComparisons type:

object[] a1 = {"string", 123, true};

object[] a2 = {"string", 123, true};

Console.WriteLine(a1 == a2); // False

Console.WriteLine(a1.Equals(a2)); // False

IStructuralEquatable se1 = a1;

Console.WriteLine(se1.Equals(a2,

 StructuralComparisons.StructuralEqualityComparer));

Neuron ESB 2.5 Available for Download

April 27, 2010 - 4:58pm

Rick Garibay posted the availability of Neuron 2.5 and points to my series on the product:  http://samgentile.com/Web/neuron-esb/. Why should you care?

  1. Neuron is the  the only commercial ESB built on WCF and the .NET Framework that is fully supported by a Microsoft Partner
  2. WCF is just a framework, not a product. You need a lot more to build real apps
  3. As Rick says, "We built Neuron ESB to accelerate SOA adoption by taking sophisticated messaging patterns such as Pub-Sub, Virtual Service, Naming and Discovery, Mediation, Protocol Bridging, and Security (to name a few) and commoditizing them so that they fall into the reach of developers of all disciplines and levels of experience, whether they are veteran WCF developers or have not yet made the leap."

See his post for the full scoop.