Sohan's Blog

Things I'm Learning

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.

Comments

Anonymous
The pattern could be much easier:
=======================================
public string Titleize(string input)
{ return Regex.Replace(input.ToLower(),
@"(?<first>\b\w),new MatchEvaluator(OnMatch));
}
public string OnMatch(Match match)
{ return match.Groups["first"].Value.ToUpper(); }
Sadique
Yes, this is a nice example of power of regular expression. Here is a nice article to learn quickly the grouping of match & several useful links of regular expression.

Solution to JavaScript File Include Problem From ASP.Net MasterPage

You can include javascript files using a simple script tag. However, you will soon discover that, when you are using this master page from content pages that are at different levels in folder hierarchy then the script files will be missing at some cases. This is due to the fact that, script file paths are referenced relative to the content page and NOT to the master page. As a result, despite having the correct include wrt the master page, your content pages may still miss the scripts!

The solution is simple. Add this following line (of course, replacing the sample values with your own ones) to your master page’s page load method to add the script tag through code instead of through markup.

this.Page.ClientScript.RegisterClientScriptInclude(“YourKey”, ResolveUrl(”~/Scripts/myscript.js”);

Hope it saves you from the pain of adding a common js file into each of your content pages.

Comments

Sohan
Thank you Yoann for your comment. I will check your solution.
Yoann
You may also put a System.Web.UI.HtmlControls.HtmlLink in the Head Content Place Holder which is runat=”server” so relative url works.

Asp.Net Membership: How to Change a User’s Password From an Admin Account Without Knowing the Current Password?

Like mine, you may also need to change a user’s password from an admin account. By default, when you are using ASP.Net authentication and storing the password in the hashed format, you will not be able to see the existing password in its decrypted form. Also, to change a password using the Membership API, you will need to know the existing password. However, here is a simple solution to the problem -

AspNetChangePassword

The idea is, you can reset the password of a user using the following code-

string tempPass = Membership.Provider.ResetPassword(“username”, string.Empty)

Make sure you have the config that allows you to change password without an answer to the security question. Now, you can invoke the ChangePassword method using this tempPass as the existing pass and your custom password as the new password. Refer to the following line for a compact implementation-

Membership.Provider.ChangePassword(“username”, Membership.Provider.ResetPassword(“username”, string.Empty), “custompass”)

I believe this will save your time with a similar need.

Part 1: How Am I IMPACTing Following Scrum?

In a previous post in this blog, I introduced the nice little acronym IMPACT for agile. To recap, here is what IMPACT stands for -

“Iterative and Incremental development of a software by means of Merciless refactoring, Peer reviews, Automated acceptance testing, Continuous integration and of course, Test driven development”

To give you a little background around my story, let me tell you about a project that I am working since June 2006. The project is a micro-finance loan application automation server for the US financial industry. It acts as a mediator between a loan seeking customer and one of over 50 lenders in an attempt to get a loan for the customer. So, the server adds value by taking a single application to 50 odd lenders from a single submission unless no lender is left untried or some lender says ‘yes’ to it. This is done in real time, the processing time in average is less than 3 minutes.

Now that you have the background, let me introduce the the challenges associated with this project. The bullet points are-

  • Since this involves real dollars, there is nearly no margin for an error.
  • It processes more than a thousand loan applications per hour, so a high availability is a must.
  • This is done following agile Scrum and each two week one/two new lending partners need to be integrated.
  • The lending partners change their integration API from time to time and we need to accommodate the changes ASAP.

To address these challenges this is how we are responding-

Iterative and Incremental development (IID)

We are following Scrum and using ScrumPad to manage the IID. Basically, our clients/product owners put new requirements in terms of user stories in the product backlog at ScrumPad. So, with the prioritized product backlog we, the team, pick items to a sprint’s backlog. Then as usual, we break it down to tasks and do everything that it takes to meet the deadline of two weeks. Within a sprint the following are the milestones-

Day 1 Day 2 Day 3 Day 4 Day 5 Day 6 Day 7 Day 8 Day 9 Day 10
Sprint Planning Dev & Test Dev & Test Dev & Test Dev & Test Dev & Test Dev & Test Dev & Test Test Release Production Release
  • 8th day - Sprint works are completed.
  • 9th day - Test delivery at a near production environment and feedback gathering from product owner.
  • 10th day - Incorporate feedbacks and release in production.

Note that, we generally produce a number of test releases within the first 8 days. That gives us an earlier chance to gather client feedbacks.

The beauty if this approach is, with this model in place we can release as early as in 8 working days, if not earlier. So, this helps us meeting the last two challenges as mentioned above.

Merciless refactoring

Developing incrementally offers much challenge in attaining the longevity of the product. Because, naturally as new features come in, we need to make room for that in the existing implementation.To ensure the quality and life of the product, we do merciless refactoring as we go. We have over 90% unit test coverage, which helps us in doing this continuous refactoring. So, the idea is-

  • Writing unit test and acceptance test.
  • Refactoring our code/design and validating against automated tests.

Peer reviews

This is probably the most important practice that I recommend. Because, as we had new members in the team, we found that the quality was somewhat degrading. Once, we started peer reviews, it was very helpful to the new comers as well as the veterans to keep the code quality up to the mark. We review the following things-

  • Naming of variables, methods, classes, files, namespaces etc.
  • Use of private methods for increased readability.
  • Hard coded string literals or constants.
  • Long/nested loops and long running if-else blocks.
  • Code commenting.
  • Quality of coding.

I would suggest you to try Microsoft’s Stylecop, it will give you a great head start to ensure the first level code quality by enforcing the common rules. This practice is allowing us to continue the good quality over time.

I have always been shy of reading extra large text in the web. So, I thought I could better post this in two parts! I assure, next post will contain more images than texts, So, you better stay tuned for the next one…

Comments

Sohan
@Hasan,
Thanks for the complement!
Yes, I am promoting the acronym. I believe this acronym somehow unites the best practices all in a single word. Just like how we need to unite these to make the most of our efforts!
hasan
nice acronym sohan bhai, lets spread the agile IMPACT!!

IMPACTing for Agile Software Development

Well, next time on a dev job interview when someone asks you the question, Can you give us a brief idea on agile software development engineering practices?”, you are probably gonna laugh on your mind and just answer, “IMPACT!”. Yes, this is it, compact and right on target!

Today, I came up with this acronym about agile engineering practices and I think its a nice one :-)

IMPACT can be elaborated as follows-

I for Iterative and Incremental Development
M for Merciless Continuous Refactoring
P for Peer Code Reviews
A for Automated Acceptance Tests
C for Continuous Integration
T for Test Driven Development

For all you agile folks out there, I hope this IMPACT makes sense to you! I have found many people to take agile as a panacea and start getting skeptical as soon as they feel the heat in real life. Well, we all know, there is no free lunch! So, lets get our feet on track and do the first things first.

What are the first things? The answer is, IMPACT, if you really want to create a positive impact out of agile methods.

Comments are welcome!

Comments

Sohan
Thanks!
Alexander Beletsky
I really liked the idea of Impact :) nicely done!
Sohan
Syed,
Thanks for sharing your idea. I also think peer reviews are applicable to design and user stories.
Syed
Good one. I like it. Maybe ‘P’ should stand for Peer review of stories/design/code, and not just code.

