Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, September 16, 2011

Quiz: C# Async and Await. What is the Output of this Code?

C# 5.0 (CTP version at this point) has support for async and await to allow clean implementation of non-blocking IO using a task-continuation model. I was just playing with it and here's the sample code to tease your brain. Tell me what is the output of this program?

Thursday, March 17, 2011

NuGet - Why Should You Care?

Traditionally the .NET community, or more appropriately the users of .NET framework relied on products from Microsoft - so, in a product stack you are likely to see almost everything coming from Microsoft. However, some community contribution made its way into the main stream - for example, NUnit or Log4Net. But you can literally count the number of such main stream non-Microsoft products in your development stacks with your fingers (sparing a few)!
NuGet makes it easy to share your reusable library/utility code to the community. So, if you've done something cool that you wanna share, you should utilize the platform.
One important difference between your and Microsoft's contribution is, whatever you are contributing is likely to be a piece of software extracted from one of your real world projects. On the other hand, Microsoft attempts to produce something based on public interest and their imagination - often missing the real pain that you or I have. So, this mismatch between the designer and the actual consumer of the product often leaves a lot of opportunity for you. If you did something to solve your own pain on a project, its likely you're not alone. So, share it with us.
NuGet official feed and website is a great place to get feedback.
Did something cool? Well, you should feel good as people will use and appreciate your work. More importantly, they will provide you with interesting ideas and reviews that you haven't thought about. Does this sound useful to you? People will go even further - they will directly contribute to the project with code!
NuGet will challenge you with competition from other contributors.
A healthy competition is a great way of learning from others too. You'll see other contributors attacking the same pain you are solving in a different approach, often directly challenging you! You love challenge, don't you?
If you need hard numbers to get motivated, here's some data from my MvcMailer project:
  • Downloaded 600+ times in less than 2 months.
  • Received 60+ emails from people using MvcMailer, mostly encouraging feedback.
  • 300%+ increase in my blog traffic.

Bottom line is, you should publish your NuGet package if there's any cool project you have done. Or, look out for what others are doing and possibly contribute with your code/suggestions. If you need an idea, look for StackOverflow questions, you'll see there are solvable problems that people are fighting against time and again.

Friday, January 14, 2011

Social Helpers in ASP.Net MVC3 (Facebook, Twitter, Gravatar etc.)

This site shows the examples!
http://www.asp.net/webmatrix/tutorials/13-adding-social-networking-to-your-web-site

Now, the social links and buttons are no longer from a third-party source, its straight from Microsoft. I don't know if this is first-party or second-party :p

Thursday, January 13, 2011

My Article at CodeProject: MvcMailer

I just released a .Net NuGet package called MvcMailer and to get people super easily started, put an article at CodeProject.com. You are most welcome to the article at http://www.codeproject.com/KB/aspnet/MvcMailerNuGet.aspx
I welcome your comments and suggestions!

Friday, January 07, 2011

C# Named Parameters Can be Very Useful

Think about the following code example:
htmlHelper.InputHelper(InputType.CheckBox, name, "true", true /* useViewData */, false /* isChecked */, true /* setId */, false /* isExplicitValue */, htmlAttributes);
This line is taken from the source code of ASP.NET MVC, or to be more specific its a line from the InputExtension class. I think the intent of the original developer is clear:
Add comment next to arguments so that one can easily read the method call without getting lost in a who's who since there are quite some arguments to pass.
To learn more about named parameters using C#, you can visit this post by ScottGu.

Monday, December 13, 2010

DRY - Total 161 Duplicate ArgumentNullException calls in ASP.Net MVC Source Code

