Wednesday, August 20, 2008

My Target items still in the 2008 learning Queue

1. Windows Workflow foundation.

2. Study about ERP and take a good look into a popular open-source ERP application.

3. Study on SOA.

4. Study on Smart Client applications.

Wednesday, August 13, 2008

Unit Testing using Mocks - FillWithMocks, Fill all or only selected properties with Mocks using only a single method call

I have been doing TDD for about two years now and using mock testing for interaction based unit testing in my projects. What I have learned over this time is, a unit testable design leads to introduction of interfaces and dependency injection for testing a code in isolation. And when I want to perform tests on my interactions, I need to create mock objects and inject these mock instances to my object under test. Sometimes, a unit test class needs to create quite a few of such mock objects and I feel this can be done using a simple wrapper around the usual mocking frameworks.

I suggest a similar and even more powerful wrapper so that you don't need to create instances for each of the mock objects, rather do it in a single call for all your desired mocks. I have shown this method for NMock2, however, its evident that you can write your own method for your favorite mocking framework just using this code as a reference.

This code is written in C# 3.0 and should compile in .Net 3.5. You will need to add a reference to NMock2 to compile this. Also, you need to know a bit about Reflection to understand the following code fragment.

Disclaimer: This code is just a simple example and it may not suit all your needs.

1 using System;

2 using System.Collections.Generic;

3 using System.Linq;

4 using System.Text;

5 using System.Reflection;

6

7

8 namespace NMock2.Extensions

9 {

10 public static class MockeryExtensions

11 {

12 /// <summary>

13 /// This method will fill all properties of the 'target' of interface type having a setter

14 /// </summary>

15 /// <param name="mocks"></param>

16 /// <param name="target"></param>

17 public static void FillWithMocks(this Mockery mocks, object target)

18 {

19 Type targetType = target.GetType();

20 PropertyInfo []properties = target.GetType().GetProperties();

21

22 foreach (PropertyInfo property in properties)

23 {

24 Type ptype = property.PropertyType;

25 if (ptype.IsInterface)

26 {

27 if(targetType.GetMethod(string.Format("set_{0}", property.Name)) != null)

28 {

29 targetType.GetProperty(property.Name).SetValue(target, mocks.NewMock(ptype), new object[] { });

30 }

31 }

32 }

33 }

34

35 /// <summary>

36 /// This method will fill the properties with names specified in the propertyNames array having a setter

37 /// </summary>

38 /// <param name="mocks"></param>

39 /// <param name="target"></param>

40 /// <param name="propertyNames"></param>

41 public static void FillWithMocks(this Mockery mocks, object target, params string[] propertyNames)

42 {

43 Type targetType = target.GetType();

44 foreach (string propertyName in propertyNames)

45 {

46 PropertyInfo pInfo = targetType.GetProperty(propertyName);

47 if (pInfo != null && targetType.GetMethod(string.Format("set_{0}", propertyName)) != null)

48 {

49 pInfo.SetValue(target, mocks.NewMock(pInfo.PropertyType), null);

50 }

51 else

52 {

53 throw new ArgumentException(string.Format("the property {0} is not found or does not have a setter", pInfo.Name));

54 }

55 }

56 }

57 }

58 }

So, with this extension method in place, you can go and write your test code in a much compact manner. The following is an example showing one possible use of this method in your NUnit test code.

83 public interface IMyInterface

84 {

85 void MyMethod(string name);

86 }

87

88 public class MyExampleClass

89 {

90 public IMyInterface MyPropertyOne

91 {

92 get;

93 set;

94 }

95

96 public IMyInterface MyPropertyTwo

97 {

98 get;

99 set;

100 }

101

102 public IMyInterface MyPropertyThree

103 {

104 get;

105 set;

106 }

107

108 public MyExampleClass()

109 {

110

111 }

112 }

113

114 [TestFixture]

115 public class MyExampleClassTest

116 {

117 private MyExampleClass _myExampleClass;

118 private Mockery _mocks;

119

120 [SetUp]

121 public void Init()

122 {

123 _myExampleClass = new MyExampleClass();

124 _mocks = new Mockery();

125

126 //This call fills all the three properties with mocks

127 _mocks.FillWithMocks(_myExampleClass);

128

129 //This call fills only MyPropertyOne and MyPropertyTwo with mocks

130 _mocks.FillWithMocks(_myExampleClass, "MyPropertyOne", "MyPropertyTwo");

131 }

132 }

Comments are welcome!

Tuesday, August 12, 2008

