Archive

Archive for the ‘C#’ Category

Why Properties matter : Uniform Access Principle

November 28th, 2009

Learning a new language has various side-effects. Old habits are questioned, good practices are reinforced while bad habits come to light. By re-learning programming principles in a new syntax, in that strange new world (IDE, Syntax, etc..) you learn something new about your favorite languages – and often yourself.

I started off in C++ moved to Java then C# and most recently have begun working w/ Scala. In the book, Programming Scala by Dean Wampler & Alex Payne, the Uniform Access Principle was described & named.

So what is all the hubbub about Uniform Access Principle?

Clients read and write field values as if they are publicly accessible, even though in some case they are actually calling methods

In short, from the outside, a method or field is indistinguishable.

Why is the Uniform Access Principle important?

Classes can interchange methods and fields without affecting the classes that use them.

 

Language support of UAP?

Sadly, few languages (that I know) support UAP fully.

JAVA

Java does not support UAP, either a class has a field or bean properties. (getter/setter).

public class Employee{

    private String m_name;

    public String getName() {
      return m_name;
    }

    public void setName(String name) {
      return m_name;
    }

}

C#

C# does not fully support UAP, but fields & properties are partially indistinguishable. Here are the short comings:
  • interfaces can not contain fields, only properties.  [ propName {get;set;}  vs fieldname; ]
  • fields can be passed by ref or out but not properties (see example project)

 

    class Program
    {
        static void Main(string[] args)
        {
            var e = new Employee();
            e.Name = "Alan Huffman";

            PrintRef(ref e.Name);

            var e2 = new EmployeeProp();
            e2.Name = "John Dobson";

            // COMPILATION ERROR
            // can not pass a property by reference
            PrintRef(ref e2.Name); // *** Compilation error

                     image
        }

        public static void PrintRef(ref String str){
            Console.WriteLine(str);
        }
    }

     

    public interface IEmployee
    {
        String Name;

          image

        // if we change the field into a property, we get an error on Employee class below

        String Name {get;set;}
    }

    public class Employee : IEmployee

    // if the interface defines a property and we try to implement w/ a field

    image
    {

        public String Name;

    }

    public class EmployeeProp : IEmployee
    {
        public string Name { get; set; }
    }

     

     

    SCALA

    SCALA does support UAP, essentially providing abstraction at a language / syntactic level.

Though there is no scala analogous type to C# or Java’s interfaces, traits are close. See here for more http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5

    Here you can see the treatment of the trait IEmployee’s Name property.

     

    trait IEmployee {
      protected var s : String = ""
      def Name : String  = s
      def Name_=(news : String) = s = news
    }

    class E extends IEmployee{
    }

    class F extends IEmployee{
      private var x = s
      override def Name = x
      override def Name_= (news : String) = { s = news; x = news; }
    }

    The property can be accessed via a DOT operator, e.g.

    var f = new F

    var e = new E

    f.Name = “foo”

    e.Name = “foo”

    Alternatively IEmployee could have been written this way:

    trait IEmployee {
      var Name = ""
    }

    class E extends IEmployee{
    }

     

    // However, this no longer compiles! [ I think this has larger implications (see below) ]

    class F extends IEmployee{
      private var x = ""
      override def Name = x
      override def Name_= (news : String) =  x = news;
    }

    image

     

    Omitting the override, results in an alternate error:

    class F extends IEmployee{
      private var x = ""
      def Name = x
      def Name_= (news : String) =  x = news;

    }

    image

     

     

    Because the choice of using a var Name = “” [ field ] or a property def Name = … & def Name_= (news:String) = … [property] has affects what can be done in mixins, the UAP only applies access to but not overriding of a [field] / [property]

    In this case, the C# & Scala are similar, except that traits can have fields while interfaces can not.

    Prefer flexibility

    I am lead to believe that I should prefer:

> Using traits in method signatures: The corollary to “code to interfaces not concrete classes”  in Scala becomes “code to traits not concrete classes

> When defining traits, there is more flexibility in defining properties as opposed to fields.

In the wild, fields are preferred (but traits in signatures does hold)

That said, I have been told that fields are more often defined, "var Name = …” and can be changed later on, as needed, assuming you have access to the code.

alan.huffman C#, JVM Languages, Scala , , , , ,

Magic Strings: How to make this necessary evil (LESS) evil

October 15th, 2009

Magic strings are nasty for several reasons.

  1. Compiler will not pick up type-o’s
  2. When done improperly (e.g. copy / paste ) they can be inconsistent
  3. If they refer to a property or method, they will break on refactoring or renaming (prop / method)

What to do:

1) Try not to use them.