There are 161 occurrences of the following code pattern inside the ASP.Net MVC source code: See details of which class and which line at https://gist.github.com/739523
method(type argument)
{
  if(argument == null){
    throw new ArgumentNullException("argument")
  }


...
}
So, in total this pattern introduces 312 lines of duplicate code without whitespaces and 644 lines of duplicate code including whitespaces. And the pattern is simple, just check a condition and throw exception if its true. Not to mention, there are numerous other duplications where string.IsNullOrEmpty is used to check for string arguments.
This observation is interesting to me. Since, I think it adds a lot of noise to the code. In fact, if you randomly look at any of the methods - you have a good chance of seeing the first few lines doing this exactly similar thing. And this adds noise to me. Not to mention that, the developer needs to write the code, write tests for this code and if one needs to use this method, somehow should know this in advance that passing a null will result in an exception. But of course, this is not explicit from the method signature unless the developer also takes the pain to put a documentation styled comment and mention about this ArgumentNullException.
To remove this clutter, I think C# can introduce a few language keywords such as the follows:
public void Authenticate(required User user)
public void AddNewUser(nonblank string userName)
A compiler can very easily compile the code and put the exception throwing logic based on these keywords. Call it a syntactic sugar or a language keyword, this is the kind of translation that seems to be perfect for the compilers. And I can foresee it being used in almost all methods we write, since if the methods require an argument they do it for a purpose and most of the time null is not expected anyway!
I don't know if this will reach the people responsible for developing C#, but if it does, I think the community will really love this new language feature.
I know about workarounds using AOP or other hyped-but-seldom-used tricks to solve this problem. But these tricks often make life harder by introducing a learning curve and then punishing the learning by slowing down the application. So, its best to put in as a core language feature. What do you think?

Wednesday, January 21, 2009

A good example of C# Regular Expression: Implementing InitCap or Titleize/TitleCase using C# and Regular Expression

Ever since I first learned about the regular expressions, I have always been fascinated by its magical capability. When I first learned about DFA/NFA, I figured out how it is possible to evaluate a regular expression and eventually, during my Undergrad at BUET, I implemented a regular expression evaluator for the Compiler Lab.

Now, given this history, here is a simple code that I wrote today. Let me know if you liked it-

Program()

{

Console.WriteLine(Titleize("hello! This is a sample string for titleize!"));

Console.Read();

}

public string Titleize(string input)

{

return Regex.Replace(input.ToLower(), @"(?<space>\s*)(?<first>.)(?<rest>\S*)", new MatchEvaluator(OnMatch));

}

public string OnMatch(Match match)

{

return string.Format("{0}{1}{2}", match.Groups["space"].Value, match.Groups["first"].Value.ToUpper(), match.Groups["rest"].Value);

}

For a little explanation, the pattern @"(?<space>\s*)(?<first>.)(?<rest>\S*)" matches to a series of space followed by a word. The word is further divided into two parts, the first one is just the first character and the rest understandably captures the "rest" part of the word.

Next the OnMatch method takes each occurrence of a match of the above pattern and as shown, simply regroups the word as previous but just takes the Upper case of the first letter!

Simple? You got another good example of Regular Expression? Share with me.

Monday, November 10, 2008

RowTest Extension for NUnit

Well, I was just about to implement it myself! However, its good to see that the NUnit addin named RowTest actually allows us to do the data driven unit test through declarative programming and adding parameters to the dumb test methods!

http://www.andreas-schlapsi.com/projects/rowtest-extension-for-nunit/

Check out this website for an example and get started with RowTest.

Monday, September 01, 2008

Set and Compile using C# Language Version 2.0 in Visual Studio 2008

I know, while most of you are very happy with the new features in Visual Studio 2008, its sad that not all your deployment environments are upgraded to .Net framework 3.5. I had a similar situation as well on one of my projects.

Its great that you can just navigate to a VS 2008 project file properties and from the Application Tab select the Target .Net Framework version to use one of .Net 2.0, 3.0 and 3.5. But this doesn't solve all the problems. You will soon discover that, your application doesn't show an error when you write C# 3.0 code with the target framework set to 2.0. This is because, the IDE by default uses the latest language version by default.

To solve this problem, Navigate to project properties > Build > Advanced > Language Version and choose ISO-2 (or ISO-1). Now with this information, the VS 2008 will start showing compiler errors for features that don't comply to the version specification!

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!

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!

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!

Tuesday, June 10, 2008

[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.