XDocument.ToStringWithXmlDeclaration() - Get the string representation of XDcoument with its Xml Declaration

The System.Xml.Linq.XDocument.ToString() produces a serialized string version of the XDocument object. But unfortunately, while doing so, it leaves the xml declaration in the serialized version which may be required in your application.

Again, there is another method called Save that produces the serialized version including xml declaration. So, I think we can write a simple extension method for producing the xml declaration as shown in the following -

14 class Program

15 {

16 static void Main(string[] args)

17 {

18

19 XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("root"));

20 Console.WriteLine(doc.ToStringWithXmlDeclaration());

21 }

22 }

23

24

25 public static class XDocumentExtensions

26 {

27 public static string ToStringWithXmlDeclaration(this XDocument doc)

28 {

29 StringBuilder builder = new StringBuilder();

30 StringWriter writer = new StringWriter(builder);

31 doc.Save(writer);

32 writer.Flush();

33 return builder.ToString();

34 }

35 }

Apart from its purpose, this is also an example use of the Extension Method feature of C# 3.0.

Monday, August 11, 2008

Simple Wildcard replacement on the Rendered Html of Asp.Net Page

This is a simple solution for implementing wildcard replacements in your asp.net pages. You may use this, if you want to replace some tokens / merge codes in the asp.net generated html by your personalized values.

System.Web.UI.Control has a virtual method called 'Render' of the following signature -

protected internal virtual void Render(
HtmlTextWriter writer
)

Since, all your ASP.Net pages and server controls are subclasses of this Control class, you can override this method and manipulate the html that's rendered from this control. So, using this method, we will intercept the render method and apply a global replacement on the tokens present in the generated html. The C# code looks like the following one -

21 protected override void Render(HtmlTextWriter writer)

22 {

24 MemoryStream stream = new MemoryStream();

25 StreamWriter memWriter = new StreamWriter(stream);

26 HtmlTextWriter myWriter = new HtmlTextWriter(memWriter);

27

28 base.Render(myWriter);

29 myWriter.Flush();

30

31 stream.Position = 0;

32

33 string renderedHtml = new StreamReader(stream).ReadToEnd();

34

35 renderedHtml = renderedHtml.Replace("$Name$", "Sohan");

36

37 writer.Write(renderedHtml);

38 writer.Close();

39 myWriter.Close();

40 stream.Close();

41 }

So, the steps are -

1. Intercept the rendering - override the Render method.

2. Get the generated html - invoke the Render method on the base class supplying it a simple memory stream writer. Then read the html from the stream. You can also make use of other TextWriter implementations including StringWriter.

3. Apply your replacements - use simple string.Replace or Regex.Replace for more control.

4. Now, write the replaced content on the original writer.

Hope it helps!

Thursday, August 07, 2008

Log4Net SmtpAppender and sending emails with log messages

Since my client asked me if it was possible to generate emails for log entries on an error/fatal level I took a look into the Log4Net SmtpAppender. In your project you may need to implement a similar function and in that case you may use a log4net configuration like the following one-

93 <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">

94 <to value="" />

95 <from value="" />

96 <Username value=""></Username>

97 <password value="" ></password>

98 <authentication value="Basic"></authentication>

99 <subject value="test logging message from log4net" />

100 <smtpHost value="" />

101 <bufferSize value="512" />

102 <lossy value="true" />

103 <evaluator type="log4net.Core.LevelEvaluator">

104 <threshold value="INFO"/>

105 </evaluator>

106 <layout type="log4net.Layout.PatternLayout">

107 <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />

108 </layout>

109 </appender>

110

111 <root>

112 <level value="DEBUG"/>

113 <appender-ref ref="LogFileAppender"/>

114 <appender-ref ref="SmtpAppender"/>

115 </root>

I had to use the username and password as my server requires authentication. Now, in case your server don't demand authentication, you can avoid using these two nodes as well as the authentication node. You can also specify the port name if your smtp server is not using the default port.

Doing so keeps you posted of the error conditions early since sometimes finding an error entry by periodically checking is missed. Hope this helps someone with similar need.

Tuesday, August 05, 2008

Comparing with NULL in where clause using Linq to SQL

In SQL Server, a SQL statement like 'NULL=NULL' evaluates to false. however 'NULL IS NULL' evaluates to true. So, for NULL values in your database columns, you need to use the 'IS' operator instead of the regular '=' operator.