2) When you must, make constants (do not copy paste)

  • Bad: [Dependency("RxDomainUOW")]
  • Good:

Create a new Constants class in a top level directory (make it obvious)

public static class AmPharmConstants

    {

            const String c_RxDomainUOW = "RxDomainUOW";

    }

ii. Then use that constant instead

[Dependency(AmPharmConstants.c_RxDomainUOW)]

3) Rather than magic strings to name a property you can use a class in AmMedUtils: ReflUtil

  • Instead of this: this.PropertyChange(this, “PublishedOrders”);
  • Use this: this.PropertyChange(this, ReflUtil.PropName(() => PublishedOrders));

< CLASS ReflUtil >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace AMFW.Utilities
{
    /// <summary>
    /// From:
    /// http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
    /// </summary>
    public static class ReflUtil
    {
        /// <summary>
        /// string name = ReflectionUtility.PropName(() => default(Sample2).Foo);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static string PropName<T>(Expression<Func<T>> expression)
        {
            MemberExpression body = (MemberExpression)expression.Body;
            return body.Member.Name;
        }

    }
}

alan.huffman C# , , ,

Unfortunate differences between LINQ SQLMetal and SQLDesigner

May 25th, 2009

Summary:

Over the past 1.5 years my team has been using LINQ SQL Designer. We have written a significant amount of code, but our team is doubling in size and we can no longer afford the SVN conflicts from concurrent changes to .DBML files (SQL Designer).

 

Differences:

 

Why:

DLINQ (Linq to SQL) was created to showcase LINQ (Language Integrated Query) but was never meant as a ORM solution. Entity Framework is Microsoft’s chosen ORM solution, but since it was released after LINQ To SQL, EF is not used as much. That’s the reason we did not use it.

    Obviously different teams must have come up with the LINQ SQL Designer versus SQLMetal. I can only assume that the differences outlined above are due to a lack of communication b/w these teams.

Result of these differences:

In switching from LINQ TO SQL to SQL Metal, we had to do the following:

  1. Build DBMLGod (about 1 week) (though http://www.plinqo.com/ might have sufficed)
  2. Refactored nearly every file in our code base (another 1 week)
  3. Testing (TBD)

See related post DBML Hell.

alan.huffman C#, Development Infrastructure, LINQ , , , ,

DBML Hell : Legacy DB + SQLMetal is painful

May 16th, 2009

(when migrating from SQL Designer)

History:

For the past 1.5 years our team has developed HIT (Healthcare IT) LOB (line of business) software using DLINQ SQL Designer. The experience has been pleasant from a tooling perspective except for the reasons that are frequently blogged about, namely DBDesigner results in SVN conflicts when 2 people make changes to the model.

We have a few large DB’s – one is about 9 years old and has hundreds of tables (600+) and even more views plus hundreds if not thousands of SPROC’s (many of which are complex)

We have 3 such DB’s. (each w/ their own pain)

Consider a common use:

More than 1 developer is making changes to a shared relational database (adding/changing tables, sprocs or functions).  Changes are made by Developer A & Developer B and then both try to check in. SVN detects a conflict – given that the code is generated, resolving the conflict is *not* easy to resolve.

Primary Issue:

When a checking in DLINQ Designer DLinq DBML generated files a conflict occurs.

Solution? Move from using the DLINQ Designer to using SQLMetal. (We could use Entity Framework, but that would require significant changes. So we want to stick with DLINQ (LINQ to SQL)).

SQLMetal does not generate what SQL Designer does!

Obviously, if you are on a green field project, this is not as big of an issue. If you are on an existing (brown field) project that has used SQL Designer, this hurts (a lot).

A) SQLMetal does not handle complex stored procedures (in same way)

What is a complex stored procedure?

  1. Uses control flow logic (If/Else) that results in different result sets.
  2. Uses temporary tables (#TmpTable )

#1 results in a IMultipleResults being returned by SQLMetal even though SQL Designer results in a ISingleResult. So migrating from SQL Designer to SQLMetal results in compilation errors.

#2 SQLMetal does not generate these sort of sprocs (at all) though SQL Designer does (ugh!)

#2 is particularly difficult to cope with, assuming you need a #Temp Table. SQLMetal just isn’t going to work.

SET FMTONLY OFF;  — explicitly in the SPROC

http://msdn.microsoft.com/en-us/library/ms173839.aspx

– what does this do? Results in the **ACTUAL** execution of the sproc and not just returning the meta data about what the SPROC result will be.

– in other words, when you run SQLMetal, your sprocs (that have FMTONLY OFF) will be executed. There could be side effects (assuming your SPROC does something & doesn’t just return information)

– This was *NOT* an option for us

B) SQLMetal does not support manual tweaking of DBML as SQL Designer does.
  1. Can not add associations between DTO (Data Transfer Objects) that do *not* exist in DB. [ SQL Designer allows this ]
  2. Can not map a SPROC to a DTO/Entity (easily done in DBML Designer by simply dragging the SPROC to an existing entity (table)
C) Not easy to change the inheritance hierarchy of the generated DataContext?

