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

Disabling Request Validation with ASP.NET MVC

Sometimes when dealing with POSTS and form data, you need to disable Request Validation to allow HTML/scripting data into your methods.   Traditionally with Web Forms you use <%@ Page ValidateRequest=”false” %> which turns off Request Validation, just be aware that this doesn’t work with ASP.NET MVC.

You apply the [ValidateInput] attribute to the controller action in order to make this happen.

1
2
3
4
5
6
7
8
9
[ValidateInput(false)]

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create([Bind(Exclude="Id")]Product productToCreate)

{

}

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

Fixing the EF Tracing and Caching Provider Wrapper Issue

If you have been using the Tracing and Caching Provider Wrappers for the ADO.NET Entity Framework 4.0, you might of come across this error message when creating POCO objects, adding them to a Data Context and commiting them to the database using the Caching Wrapper:

[NotImplementedException: The method or operation is not implemented.]
   EFCachingProvider.EFCachingDataReaderCacheWriter.GetName(Int32 ordinal) in EFCachingProvider\EFCachingDataReaderCacheWriter.cs:109
   System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) +8118458
   System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +267

Line 107:        public override string GetName(int ordinal)
Line 108:        {
Line 109:            throw new NotImplementedException();
Line 110:        }
Line 111:

Basically, the author’s of the code have created a wrapper for the DBDataReader class and have not implement the override methods.   This can be fixed by calling the Wrapper DataReader object methods.  This is what I have modified in the EFCachignDataReaderCacheWriter.cs file:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
using System;
using System.Data;
using System.Data.Common;
using EFCachingProvider.Caching;

namespace EFCachingProvider
{
///
/// Implementation of the  which reads the results of another data reader
/// and stores a copy in the cache.
///
internal class EFCachingDataReaderCacheWriter : EFCachingDataReaderBase
{
private DbQueryResults queryResults = new DbQueryResults();
private DbDataReader wrappedReader;
private int maxRows;
private Action addToCache;

///
/// Initializes a new instance of the EFCachingDataReaderCacheWriter class.
///
///
<span> </span>The wrapped reader.         ///
<span> </span>The maximum number of rows which can be cached.         ///
The delegate used to add the result to the cache when the reader finishes.         public EFCachingDataReaderCacheWriter(DbDataReader wrappedReader, int maxRows, Action addToCache)
{
this.wrappedReader = wrappedReader;
this.addToCache = addToCache;
this.maxRows = maxRows;
}

///
/// Gets a value that indicates whether this  contains one or more rows.
///
///
/// true if the  contains one or more rows; otherwise false.
///
public override bool HasRows
{
get { return this.wrappedReader.HasRows; }
}

///
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
///
///
///
/// The number of rows changed, inserted, or deleted. -1 for SELECT statements; 0 if no rows were affected or the statement failed.
///
public override int RecordsAffected
{
//get { throw new NotImplementedException(); }
get { return this.wrappedReader.RecordsAffected; }
}

///
/// Gets a value indicating whether the  is closed.
///
///
/// true if the  is closed; otherwise false.
///
public override bool IsClosed
{
//get { throw new NotImplementedException(); }
get { return this.wrappedReader.IsClosed; }
}

///
/// Gets a value indicating the depth of nesting for the current row.
///
///
///
/// The depth of nesting for the current row.
///
public override int Depth
{
//get { throw new NotImplementedException(); }
get { return this.wrappedReader.Depth; }
}

///
/// Gets name of the data type of the specified column.
///
///
The zero-based column ordinal.         ///
/// A string representing the name of the data type.
///
public override string GetDataTypeName(int ordinal)
{
//throw new NotImplementedException();
return this.wrappedReader.GetDataTypeName(ordinal);
}

///
/// Gets the data type of the specified column.
///
///
The zero-based column ordinal.         /// The data type of the specified column.
public override Type GetFieldType(int ordinal)
{
return this.wrappedReader.GetFieldType(ordinal);
}

///
/// Gets the name of the column, given the zero-based column ordinal.
///
///
The zero-based column ordinal.         /// The name of the specified column.
public override string GetName(int ordinal)
{
return this.wrappedReader.GetName(ordinal);
}

///
/// Gets the column ordinal given the name of the column.
///
///
The name of the column.         /// The zero-based column ordinal.
///
/// The name specified is not a valid column name.
///
public override int GetOrdinal(string name)
{
return this.wrappedReader.GetOrdinal(name);
}

///
/// Returns a  that describes the column metadata of the .
///
///
/// A  that describes the column metadata.
///
public override DataTable GetSchemaTable()
{
return this.wrappedReader.GetSchemaTable();
}

///
/// Advances the reader to the next result when reading the results of a batch of statements.
///
///
/// true if there are more result sets; otherwise false.
///
public override bool NextResult()
{
if (this.wrappedReader.NextResult())
{
this.queryResults = null;
return true;
}
else
{
return false;
}
}

///
/// Closes the  object.
///
public override void Close()
{
this.wrappedReader.Close();

if (this.queryResults != null)
{
this.addToCache(this.queryResults);
}
}

///
/// Advances the reader to the next record in a result set.
///
///
/// true if there are more rows; otherwise false.
///
public override bool Read()
{
if (this.wrappedReader.Read())
{
object[] values = new object[this.wrappedReader.FieldCount];

this.wrappedReader.GetValues(values);
SetValues(values);
if (this.queryResults != null)
{
this.queryResults.Rows.Add(values);
if (this.queryResults.Rows.Count &gt; this.maxRows)
{
this.queryResults = null;
}
}

return true;
}
else
{
return false;
}
}
}
}

