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

MySqlConnector working on Visual Studio 2011 Beta

I’m currently working on a project using the latest and greatest (perhaps not?) Visual Studio 2011 Beta with mysql. It’s quite a painful task at the moment as i’m using the Entity Framework as my ORM. However, for all of you who want to get the MySqlConnector working with Visual Studio 2011 Beta, then I suggest you visit this page. It’s in a different language so make sure you have your favorite language translator ready. It’s a good start, but it still doesn’t integrate into the Entity Framework section so you cannot generate models etc from mysql databases in VS 2011 Beta. At the moment I’m using the Code First approach with an existing mysql database and using the Fluent API to map the fields together, what a task!

http://social.technet.microsoft.com/wiki/pt-br/contents/articles/10476.instalando-mysql-connector-no-visual-studio-2011-beta.aspx

Tracking and Not Tracking Objects returned from SqlQuery in Entity Framework

If you don’t want objects to be tracked by the context, you can do this:

1
2
3
4
public ObjectResult<MyObject> GetData()
{
         return this.Database.SqlQuery<MyObject>("call GetData(@p0,@p1,@p2,@p3)", 1, 2, 3, 4);
}

If you want to track objects by the context, you can do this:

1
2
3
4
public ObjectResult<MyObject> GetData()
{
     return ((DbSet<MyObject>)this.MyObjects).SqlQuery("call GetData (@p0,@p1,@p2,@p3)", 1, 2, 3, 4);
}

The different is when you call SqlQuery from the objects DbSet, this will automatically track objects with the current database context.

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

}

OrderBy making null records come last Entity Framework and Linq

Ever want to sort your result set but make sure the records with a null sorting column appear last?
See the example below

1
2
3
4
5
6
7
8
9
10
var results = (from x in EntityObjectContext.MyTable
              select x
              into grp
              select new
              {
            mydata = grp,
            myid = grp.id,
            mysortingentity = grp.mysortingentity
              }
             ).OrderBy(x => sortingcolumn == null).ThenBy(x => x.mysortingentity.Name).ThenBy(x => x.myid);

Watch this space, this can easily be transformed into a Extension Method. Check out this link http://tahirhassan.blogspot.com/2010/06/linq-to-sql-order-by-nulls-last.html, this Extension method works for LinqToSQL.

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
      }
   }
}