Archive for ◊ March, 2012 ◊

Saturday, March 31st, 2012
Cloud9 IDE is an online development environment for Javascript and Node.js applications as well as HTML, CSS, PHP, Java, Ruby and 23 other languages. Cloud9 IDE lets you build, debug, and run your Node.js applications within the browser. Set breakpoints, follow the call stack, and analyze your performance. In this post I’ll demonstrate how to build a simple Node.js server app using Cloud9 IDE.
Creating a new project:
Creating a project in Cloud 9 IDE requires an account which is available as a free subscription at http://c9.io/.
After successful registration you can create a new project by adding a new project form the dashboard.
After entering the project name you can select the type of project to create
·
Git project: will allow you to run git commands from the console and push your changes to Github
·
Mercurial: will allow you to run hg commands form the console and push your changes to Bitbucket.
·
FTP: will allow you to upload your files directly to an FTP server you have access to.
Select create after choosing a project type. Now, just click Start Editing to get started!
You can right click on the selected project and add a ‘New File’
Creating the node.js server
We’ll create a simple http server with controllers to handle the request and send the response to the
clients. Create a new loginController.js file and add the code given below.

exports.process = function handle(response) {

response.writeHead(200);
response.end(‘<html>’ +
‘<head>’ +
‘<meta http-equiv=”Content-Type”
content=”text/html; ‘
+
‘charset=UTF-8″ />’ +
‘</head>’ +
‘<body>’ +
‘<form action=”/login” method=”post”>’ +
‘Login name:<input type=text value=”"
name=”txtLogin” style=”width: 100px”></br>’
+
‘Password
:<input type=password value=”" name=”txtPassword”
style=”width: 100px”></br>’
+
‘<input type=”submit” value=”Login”
/> &nbsp; &nbsp; <input type=”submit”
value=”Cancel” />’
+
‘</form>’ +
‘</body>’ +
‘</html>’);
The process property is assigned to an object called ’exports’. Such an ‘exports’ object is available in every module, and it is returned whenever the required function is used to include the module. We can now use this function as given below
var loginController = require(‘./handlers/loginController’);
loginController.process(response);
Similarly you can create the other controllers and then the http server like
var http = require(‘http’);
var homeController = require(‘./handlers/homeController’);
var loginController = require(‘./handlers/loginController’);
var errorController = require(‘./handlers/errorController’);
var port = process.env.PORT;
var requestListener = function(request, response)
{
switch(request.url)
{
case ‘/’:
homeController.process(response);
break;
case ‘/login’:
loginController.process(response);
break;
default:
errorController.process(response);
break;
}
}
var server = http.createServer(requestListener);
server.listen(port);
In the first line, we included the http core module and assign it to a variable called http. Later we use this variable called server by calling http.createServer(). You can also specify which port the server listens to. When
Node.js projects run within Cloud 9 IDE, you can retrieve the port information with process.env.PORT. You can run the project by clicking the Debug button.
Category: General | Tags: ,  | One Comment
Saturday, March 17th, 2012
Unity Auto Registration extends Unity IoC container and provides fluent syntax to configure rules for automatic type registration. You can add Unity Auto Registration package using NuGet package manager.
Using few code lines you can scan specified assemblies and register all types that satisfy the rules. Rules for determining whether to include/exclude type/assembly are predicates so you can use lambda syntax to
specify them or direct method name. For e.g. you can register interfaces, using AsFirstInterfaceOfType() which
will throw an exception if more than one interface is found on a type.  You can also use decorated attributes type to
register types to the container.
For e.g. All my repositories that implement the type
public interface IRepository
{
IEnumerable All();
T One(Funcbool> condition);
IEnumerable All(Funcbool> condition);
void Add(T entity);
void Save(T entity);
void Remove(T entity);
HashSet Context { get; }
}
public class CustomerRepository : BaseRepository<Customer>
{
//Implementation
methods
}
Can be registered as
_container
=
new UnityContainer();
_container.ConfigureAutoRegistration()
.LoadAssembliesFrom(RegistrationAssemblies.AssemblyNames)
.Include(r => r.ImplementsOpenGeneric(typeof(IRepository<>)),
Then.Register().AsFirstInterfaceOfType())
.ApplyAutoRegistration();
Where RegistrationAssemblies.AssemblyNames is a string array of the assemblies to look for types to register.
You can also decorate the types with a common attribute to register types. For e.g. the business logic components in this sample is decorated with the attribute [Logic] as given below
[Logic]
public class CustomerLogic : ICustomerLogic
{
public IEnumerable<Customer> GetAllByName(string name)
{
var repository = IoC.Container.Resolve<IRepository<Customer>>();
return repository.All(c => c.Name.StartsWith(name));
}
}
These types can be registered using the DecoratedWith method as given below.
_container
=
new UnityContainer();
_container.ConfigureAutoRegistration()
.LoadAssembliesFrom(RegistrationAssemblies.AssemblyNames)
.Include(r => r.ImplementsOpenGeneric(typeof(IRepository<>)), Then.Register().AsFirstInterfaceOfType())
.Include(If.DecoratedWith<Logic>, Then.Register().AsFirstInterfaceOfType())
.ApplyAutoRegistration();
Author:
Thursday, March 15th, 2012

Unit testing code that is spawned as a separate thread can be challenging.

We need to make sure our Asserts can run after the parallel thread completes, and not before.

Moreover, we need to make sure our unit test doesn’t complete before the parallel thread, leaving it orphan and causing errors for the test agent.

Consider the following code:

        private void LoadCustomerData()
        {
            this.IsLoading = true;

            // the following code will run a separate thread (use a BackgroundWorker if you like)
            Task.Factory.StartNew(() =>
                                      {
                                          // do some stuff here to load the data
                                          this.Customers = dao.GetCustomers();

                                          // finally indicate that loading is completed
                                          this.IsLoading = false;
                                      });
        }

Now consider a unit for this:

        [TestMethod]
        public void LoadData_should_bla_bla()
        {
            // Arrange
            var testObject = new SomeClass();

            // Act
            testObject.LoadData();

            // Assert
            Assert.IsNotNull(testObject.Customers);
        }

The test looks pretty straight forward. However, when you run this, it’ll not pass. You’ll most probably get the “agent terminated before execution completed” error or your assert will fail.

The reason is this: this.Customers is set by a separate thread, and as soon as you call LoadCustomerData(), it spawns that thread and returns immediately. Giving no time for the actual load to happen before you can do your Assert. In other words, your assert runs before the thread that loads the data.

OK, how to we solve this? Well, my first attempt would be to wait before I assert:

        [TestMethod]
        public void LoadData_should_bla_bla()
        {
            // Arrange
            var testObject = new SomeClass();

            // Act
            testObject.LoadData();

            while (testObject.IsLoading)
                ; // do nothing till loading completes

            // Assert
            Assert.IsNotNull(testObject.Customers);
        }

Again, at first look this looks pretty straight forwards. Your test would also work pass now. However, you’ll hit trouble when the test fails. What if something goes wrong when loading and IsLoading is never set to false. Well, your test will run indefinitely!

Ideally, your test should fail if for some reason IsLoading is not set to false. So, we could try a “wait with timeout” approach. Instead of waiting indefinitely, we can wait for some time (say 2 seconds) and throw a timeout exception after that (which will make the test fail). May be something like this:

        [TestMethod]
        public void LoadData_should_bla_bla()
        {
            // Arrange
            var testObject = new SomeClass();

            // Act
            testObject.LoadData();

            // Wait until IsLoading becomes false or for 2 seconds, whichever occurs first
            TestUtility.WaitWithTimeout(() => testObject.IsLoading == false, 2000);

            // Assert
            Assert.IsNotNull(testObject.Customers);
        }

There you go. This would work!

And here’s the code for this WaitWithTimeout function:

    class TestUtility
    {
        internal static void WaitUntil(Func<bool> whatToWaitFor, int howManyMilliseconds)
        {
            DateTime start = DateTime.Now;

            while (!whatToWaitFor())
            {
                Thread.Sleep(100); // just breathe a little instead of a continuous loop!

                if (DateTime.Now.Subtract(start).TotalMilliseconds > howManyMilliseconds)
                {
                    throw new TimeoutException("Wait timed out");
                }
            }
        }

Cheers!

-Anand

        private void LoadInitialData()
        {
            Loading = true;
            Task.Factory.StartNew(() =>
                                      {
                                          if (BranchTeams == null) // we only need to load first time
                                          {
                                              LoadBranchTeamData();
                                              if (App.StartupSurveyId > 0)
                                              {
                                                  SurveyFilter = App.StartupSurveyId;
                                              }

                                          }

                                          ApplyFilters();

                                          Loading = false;
                                      });
        }
        [TestMethod]
        public void LoadData_should_bla_bla()
        {
            // Arrange
            var testObject = new SomeClass();

            // Act
            testObject.LoadData();

            // Assert
            Assert.IsNotNull(testObject.Customers);
        }
Thursday, March 15th, 2012
Visual studio 2011 introduces the code clone analysis feature that allows developers for identification of similar code sections. The new feature enables developers to identify duplicate code in the solution which makes it difficult for making changes in the code, as the same change must be made in multiple places in the code base. Code clone analysis, by identifying these similar sections of code, makes it easier to refactor them.
You can launch the code clone analysis from the Analyze menu item, which shows the two exact matches for a code clone.
Code clone window will display the from – to line number along with the files name. You can click on that line to navigate to the code block or just mouse hover to see the cloned code.
Category: .Net  | Leave a Comment
Author:
Friday, March 02nd, 2012

Often while writing an application or adding a module to an existing application we wonder if we should go with multithreading. Multithreading can be a powerful tool, but only if used the right way. Lets examine.

There are two main reasons when one should consider multithreading,

  1. We have a GUI application and want to improve the user experience.
  2. We have a batch job processing application and want to improve the performance.

Lets take the first situation. I have developed a desktop application which splits large files into smaller chunks. I choose a movie file and want to split this into smaller chunks. Depending on the size of the file this operation may take anywhere from few seconds to few minutes. Lets say in the middle of the operation, I realize I chose the wrong file. If my application is single threaded I cant do anything to stop this as the main thread is working away splitting the file. So, if my application uses one thread, I can do only one thing at a time.

Now it makes sense to have this application multithreaded. You can start the file splitting on one thread while you have the main thread listening to user inputs. The thread doing the splitting work can be interrupted in case the user cancels the operation or needs to do something else.

So, writing GUI applications with multithreading makes a lot of sense and almost all modern day applications are multithreaded.

Now lets take the second scenario. We have a batch processing job to do. We have a bunch of xml files which we have to parse and persist in a database. If I do this operation in my main thread, I would have to parse each xml file and put the data in database sequentially. If I want to speed this process up, the logical thing to do would be to process these files and update the database in parallel. But its not that simple, there is a catch.

One CPU can process only one thread at a given time. There is also an overhead involved in thread scheduling as time slicing will be done to give CPU time to different threads. So if 50 threads are started to process 100 files, the job will definitely slowdown on a single CPU machine. At the same time doing the process in one thread does not make sense as the process involves i/o and db operations which are time consuming. A thread waiting on i/o is automatically removed and another thread is given a chance by most operating systems today. So the ideal number here would be around 5 threads. In case the environment has more than one CPU, the number of threads can be increased. This can even be decided at run time. The number of CPUs available for the VM can be got from the Java API Runtime.getRuntime().availableProcessors(). This can be multiplied with a suitable factor to get the number of threads required to process the job.

Multithreading for batch jobs should be considered based on the platform on which the process runs. Even better would be to have this configurable at run time.

It is good to consider the above while developing multithreaded GUI or batch jobs. In case we didn’t get the required performance, we now know where we were going wrong.