Delving Into Client Side Capabilities of ASP.Net Ajax

I believe the client side scripting capabilities of ASP.Net Ajax is not utilized by many ASP.Net developers. This is most probably due to the fact that, not many people are aware of it at the first place. Also, since most of the javascripts are rendered secretly (read, not blatantly, which is good), most developers don’t even feel the existence of the underlying javascript at all.

Two very simple examples of the client side library are given here as examples -

1. Did you know, if you have the following javascript method, it will be automatically called when your page’s DOM is finished loading?

function pageLoad(sender, args) {
}


2. Do you know the following javascript code will add an event handler to catch whenever an asynchronous post back is completed?



Sys.WebForms.PageRequestManager.instance.add_endRequest(endRequestHandler)


These are just very little glimpses of the big scenario. To uncover more, visit the official MSDN documentation at http://msdn.microsoft.com/en-au/library/bb398822.aspx


If you are new to this, I assure, you will have a much better knowledge about ASP.Net Ajax scripting than ever before and can produce better quality javascript for your ASP.Net websites.


Happy digging!

Iterative and Incremental Implementation of Code Reviews

Extreme Programming (XP) advocates for a pair-programming, taking the code review to its extreme. I have also found that pair programming generates a lot of speed and also helps producing better quality product in the first time. But, at the same time it’s difficult to impress the management or prove return on investment associated with pair programming to the business people. So, what is the best possible solution? I believe, we can implement frequent peer code reviews to mimic the pair programming to some extent and get the benefit out of it.

In our team, we started implementing code reviews as we now recognize that there is no way to live without it. As usual, our approach is an iterative and incremental approach. So, we are taking small steps and eventually embracing the best practices in the team. I would like to share our plan here in this blog. The review process goes on the following work flow-

“When I am done with my work on task, I commit the code with the reviewer’s name on the svn comment. CCNet automatically builds and sends a mail to the reviewer. The reviewer gets the review email through a filter and reviews the code and sends his feedback to me via IM/email.”

Sprint #1: Review all the names or classes, files, methods, variables and so on. So, the reviewer emphasizes on the names and provides feedback on the following things-

1. Is the naming standard correctly followed?

2. Is this a meaningful identifier?

3. Does the name conform to the conventions used elsewhere in the code?

Sprint#2: Review the use of private methods and code structure. The to-do list is -

1. Would it make more sense to put some code into the private method for readability and/or reusability?

2. Is there any hard-coded constant directly used without referring to a const/readonly data type?

3. For all the methods, is it possible to reduce the dependency by using a simple parameter instead of a whole object?

4. Learn from sprint#1 and use the common learning.

Sprint#3: Review the use of loops, if-else blocks. At this iteration, the to-do is-

1. Is it possible to eliminate a loop?

2. Is it possible to avoid the nested loops?

3. Is there a large if-else-if-else block? Why is it required? Is this large conditional block a possible candidate for future change?

