LinqFu: Dynamic Linq in NHibernate 3.0 (Alpha 3) Linq Provider (part 2 of n)

By following the Dynamic Linq sample from ScottGu’s post, I was able
to use the new Linq provider in NHibernate 3.0 Alpha 3 to create
dynamic Linq statements for NHibernate. The idea is to incorporate
the Visual Expression Builder for Dynamic Linq to allow users to
create their own data filters. Simply copy the Dynamic.cs file from
the DynamicQuery sample and replace the second method
with the following:
public static NhQueryable<T> Where<T>(this IQueryable<T> source,
    string predicate, params object[] values) {
    if (source == null) throw new ArgumentNullException("source");
    if (predicate == null) throw new ArgumentNullException("predicate");
        LambdaExpression lambda = DynamicExpression.ParseLambda(
            source.ElementType, typeof(bool), predicate, values);
        return new NhQueryable<T>(source.Provider,
            Expression.Call(
                typeof(Queryable), "Where",
                new Type[] { source.ElementType },
                source.Expression, Expression.Quote(lambda)));
    }

NOTE: I wasn’t able to get it to work with NHibernate 2.1’s Linq Provider as NHibernateQueryable didn’t inherit from IQueryable. I tried for most of the day to weave my way through it but thought it might just be easier to try the new version of NHibernate and upgrade the references in my app than to create maintenance work for myself in the future.

LinqFu: Linq in Linq (part 1 of n)

I had to perform some LinqFu today where I used a Linq expression within a Linq expression and thought I would post a reminder to myself about what I did and how I did it. Looking at it afterward, I’m surprised it was as simple as it was. *shrug* I guess that’s how these things go.
 
Basically, it’s the equivalent of selecting an order based on its order items (to use the classic relationship scenario).
 
var value = 10;
 