The problem is, in Linq to SQL, there is no such 'IS' operator since 'IS' is already used as a C# language keyword. So, when you are invoking an equality check in your Linq to SQL where clause to a nullable column you need to be alert on this behavior.

For example, take the following sample code that I wrote to demonstrate this topic.

1 using System;

2 using System.Collections.Generic;

3 using System.Linq;

4 using System.Text;

5 using System.IO;

6

7 namespace ConsoleApplication1

8 {

9 class Program

10 {

11 static void Main(string[] args)

12 {

13 MyDataContext context = new MyDataContext();

14 context.Log = new ConsoleWriter();

15

16 string name = null;

17 var aff = from a in context.Affiliates

18 where

19 a.CompanyName == name

20 select a.ID;

21 var aff2 = from a in context.Affiliates where a.CompanyName == null select a.ID;

22

23 aff.ToList();

24 aff2.ToList();

25 }

26 }

27

28 class ConsoleWriter : TextWriter

29 {

30

31 public override Encoding Encoding

32 {

33 get { return Encoding.UTF8; }

34 }

35

36 public override void Write(string value)

37 {

38 base.Write(value);

39 Console.WriteLine(value);

40 }

41

42 public override void Write(char[] buffer, int index, int count)

43 {

44 base.Write(buffer, index, count);

45 Console.WriteLine(buffer, index, count);

46 }

47 }

48 }

In this code, I have attached a sample logger to my DataContext so that all my queries are logged. Now I ran two queries. Lets take a look at the first query and its logger output,

16 string name = null;

17 var aff = from a in context.Affiliates

18 where

19 a.CompanyName == name

20 select a.ID;

The logger output after executing this query is, as follows -

SELECT [t0].[ID]
FROM [dbo].[Affiliates] AS [t0]
WHERE [t0].[CompanyName] = @p0

-- @p0: Input VarChar (Size = 0; Prec = 0; Scale = 0) [Null]

So, you see that although a null is assigned in the variable 'name', the Linq to SQL generated query uses the '=' operator which may lead to undesired results.

However, the second query and its logger output looks like the following -

21 var aff2 = from a in context.Affiliates where a.CompanyName == null select a.ID;

SELECT [t0].[ID]
FROM [dbo].[Affiliates] AS [t0]
WHERE [t0].[CompanyName] IS NULL

Here, the generated query uses the 'IS' operator which is desirable.

In case, you want Linq to SQL to generate the first code using 'IS' operator, you may use something like the following one -

26 var aff3 = from a in context.Affiliates

27 where

28 ((name == null && a.CompanyName == null) || (a.CompanyName == name))

29 select a.ID;

This query produces the following SQL code -

SELECT [t0].[ID]
FROM [dbo].[Affiliates] AS [t0]
WHERE ([t0].[CompanyName] IS NULL) OR ([t0].[CompanyName] = @p0)

So, to end, whenever you are writing a where clause on a nullable column using Linq to SQL, make sure you know the consequences and take measures accordingly.

Happy coding!

Monday, August 04, 2008

JQuery - I will consider using it in my future web project

I find the problems with cross-browser issues with Javascript to be bothering at times. Also, I am most annoyed with Javascript because, with Javascript, I need to think about another programming language along with my server side programming. I have a feeling that Javascript codes make the web application harder to test using various automated test frameworks and adds complexities as there are different browsers who interpret the Javascript code in different ways.

As I have always preferred to write only as few lines of Javascript as I can, I found JQuery to be an interesting choice. I have just taken a look into the documentation and wish to use it in a future project.

One thing about JQuery is, the code looks a little hard to read to me in some cases. The use of anonymous methods and callbacks should be standardized and I suggest, its better to write and refer to actual methods instead of the unreadable anonymous methods all around.

You may wish and take a look at JQuery at http://www.JQuery.com for more!

Sunday, August 03, 2008

Ninject - Dependency Injection Framework for .Net Objects

I loved Ninject because

- I don't love to write/edit XML documents myself.

- I think Ninject can save a lot of coding and debugging time.

- This is a cool framework :-) with a fun-to-read documentation.

- It uses simple conventions and Attributes for resolving most dependencies behind the scene.

- You can take full advantage to lambda expressions for writing compact codes.

Today, I took a look into this Ninject framework. I have used Spring.Net and Unity in my previous and current projects. But seems like Ninject has the most 'fluent vocabulary' that lets you develop on most 'fluent interfaces'.

Take a look at the fun-to-read documentation at http://dojo.ninject.org/wiki/display/NINJECT/Home and enjoy the 20 minutes while you eat the whole document!