If you need to change the class that the datacontext inherits from the change must be made each time SQLMetal is run.

e.g.

MyDataContext  : System.Data.Linq.DataContext // generated by SQLMetal each time

// but we want

MyDataCongext : BaseDataContext

// where

BaseDataContext : System.Data.Linq.DataContext

D) SQLMetal DBML or Code generation is VERY SLOW for large DB (15 min !)

Can you imagine adding a table and then waiting 15 minutes before you can start coding using that new table b/c SQLMetal takes that long to generate the DBML or DataContext.cs?

Me neither b/c this is totally unacceptable

E) SQLMetal generates the entire database model! (ugh)

The only filtering that can be done using SQLMetal is at the SPROC / View / Function level. What happens if you only want a specific schema, a limited number of tables or certain functions? SOL.

F) SQLMetal generates a DataContext file so large that Visual Studio crashes (esp. with Resharper)

Essentially this is an extension of the (E) issue, but it is a very different issue. Where E may result in too many things being generated, the fact that Visual Studio crashes may make exploring the DataContext file impossible. Our DataContext.cs file was over 13MB. The DBML was 4MB.

Solutions:

A) Use a different ORM + CodeSmith :-)

This was not a consideration for us. We love LINQ. We drink the MSFT cool aid, and we weren’t about to move to NHibernate or LLBGEN (though I had a history w/ Hibernate). We have too much invested in LINQ. ( I suspect many are in this camp ).

B) Hand code the DBML

Not an option for us, as there we had a very green OOP / ORM team. We needed something convenient that could work with several very large DB’s with a very diverse set of objects (functions, SPROCs, Tables, Views).

C) Move to Entity FrameWork

This doesn’t provide much shelter from the issues outlined above, not to mention that we have a large amount of existing LINQ code. (we’re vested / locked in)

D) Mix the advantages of SQLMetal & SQL Designer

This is the choice we took. But it required the building of a utility tool that provided a mixture of functionality of SQLMetal & SQL Designer. We were in DBML Hell, and thus only DBMLGod could set us free! (tongue in cheek, but I named the tool just that DBMLGod).

DBMLGod ( SQL Designer + SQLMetal + Hand Coded DBML )

The idea was to take the strengths of SQL Designer and that of SQLMetal and merge them into a hybrid that has all the positive qualities but none of the negative. Plus we need the ability to HAND code very complicated SPROC’s that even SQL Designer doesn’t generate correctly. This succeeded, but it does require a us to develop in a certain way.

SQL Designer

Strengths:
  1. Handles Complex Sprocs better than SQLMetal (often times)
  2. Allows SPROCs return types to be mapped to entities
  3. Can add associations that do not exist in the DB / ER
  4. Quick additions of new DB objects (See issue #D above)

Primary weakness: SVN Conflicts

Hand generated DBML

Strengths:
  1. Full control over what is generated & how

Primary weakness: Must hand code / Must understand the DSL.

SQLMetal

Strengths:
  1. Reduces conflicts (on par with Hand generated DBML)
  2. Generates required classes

Weaknesses: See above (A-F)

Ideally we should be able to accumulate strengths without suffering weaknesses.

Implementation of DBMLGod

(Hopefully to be a open source project) – requires my companies sign off.)

In a green field project we might be able to avoid weaknesses of SQLMetal, but given real world scenarios of large existing databases with complex SPROC’s this isn’t possible (for us).

Requirements:
  1. Support complex SPROCs (use SQL Designer / hand coded DBML) [ Issue A ]
  2. Add associations not defined in DB / ER [ Issue B ]
  3. Map SPROC return types to Entities [ [ Issue B ]
  4. Change generated SQLMetal DataContext code (support inheritance from custom DataContext Object) [ Issue C ]
  5. Quick addition of new DB objects (no waiting 15 minutes for regen of DBML / DataContext file) [ Issue D ]
  6. Decrease the size of the generated DBML / DataContext [ Issue E ]
  7. Generated DataContext must not be unnecessarily large (make things as simple (small) as necessary but no smaller) [ Issue F ]

How do we do that?

image

And so the idea is to take the SLOW SQLMetal Generation of the DBML (for large DB) and the faster FILTER / MERGE / SQLMetal Code Gen process and make it fast.

DBMLGod does just that. It gets us out of hell by filtering the Generated DBML, merging those into Hand/Designed DBML files (preferring elements in the latter), generating the code and then replacing code elements in the generated DataContext to get the desired result.

Step 1) Gets value of SLQ Metal DBML Gen but allows us to filter resolving issues E & F

