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.

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

}

Back to Basics – Deleting Cookies using ASP.NET

You cannot instruct ASP.NET to physically remove cookies from the user’s computer so you have to tell the user’s browser to modify the cookie in order to trigger the browser to remove the cookie.

See code example:

1
2
3
4
5
6
7
8
9
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i {
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie);
}

 

References:

http://msdn.microsoft.com/en-us/library/ms178194.aspx#Y5776

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!

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

Exam 70-536 Part 1 – The journey begins…

I’m beginning my journey into the world of Microsoft Certification.   Why? The biggest reason is that the company I’m working for encourages professional development so I have taken up the challenge and the opportunity to sit a few Microsoft Exams.   But my biggest reason why is getting one step closer to obtaining a Doctorate in IT.   Well, lets take a step back…its a step closer to obtain a Masters degree from Charles Sturt University (Master’s in System Development .NET stream).  Yes, you can credit your .NET 3.5 exams towards a masters degree.

So, I will be studying my way through the Application Framework Foundation Microsoft Training Kit, but I came across this interesting Wiki which is kept up to date: http://en.wikibooks.org/wiki/.NET_Development_Foundation.

Wish me luck..until part 2.

References:

http://en.wikibooks.org/wiki/.NET_Development_Foundation

IT Masters Degree Programme