4. Learn from sprint#2 and use the common learning.

Well, this is pretty much it. The idea is, we feel its not practical to go with an overnight policy for implementing peer code reviews. But, its very much possible that we do it in small increments and at each sprint’s retrospective we bring this point. So, we are all informed that we need to do reviews, which, eventually should sustain as a best practice!

If you think you have some ideas regarding this, please share it with me/my readers.

Comments

Gregg Sporar
Agreed, an incremental approach can work well.

FYI, we're offering a special for one week only on our lightweight code review tool: Code Reviewer. $5 for 5 licenses - 5 days only (July 13-17). Full details here: http://smartbear.com/code-review-5-for-5.php

CruiseControl.Net (CCNet) Configuration Example for NCover

CruiseControl.Net is a great continuous integration tool for .Net projects. It not only continuously builds your software but provides some really helpful reports to monitor your project’s progress.

In agile world, we all speak of self-testing code or test driven development (TDD). If we really want to ensure our code has enough test coverage, we need to use some tool to ease our lives and NCover is a good one for this purpose. To learn more about NCover, please visit this.

When integrating to CCNet, you can use a similar configuration in ccnet.config as shown below to show NCover reports for your project-

\par ?? <\cf3 msbuild\cf1 >\par ?? <\cf3 executable\cf1 >\cf0 C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe\cf1 \par ?? <\cf3 projectFile\cf1 >\cf0 CISample.sln\cf1 \par ?? <\cf3 buildArgs\cf1 >\cf0 /p:Configuration=Debug\cf1 \par ?? <\cf3 targets\cf1 >\cf0 Rebuild\cf1 \par ?? <\cf3 timeout\cf1 >\cf0 300\cf1 \par ?? <\cf3 logger\cf1 >\cf0 C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll\cf1 \par ?? \par ??\par ?? \par ?? <\cf3 nunit\cf1 >\par ?? <\cf3 path\cf1 >\cf0 C:\Program Files\NUnit 2.4.1\bin\nunit-console.exe\cf1 \par ?? <\cf3 assemblies\cf1 >\par ?? <\cf3 assembly\cf1 >\cf0 CISample\bin\Debug\CISample.dll\cf1 \par ?? \par ?? \par ??\par ?? \par ?? <\cf3 exec\cf1 >\par ?? <\cf3 executable\cf1 >\cf0 ncover.console.exe\cf1 \par ?? <\cf3 baseDirectory\cf1 >\cf0 CISample\bin\Debug\\cf1 \par ?? <\cf3 buildArgs\cf1 >\cf0 nunit-console CISample.dll //xml coverage.xml //ea NUnit.Framework.TestFixtureAttribute\cf1 \par ?? \par ??\par ?? \par ?? <\cf3 exec\cf1 >\par ?? <\cf3 executable\cf1 >\cf0 NCoverExplorer.Console.exe\cf1 \par ?? <\cf3 baseDirectory\cf1 >\cf0 CISample\bin\Debug\\cf1 \par ?? <\cf3 buildArgs\cf1 >\cf0 coverage.xml /xml /r:ModuleMethodFunctionSummary\cf1 \par ?? \par ??\par ?? } –>

10 <tasks>

11 <!– Task for MSBuild –>

12 <msbuild>

13 <executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>

14 <projectFile>CISample.sln</projectFile>

15 <buildArgs>/p:Configuration=Debug</buildArgs>

16 <targets>Rebuild</targets>

17 <timeout>300</timeout>

18 <logger>C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>

19 </msbuild>

20

21 <!– Task for NUnit –>

22 <nunit>

23 <path>C:\Program Files\NUnit 2.4.1\bin\nunit-console.exe</path>

24 <assemblies>

25 <assembly>CISample\bin\Debug\CISample.dll</assembly>

26 </assemblies>

27 </nunit>

28

29 <!– Task for NCover –>

30 <exec>

31 <executable>ncover.console.exe</executable>

32 <baseDirectory>CISample\bin\Debug\</baseDirectory>

33 <buildArgs>nunit-console CISample.dll //xml coverage.xml //ea NUnit.Framework.TestFixtureAttribute</buildArgs>

34 </exec>

35

36 <!– Task for NCoverExplorer –>

37 <exec>

38 <executable>NCoverExplorer.Console.exe</executable>

39 <baseDirectory>CISample\bin\Debug\</baseDirectory>

40 <buildArgs>coverage.xml /xml /r:ModuleMethodFunctionSummary</buildArgs>

41 </exec>

42

43 </tasks>

You see that there are two NCover related <exec> nodes. The first one generates the coverage.xml. Then using this first one you can create actual report to present specifying the desired level of details of the report.

Comments

Abhishek Tyagi
NUnit task in this example does not work.

The warning : warning MSB6003: The specified task executable could not be run. The directory name is invalid

the path is correct. can u help out in this issue thank you

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!

Comments

Jeff Sinclair
The important thing to remember is that if you compile using c# 3.0 features, this does not mean that the compiled output won’t run on 2.0 Most of the c# 3 features are compile time only.
Be clear on if you want to be restricted at compile time, or if your goal is to have the output work on 2.0 at runtime.