Step 2) Leverages value of Hand/SQL Designer to resolve issue A & B

Step 3) Generate the Code

Step 4) Allows us to resolve isssue C & D

How well does this work?

Addition of DB objects has performance on par with SQL Designer (fast)

SVN conflicts are minimized.

Generation of DBML by SQLMetal (SLOW) can be left to END OF DAY process!

Unresolved issues

SQLMetal capitalizes properties on entity clasess and SPROCs. Default behavior of SQL Designer is to *NOT* do this.

Thus you have 2 choices:

1) Change the SQL Designer generated Sprocs/Entities to conform with SQLMetal generation

2) Use SQL Designer & correct/deal with compilation errors as they occur

Can you believe that MSFT uses different strategies depending on the tool? (UGH, SIGH, HORROR)

But thanks for LINQ! Love it!

Related Post: Unfortunate differences between SQL Metal and SQL Designer

alan.huffman Architecture, C#, Development Infrastructure, LINQ , , , ,

.NET Generic Function : Func & Action where have you been in my life?

April 26th, 2009

[download example project]

Screen cast @ http://dimecasts.net/Casts/CastDetails/105

Just discovered the generic delegate type in .NET that I’ve been building over and over again. (sigh) [ Don’t forget Action<T> – works the same way but returns VOID ]

Problem:

A generic function is needed to define an event handler or implement strategy pattern. Also, in the case of an event, I want to avoid sending the calling object or EventArgs<T>.

Solution:

Previously I built my own delegate.

// the wheel I re-invented

public delegate int delStrategy(int a, int b);

public class OldWay
    {
        public delStrategy Strategy { get; set; }

When I should have just used the generic function built into  the language.

public class NewWay
{

    // generic function is the wheel
    // that I re-invented over and over again (ugh)
    public Func<int, int, int> Strategy { get; set; }

Use:

// OLD WAY

OldWay oldWay = new OldWay();
oldWay.Strategy = delegate(int a, int b) { return a + b; };
Console.WriteLine("Old Way Result: " + oldWay.DoYourThing(1, 2));

// NEW WAY

NewWay newWay = new NewWay();
newWay.Strategy = delegate(int a, int b) { return a + b; };
Console.WriteLine("New Way Result: " + newWay.DoYourThing(1, 2));

// New New Way (More terse)

newWay.Strategy = (int a, int b) => return a+b;

 

The generic function / delegate has 5 overloads:

Func<TResult>

Func<String> myFoo = delegate(){ return “Foo”; }

Func<T1, TResult>

Func<String, String> myFoo2 = delegate(String st){ return st; }

Func<T1, T2, TResult>

Func<String, String, int> myFoo3 = delegate(String st, int a) { return st + a; }

Func<T1, T2, T3, TResult>

Func<String, String, int, bool> myFoo4 = delegate(String st, int a, bool b){…}

Func<T1, T2, T3, T4, TResult>

Func<String, String, int, bool, int> myFoo4 = delegate(String st, int a, bool b, int c){…}

alan.huffman C# , , , ,

Modified Closures should be a language bug

April 19th, 2009

Summary:

When you define a closure within the context of a loop, the closure is defined with the final value of anything iterated over in the loop. If this sounds strange, that’s because it is. See the simple example below.

The Code:

Download: [C# File] [Zipped Console Project]

image

The curious part is the simple PrintMe delegate that takes no arguments & returns nothing.

delegate void PrintMe();

Within the foreach loop where we iterate over the int array {1,2,3,4}, we define a closure (delegate) that merely prints i the integer being iterated.

(PrintMe)delegate(){    Console.WriteLine(i);   }

The Output:

You might expect the output, when we invoke each PrintMe delegate to be 1, 2, 3 & 4, but instead the output is 4, 4, 4, 4.

image

Solution:

By copying the value of i to a local variable j and the expected result is the actual result. We iterate over the integer array { 1,2,3,4 } and we print { 1,2,3,4 }.

This one line is the strange fix.

int j = i;

Just use j in the closure instead of i

(PrintMe)delegate()
         {
             Console.WriteLine(j);
         }

Download: [C# File] [Zipped Console Project]

image

image

alan.huffman C#, Modified Closures , , , ,