if ((from order in orders where order.Items.Any(item => item.Value >= value) select order).Any()) { //Any orders w/item whose value is >= value
   MessageBox.Show(string.Format("There are orders with items greater than or equal to ‘{0}’, value));
}

Simple Object State Awareness

Through the implementation of two custom interfaces (IClonable<T> and IStateAware) and one from the .NET framework (IEquatable<T>) it becomes pretty simple to create a class that’s state-aware. The IClonable<T> interface is simply a representation of the Prototype Pattern that I have made a sample of on my website previously.
 
Here are the two custom interfaces:
 
     public interface IClonable<T> {
          T Clone();
     }
 
     public interface IStateAware {
          void StoreCurrentState();
          bool HasChanged { get;  }
     } 
 
Here’s a sample implementation:
 

     public class MyClass : IClonable<MyClass>, IEquatable<MyClass>, IStateAware {

          MyClass currentState;

 

          public string FirstName { get; set; }

          public string LastName { get; set; }

 

          public MyClass Clone() {

               return (MyClass) MemberwiseClone();

          }

 

          public bool Equals(MyClass other) {

               return other.FirstName == FirstName &&

                         other.LastName == LastName;
          }
    

         public void StoreCurrentState() {

               currentState = Clone();
          }

 

          public bool HasChanged {

               get {

                    if(currentState == null) return false;

                    return !Equals(currentState);

               }
          }

     }

 
Now I can take a snapshot of the object at any time and determine if it has changed later on.
 

Object Validation in an Extension Method

I was trying to find a way to define the state of an object based on a set of rules and assign a name to that set of rules that, then defines the state of the object. Here’s what I came up with:
 

     public static class Extensions {

          public static bool Is<T>(this T item, Predicate<T> conditions) {

               return conditions(item);

          }
     }
 
This allows me to define the conditions of any object such that I can give a name to its state based on how the business speaks about the object:
 

     Predicate<MyObject> InACancelledState = (x => x.Cancelled.HasValue);

 

This leads me to be able to code fluently about the state of the object at runtime:

     if (obj.Is(InACancelledState)) {

          // Do some stuff

     }
 
 
 

Publishing ClickOnce Applications to Run Side-by-side for Different Environments from the Command Line using Nant

Note:
The following information relates to .NET 3.5 and NAnt 0.85.
 
Preamble
I struggled with this for quite some time. I was trying to run a command-line, clickonce deployment of my application to enable it to run side-by-side for the different environments (development, quality assurance, user acceptance testing, and production). Kavinda Munasinghe’s blog post, Deploying ClickOnce on Multiple Environments was a fantastic start. It also referenced a former coworker, Neil Bourgeois, and his post, Click Once deployment using NAnt. Neil’s article looked like too much manual lifting as MSBuild should have the ability to take in some command-line parameters to do this properly as it is possible to accomplish the goal os side-by-side applications if performed within visual studio. The problem was figuring out which command-line switches to pass to MSBuild to get it to work.
 
The Keys are 3
  1. ProductName – This will identify each instance uniquely. I would recommend indicating each instance by its target environment to help users know which one they are running as well as knowing which one they are uninstalling if using Add/Remove Programs. e.g. <Product Name> – Development
  2. SignManifests – This was the one parameter missing from Kavinda‘s post that was forcing the value for publicKeyToken (a part of the application identity that must be unique to allow the applications to run side-by-side) to always remain at a value of "0000000000000000".
  3. ManifestKeyFile and ManifestCertificateThumbprint – These values are what are used to actually sign the manifest. These were what Kavinda was correctly noting in the article.

The Result

I have one exec task in my nant script that takes in parameters that are set by running a target specific to the intended environment:

<!– deployment properties –>
<
property name="publisher.name" value="My Company Name" />
<
property name="publish.output.base.dir" value="\UNCLocationDeploymentProductName" />
<
property name="product.name.base" value="ProductName" />
<
property name="product.name" value="SET_BY_TARGET__DO_NOT_CHANGE_HERE" />
<
property name="build.label" value="SET_BY_TARGET__DO_NOT_CHANGE_HERE" />
<
property name="publish.output.dir" value="SET_BY_TARGET__DO_NOT_CHANGE_HERE" />
<
property name="manifest.certificate.thumbprint" value="SET_BY_TARGET__DO_NOT_CHANGE_HERE" />
<
property name="manifest.key.file" value="SET_BY_TARGET__DO_NOT_CHANGE_HERE" />

<target name="deploy.to.dev">
    <
property name="publish.output.dir" value="${publish.output.base.dir}Development"
/>
    <
property name="manifest.certificate.thumbprint" value="003dd8c1fca443b398d240a54a7e47f2"
/>
    <
property name="manifest.key.file" value="certificatesdevelopment.pfx"
/>
    <
property name="product.name" value="${product.name.base} – Development"
/>
    <
call target ="deploy.common"
/>
</
target

 <target name="deploy.common">
    <
exec program="MSBuild.exe"  
              commandline=MyProject.csproj /target:rebuild;publish /property:ProductName="${product.name}";
                                     PublisherName="${publisher.name}";
                                     SignManifests=True;
                                     ManifestKeyFile=${manifest.key.file};
                                     ManifestCertificateThumbprint=${manifest.certificate.thumbprint};
                                     BootstrapperEnabled=True;
                                     CreateDesktopShortcut=True;
                                     UpdateRequired=True;
                                     UpdateMode=Foreground;
                                     MinimumRequiredVersion=${build.label};
                                     AssemblyVersion=${build.label};
                                     ApplicationVersion=${build.label};
                                     Install=True;
                                     Configuration=Release;
                                     Platform="Any CPU";
                                     OutDir=……${build.dir;
                                     OutputPath=${publish.output.dir};
                                     PublishDir=${publish.output.dir};
                                     PublishUrl=${publish.output.dir};
                                     InstallUrl=${publish.output.dir};
                                     UpdateUrl=${publish.output.dir}
                                      /nologo /verbosity:quiet basedir="${framework.dir}"/>
</target>

There are a few extra items in there that force this application to be installed locally as well as always remain at the latest version that are not applicable to this post, but I am leaving them in there for completeness.

 

Scalability and Massive-Capacity Sites

This post is a collection of thoughts and comments from some divergent sources on database organization that I have had in storage for some time:

Dare Obasanjo‘s Posts
Dare Obasanjo has posted at least a couple of times on database normalization (or denormalization); in his article When Not to Normalize your SQL Database, and, more recently in his article, Project Cassandra: Facebook’s Open Source Alternative to Google BigTable.

Jeff Attwood‘s Posts
Jeff Attwood also chimed in with his Maybe Normalizing Isn’t Normal article. I am particularly interested in the "database war stories" list that Jeff has in the post as they are all very interesting stories from very successful companies.

InfoQ Interview with Dan Pritchett
In the interview with Dan Pritchett on Archetecture at eBay, Dan drops some pretty large pearls of wisdom:
Evaluating the importance of data: "Paypal.com uses transactions but eBay.com doesn’t use transactions". "A lot of it is driven by availability." "There’s critical data and non-critical data". "Out of necessity, we have to split our databases."

One comment I was wondering about, "there’s just data we’re willing to lose", leads me to ask, "why are you collecting it?"

Leveraging where processing occurs based on performance – "Primary key joins are, actually, far more efficient to do in the database than they are in app space"

"We want the database to be, essentially, a reliable data store and keep as much stuff as possible in logic so we have more control over it. … same reason we don’t use stored procedures. Anything that happens in the database is invisible to the developer for all practical purposes."

Getting CruiseControl.NET working under IIS7

This was painful. Here’s some tips:

  1. Ensure that Windows Firewall Allows the ports used by CruiseControl.NET (the web port [80] and remoting port [21234]) open. Start > Settings > Control Panel > Windows Firewall > Allow a program through Windows Firewall > Exceptions Tab.

    For the Web Port, ensure that World Wide Web Services is checked.

    For the reporting port (used by CCTray) click Add port > Name: <Whatever you want> > Port number: 21234 > Protocol: TCP > Click OK. 

    Note: Don’t try and turn off Windows Firewall if you are connecting to the machine remotely. It’ll disconnect you. Don’t do it.

  2. Allow Double Escaping in IIS7 by issuing the following command (see MS KB Article 942076):
    Appcmd set config "Default Web Site" /section:system.webServer/Security/requestFiltering -allowDoubleEscaping:True
  3. If you just installed the base IIS without any additional features, you’ll likely get an HTTP Error 500.19.

    To resolve this, ensure you turn on ASP.NET Application Development Feature for IIS. Control Panel -> Program and Features -> Turn Windows Features On
    or Off -> Internet Information Services -> World Wide Web
    Services -> Application Development Features -> check/uncheck
    ASP.NET (Thank you advapi for this article).

  4. Oh… and… yeah.. the default installation uses a vbs script to create the ccnet virtual directory. This didn’t work for me. Manually creating the Virtual Directory in IIS and then promoting it to an application did.

There are baby steps, then there are leaps and bounds

Flat out; buy the book, Agile Testing: A Practical Guide for Testers and Agile Teams.

I attended a presentation by Janet Gregory during the lunch hour, cordially hosted by the Edmonton Agile User Group. This presentation, and the content in this book, fills what has traditionally been what I have witnessed to be a HUGE gap in the implementation of Agile processes at any organization.

I’d love to also see these other books (tongue-in-cheek):
Agile Product Ownership: A Practical Guide for Product Owners on Managing Product Development – Your input isn’t just welcome… it’s critical
Agile for DBAs: Engaging Database Management/Development to Improve Quality and Delivery – Breaking down silos
Agile for System Administrators: Quality Product Delivery from Beginning to End – Documentation isn’t enough

Petition: Rename TDD

A little tongue in cheek, but I think that TDD (test driven design) should be renamed to DbT (Design[ed] by Test[ing]).

Reasons:
1) Design is the most important part of the TDD mantra so put it first.
2) DbT can be pronounced "debit" which is defined as "an accounting entry that results in either an increase in assets or a decrease in liabilities or net worth". Either way, the bean counters can appreciate the connotation.
3) Should help get over the hump of BDD adoption being "easier" than TDD.