Method chaining with deferring object creation

I have decided to write a couple of posts about how I used Method Chaining to help solve and better handle the creation of test data within my Unit Tests. This post and the example code via GitHub shows how I created test data using Method Chaining in a more generic form. There will be more posts to come regarding how this test data gets persisted into a in-memory database which will get used in XUnit Tests.

For my problem, I had to build up test data that will be used within a number of Unit Tests. Creating objects and assigning values to properties through Factory classes is considered a fairly normal approach, however being able to build up objects using method chaining gives me the flexibility to create objects with different characteristics.

For example, var foo = MyFooBuilder.Create().WithName(“My Foo”).WithAge(5).WithCar(“Audi”).Build(). This allows me to build up a foo object using a nice fluent chaining of methods compared to var foo = new Foo() { Name = “My Foo”, Age = 5, Car = “Audi” }. This allows me to keep all the Foo created code in a nice and tidy builder class which provides the flexibility to extend the builder to introduce new characteristics in the future.

What I ended up creating was a generic builder class that allows me to use a object of type T, build up a set of actions to get a newly created object. for example, var foo = MyBuilder.Create().WithProperty(new { Name = “MyPropertyName”, Value = “MyValue” }).Build();

You can view my builder class at https://github.com/codelabnz/BuilderExample

Referenced Projects in a solution disappear on compile time Visual Studio 2010

Take the following example of a solution:

  • MyProject
  • MyProject.Core
  • MyProject.Infrasturcture

I decide to add a new console application called MyProject.Console. I reference the MyProject.Core into this console application. Everything is working fine until I try to build and run the console application. I get a error saying “Could not find the referenced Assembly.”.

I figured out that when I created the new console application in Visual Studio 2010 it defaulted to .NET 4 Client Profile as the framework and not .NET 4. This is because all my other projects were using the .NET 4 framework.

References

http://stackoverflow.com/questions/4286599/referenced-project-gets-lost-at-compile-time

The property could not be set to a ‘Int16′ value. You must set this property to a non-null value of type ‘Int32′.

I came across the following error when trying to map a stored procedure to a complex type in EF 4+.

The property could not be set to a ‘Int16′ value. You must set this property to a non-null value of type ‘Int32′.

The problem was the Entity Framework was thinking the return data type was Int16 but in fact the complex type value was specified as Int32.

The solution was to make sure that your results from the stored procedure are explicitly set and cast to the right data types. You can do this by using the convert function in T-SQL. Example below.

1
 select convert(int,myValue) from foo

Once you do implement this function into your stored procedures, you can update your mappings in EF and the problem will be fixed (well for me anyway).

Giving Enum’s descriptions

Enums are very good for giving descriptions to values especially numeric values. By default though a enum value name cannot have spaces. Look at the following which shows an example of no spaces between the first enum value name.

1
2
3
4
enum myEnum
{
   Icannothaveaspace = 1
}

A good way to solve this problem is to use the Description attribute from the System.ComponentModel namespace. We can use this attribute to give each enum value a descriptive meaning.

1
2
3
4
5
6
7
8
9
using System.ComponentModel;

 public enum MyEnum
    {
        [Description("Authorised Contact")]
        AuthorisedContact = 1,
        [Description("Assigned Contact")]
        CoauthorisedContact = 2
    }

From here we can create a extension method that uses reflection to get the description attribute for the selected enum value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static class Extensions
    {
        /// <summary>
        /// Get the description of a enum value using the description attribute
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetEnumDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                typeof(DescriptionAttribute),
                false);

            if (attributes != null && attributes.Length > 0)
                return attributes[0].Description;
           
            return value.ToString();
        }
    }

To use this, just call GetEnumDescription to get the description of a enum value.

1
2
3
4
5
6
7
8
9
  using Extensions; //Make sure that you use this to get the extension method
 
  public myClass
  {
      public void foo()
      {
          var myDescription = MyEnumValue.GetEnumDescription();
      }
  }

Perform ASP.NET Postback using JQuery

Came across a situation where I needed to disable the ASP.NET button using JQuery when the user clicks on the button, this is so we stop the user from clicking the button twice while the page is doing a postback.

Firstly, add the following JQuery/Javascript code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>

 function autoSubmit()
 {
 <%= ClientScript.GetPostBackEventReference(btnSaveChanges, "") %>;
 }
     $(function () {

           $("#<%= btnSaveChanges.ClientID %>").click(function () {
             $(this).attr("disabled", "true");
             autoSubmit();
           
             return false;
         });
     });
