Sohan's Blog

Things I'm Learning

BDD - My First BDD Code Using RSpec in Ruby

I am really really happy to see people putting so much efforts for building high quality, nearly all avoidable error free software. I am a big believer of Test Driven Development and doing TDD for about two years now. I have always had the feeling that TDD is a kind of a misnomer because to some people the term ‘Test’ refers to finding bugs. For this very reason, when people gets started with TDD, they consider it as a waste of time to write so much extra code that doesn’t necessarily find bugs!

Well, a good vocabulary always makes it more attractive and useful. Now with BDD, Behavior Driven Development, I think the vocabulary that people actually codes the behaviors and implements the behaviors, not the tests, makes it more like it.

So, lets see my first ever written RSpec ruby code and the sexy html output!

#This is a poor Stack implementation

class Stack
def initialize
@items = []
end
def push(item)
@items << item
end
def pop
return nil unless @items && @items.length > 0
item = @items.last
@items.delete item
return item
end
def peek
return nil unless @items && @items.length > 0
@items.last
end
def empty?
@items.empty?
end
end

#This is the RSpec ruby code. Isn’t is Simple?

describe Stack do
before(:each) do
@stack = Stack.new
end
describe “Empty” do
it “Should be empty when created” do
@stack.empty?.should == true
end
end
describe “With One Item (value = 3)” do
before(:each) do
@stack.push(3)
end
it “should not be empty” do
@stack.empty?.should be_false
end
it “should return the item (=3) when #peek” do
@stack.peek.should == 3
end
it “should return the item (=3) when #pop” do
@stack.pop.should == 3
end
end
end

Well, we all write codes and are doing this day and night for years. What I like to see is as sexy an output as the following from my source code :-)

RSpec

I know, you liked the output. For more you may check at http://rspec.info/

Need a similar solution on .Net? Keep Googling and come back to me if you see a good BDD tool. I would really like to use BDD in my .Net projects and see how better it performs over TDD.

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.

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!

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.

Comments

Sohan
@Dan:
Didn't know that. Thanks for sharing.
Dan
You can use also

return doc.Declaration.ToString() + doc.ToString();
Sohan
@Dragon:
Thanks for suggesting the improvement.
Dragon
I think better:

public static string ToStringWithXmlDeclaration(this XDocument doc)
{
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
doc.Save(writer);
}
return builder.ToString();
}

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!

Comments

Donald Soft Tech
An ecommerce web site without a good web application is not possible. application development is the backbone of any online business irrespective of the fact whether it is catering to a large, small or medium customer base. There are many good companies in India that make such services easy and affordable, just browse the net and make your pick…http://www.infysolutions.com
Tarok
this is very nice blog…
this is very helpful and attractive biog.
visit for asp.net help asp.net help

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-

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!

Comments

Technoverloaded
If you don’t know beforehand whether or not the variable “name” is null or not, you might want to try the Equals method.

For example, in the AdventureWorks database:

var query = from e in Employees
where Object.Equals(e.ManagerID, pManagerID)
select e.EmployeeID ;

If pManagerID == null, then LINQ to SQL generates

SELECT [t0].[EmployeeID]
FROM [HumanResources].[Employee] AS [t0]
WHERE [t0].[ManagerID] IS NULL

but if pManagerID contains a value, e.g. 109, then the SQL generated is

SELECT [t0].[EmployeeID]
FROM [HumanResources].[Employee] AS [t0]
WHERE ([t0].[ManagerID] IS NOT NULL) AND ([t0].[ManagerID] = @p0)
– @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [109]
merlin981
Great article. It is very important for developers new to LINQ to understand these ramifications. Thanks for demonstrating how the underlying code differs based on column type.

LINQ Exchange - Learn LINQ and Lambda Expressions

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!

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!

[ThreadStatic] - a Cool Attribute to Thread Safe Static Members

Usually static variables holds the same value for all the threads running at the same AppDommain. However, in a multithreaded scenario, you may need to add thread safe behavior to your static members so that the value of a static member is same inside only a single thread and across multiple threads the value can be different. In this way you may attain a thread specific or thread scoped storage to use in your application. One example is, in Log4Net you need to use ThreadContext class to store the values to be logged that are thread specific.

.Net framework has a smart and easy way of achieving it through the use of ThreadStaticAttribute class. When you apply this attribute to your static members, it will take care of the thread safety. So, from a sample C# code like the following one, you may define thread safe static members.