Random number of items from a Generic List extension method

Here is a code snippet  for returning N number of items from a generic list using a extension method.  This requires .NET 3.5.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public static class Extensions
    {
        /// <summary>
        /// method for returning N number of random items from a generic list
        /// </summary>
        /// <typeparam name="T">Item type</typeparam>
        /// <param name="list">Generic list we wish to retrieve from</param>
        /// <param name="count">number of items to return</param>
        /// <returns></returns>
        public static IEnumerable<T> Randomize<T>(this List<T> list, int count)
        {
            List<T> randomList = new List<T>();
            Random random = new Random();

            while (list.Count > 0)
            {
                //get the next random number between 0 and
                //the list count
                int idx = random.Next(0, list.Count);

                //get that index
                randomList.Add(list[idx]);

                //remove that item so it cant be added again
                list.RemoveAt(idx);
            }

            //return the specified number of items
            return randomList.Take(count);
        }

        /// <summary>
        /// method for returning 1 item from the generic list
        /// </summary>
        /// <typeparam name="T">Item type</typeparam>
        /// <param name="list">Generic list we wish to retrieve from</param>
        /// <param name="count">number of items to return</param>
        /// <returns></returns>
        public static T Randomize<T>(this List<T> list)
        {
            return Randomize(list, 1).FirstOrDefault();
        }
    }

used in code by calling the following: List<mytype> = myGenericList.Randomise(5) or mytype = myGenericList.Randomise();

The custom tool ‘MSLinqToSQLGenerator’ failed. Unspecified error

I kept getting this error “The custom tool ‘MSLinqToSQLGenerator’ failed.  Unspecified error.   For me, this was caused when I was using partial classes and had several using statements at the top of the file:

using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;

{namespace}

{code}

To get around this, I removed the using namespaces and ran the custom build tool, then readded the using statements which resolved my issue.   This issue apparently is in SP1 VS2008!

References:

http://blog.unidev.com/index.php/2008/09/02/the-custom-tool-mslinqtosqlgenerator-failed-unspecified-error/

Interview Questions Part 1

Over the past month, I have been interviewed by several companies and I thought I would share some of my experiences.   Here are some of the questions I was asked (Technical):

  • What is the difference between a reference type and a value type?
  • What is the difference between a stack and a heap?
  • What is the GAC?
  • Is a String a reference type or value type?
  • Can you inherit a class from two different classes?
  • What is a interface? What is the difference between a interface and a class?

Some other non-technical factors to consider..out of the four companies I saw, all of them use SCRUM.