</script>

You can inject the correct generated javascript code from using the function GetPostBackEventReference between the server tags. Bind a click event to the ASP.NET server control which disables the button and call the autosubmit javascript function to perform a post back on the ASP.NET button control.

References

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

Some useful Extension Methods

Back to basics…

A couple of useful Extension methods if you are checking if a string is a valid integer or decimal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static bool IsInteger(this string value)
{
if (String.IsNullOrEmpty(value)) return false;
Int32 tmpNo;
return Int32.TryParse(value, out tmpNo);
}


public static bool IsDecimal(this string value)
{
if (String.IsNullOrEmpty(value)) return false;
Decimal tmpNo;
return Decimal.TryParse(value, out tmpNo);
}

To implement the Extension Methods:

1
2
3
4
5
6
7
8
9
var myString = "10.5";

if (myString.IsDecimal())

{

//Do something

}

Finding StoreGeneratedPattern value in EdmProperty in T4 Template

If you need to find out if a primary key in your conceptual model which is using the Identity value from the property StoreGeneratedPattern, you can use the following code: (NOTE: This is used within a T4 template)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string inputFile = @"..\EntitiesModel.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string annotationNamespace = "http://schemas.microsoft.com/ado/2009/02/edm/annotation";

foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) {
   foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity)) {
 
      MetadataProperty storeGeneratedPatternProperty = null;
      edmProperty.MetadataProperties.TryGetValue(annotationNamespace + ":StoreGeneratedPattern", false, out storeGeneratedPatternProperty);

      if (storeGeneratedPatternProperty != null && storeGeneratedPatternProperty.Value.ToString() == "Identity") {
         //We found an Identity property
      }
   }
}

You receive a “The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect” exception when using NVarchar parameters with Sqlclient

The problem

I got the following random error:

You receive a “The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect” exception when using NVarchar parameters with Sqlclient

The Solution

Its a known bug with the .Net SqlClient Data Provider.   If you have a field in the database of type nvarchar(max) or greater than 4000 characters and if the user enters data into the field greater than 4000 characters via the .Net SqlClient Data Provider you will receive an exception.

To get around this, reduce the field size to less that 4000 characters or change your type to ntext or set the Sqlparamter.size property to -1 to allow the entire data to be saved.

References




http://support.microsoft.com/kb/970519

Open XML – OLE Automation Date Issues

If you are exporting a date from C# to Excel using 2007, you probably will use the following:

1
Math.Round(DateTime.Now.ToOADate(), 12).ToString()

This exports the date as a OLE Automation date recognized by Excel 2007. How ever, in Excel 2010 this was causing issues, every time I exported to Excel 2010, it said that it has to repair my document and it never displayed the values correctly as dates.

Because I was using Open XML to generate the markup, Excel 2010 has been support for Open XML. I got around the problem of using:

1
DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffzzz");

This exports the date as a XML Date format.
Hope this helps anyone who has the same problem!

EF Strongly Typed ObjectQuery.Include

The problem that I faced was having to put up with “hard coded” strings in the ObjectQuery.Include function to load related objects through POCO objects in the Entity Framework. This faced challenges when I renamed columns in the Model which caused a run-time error when recompiling and re-starting the application. Thanks to David Kiff, we can now change the code from being strings:

1
2
3
4
using (CommuicationsEntities entities = new CommuicationsEntities())
{
entities.Order.Include("OrderDetails");
}

To a nice strongly typed includes using a IncludeBuilder class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class IncludeBuilder
{
private readonly List _propertiesToInclude;

public IncludeBuilder()
{
_propertiesToInclude = new List();
}

public void Add(Expression<Func<T, object>> propertySelector)
{
MemberExpression memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Parameter propertySelector must be a MemberExpression");
_propertiesToInclude.Add(memberExpression.Member.Name);
}

public ObjectQuery Includes(ObjectQuery query)
{
foreach (string include in _propertiesToInclude)
{
query = query.Include(include);
}
return query;
}
}

the following code calls the include builder, includes the relationship and gets a simple list with no tracking on the POCO objects.

1
2
3
4
IncludeBuilder _include = new IncludeBuilder();
_include.Add(a => a.Orders);
ObjectQuery customers= DataContext.Servers;
return _include.Includes(customers).Execute(MergeOption.NoTracking).ToList();

References:

http://davidkiff.co.uk/post/2009/08/27/EF-Strongly-Typed-ObjectQuery3cT3eInclude%28e2809ce2809d%293b.aspx