Loops Performance differences in .Net

I never thought there will be a big different when you use different approaches to iterate through a collection of objects. I knew there are some differences between FOREACH/WHILE/FOR loops, but I never thought the different will be as much as an article I read recently in an article published on codekicks site.

The article was demonstrate how using the foreach/while/For loops will affect the performance of your application. The first time I read the article posted there I got convened and posted a recommendation to read it to my personal site. a friend of mine read the article and we had a discussion about it. He had a very true observation about the test applied to come into the conclusion. The main issue raised by Ahmad (my friend who raised the issue) was about the internal operations done by each loop. For example, in FOREACH loop, it is doing an internal object retrieval and assignment to object reference which none of other loops doing it. Even if take this note into consideration, there will be some sort of performance differences between FOREACH/While/FOR loops.

So I still recommending reading the article but please keep into consideration that the test applied is not perfect.

How Can I Enhance the Performance of .Net Application?

The performance of any system is considered as a key part of the requirements that client usually ask for implicitly. The poor perform application is most likely going to be failed because of that even if it is doing lot of very cool functionalities.
Recently I read an interesting article about this topic published on CodeGuru. They highlighted couple of key actions that is easy to be implemented and they are almost effortless but at the end those actions will improve the overall performance of you application by better utilization of server CPUs.
They depending on the fact that the CPUs we have these days is much sophisticated that previous days and we need to take benefits of that. I strongly recommend reading this article

How to create OOP representations of XML

If you have an XML file and you are seeking for the best way to deal with it inside your code. You do not want to use XPath Queries intensively in your code and want to have the best way to deal with that XML… I faced such a case where I need to build a special configuration file for an FTP windows service. The way I wanted to build this XML file was in a hierarchy way something looks like the following XML:

<FtpConnection Code="CodeName" Direction="Upload">

<Ftp>

<RemoteHost>IP or the DNS name for the remote FTP server</RemoteHost>

<Username>FTP USerName</Username>

<Password>password</Password>

<ConnectionTimeOut>50</ConnectionTimeOut>

</Ftp>

<Security>

<IsSecured>true</IsSecured>

<ScretPhase>Sec Phrase Goes here</ScretPhase>

</Security>

</FtpConnection>

 

This FTP service suppose to work with more than on FTPConnection. Thus the above configuration snap might occur more than one time. Which make it is harder to deal with .

The best way to deal with this configuration inside code is to create a object oriented representation of it and load this XML into it. then let your code deal with the OOP classes instead of directly with XML.

Well, there is a very easy way to build a OOP presentation of this XML. There is a tool that is shipped with .Net framework & visual studio called XSD. You can use this tool to generate the OOP representation by first create XSD schema for your XML then convert that schema to OOP presentations. Below is how to do that step by step.

  1. I created a file on my desktop and I called it "FTPConfig.xml", I paste the following XML into it.

<Root>

<FtpConnection Code="CodeName" Direction="Upload">

<Ftp>

<RemoteHost>IP or the DNS name for the remote FTP server</RemoteHost>

<Username>FTP USerName</Username>

<Password>password</Password>

<ConnectionTimeOut>50</ConnectionTimeOut>

</Ftp>

<Security>

<IsSecured>true</IsSecured>

<ScretPhase>Sec Phrase Goes here</ScretPhase>

</Security>

</FtpConnection>

<FtpConnection Code="Code2Name" Direction="Upload">

<Ftp>

<RemoteHost>IP or the DNS name for the remote FTP server</RemoteHost>

<Username>FTP USerName</Username>

<Password>password</Password>

<ConnectionTimeOut>50</ConnectionTimeOut>

</Ftp>

<Security>

<IsSecured>true</IsSecured>

<ScretPhase>Sec Phrase Goes here</ScretPhase>

</Security>

</FtpConnection>

</Root>

· Note that I duplicated the FTPConnection tag twice, I did that for a purpose. I did that to tell XSD tool to expect this tag to occur more than once. Thus when XSD tool build the Schema representation of it, it will make the MAX occurrence of this tag as infinite

     2. From Start menu, open "Visual Studio 2008 Command Prompt"… it is Command prompt but has special configurations to open some Command Prompt tools shipped with VS 2008

      3. We need to set the current folder on CMD to be the desktop. To do so, write the following comand

Cd c:\users\[windowsUserName]\desktop

· Where [WindowsUserName] is the login name that you are using to login into your PC

       4. Now we need to create the XSD schema file for this XML. To do that, write the following command into your CMD

xsd FTPConfig.xml

· The output from this command is an XSD file and it will placed on your Desktop; the name of this XSD file suppose to be FTPConfig.xsd; My advice to you is to take couple of minutes to review this Schema file and make sure it is meeting your expectation.

       5. Now we need to Create the OOP presentation of this XSD; to do so, write the following command

xsd FTPConfig.xsd /classes /language:CS

a. The meaning of parameter /Classes : will make the output of this command to be Classes not DataSet.

b. While the Meaning of parameter /language is the programming language in which the code will be generated; CS means C# language

    The output form this command suppose a C# code placed on your desktop.

  •  My recommendation to you is to keep all the generated classes into a single class and do not split each class into a separated file. I am saying this because you might decide to change the configuration a little bit and you need to regenerate those classes again. So if you split those classes into different files, then you will get into a loop of re-splitting the classes again and again.

I hope you will find this topic helpful. Please feel free to send any comments/questions.

What is Unit testing and what benefits I will have if I apply it on my project

What is Unit Test:

In computer programming, unit testing is a software design and development method where the programmer verifies that individual units of source code are working properly. A unit is the smallest testable part of an application.

In OOP, the smallest unit is a method, which may belong to a base/super class, abstract class or derived/child class.

Unit testing is typically done by software developers to ensure that the code other developers have written meets software requirements and behaves as the developer intended.

Benefits of Applying Unit Test:

  • Using developer time for manual ad hoc testing is not a cost effective way of ensuring software quality. (Code coverage, breaking code by others, did I test all functionalities)
  • Human tester can and will make mistakes.. Even if Company have QA, discovering issues at QA side is more expensive than @ DEV side.
  • unit tests find problems early in the development cycle.
  • an automated unit test suite watches over your code in two dimensions: time and space
  • developers will be less afraid to change existing code
  • the development process becomes more flexible (Sending hotfixes more quickly)
  • Improves your project’s truck factor:

Truck factor is the minimum number of developers that if hit by a truck the project would grind to a halt. If you have one key developer who works on a subsystem that no-one else knows, then your truck factor is effectively “1”. Obviously, having truck factor of “1” is a risk on the project.

A comprehensive unit test suite improves truck factor because it makes it easier for a developer to take over a piece of code she is not intimately familiar with. A developer can start working on code written by others because the unit tests will guide the developer by pointing it out if she makes an error. Losing a key developer for any reason just before a release is less of a catastrophe if you have the safety net of unit tests.

  1. reduces the need for manual testing

Flavors of Unit testing:

  • Point unit tests exercise a small piece of functionality, e.g., just one method or methods of a class.
  • End-to-End tests exercise one feature across many, sometimes all, layers of an application; An ideal end-to-end test works like an end user story

Test Driven Programming model: Developer start developing test methods and basic functions that make test methods success, then enhance code at methods to make sure it will cover all expected/unexpected cases.

As a rule, before a developer checks in any code into the main source control repository, she should get the latest versions of the unit tests from the version control on her development machine and run all the tests locally. Only after all unit tests pass should the developer check in new code. This ensures that the source code in the version control system remains healthy at all times and can be used to rebuild the system at any time.

In real life, developers may accidentally check in code that does not work. The daily build should be your main line of defense against these bugs.

Real Word Facts:

Trusting unit tests blindly as in: "if unit tests pass, code is ready for production" is a recipe for shipping bugs. Even if we have a comprehensive unit test suite that is run frequently, bugs can still sneak in and some amount of manual testing by humans is needed.

What if Bug appear on Production:

We need to do "post mortem" analysis.. One of the following things turned out:

  1. We have 2 bugs: one inside actual Code and the other inside Unit test code.
  2. There is no unit test code that testing this functionality.
  3. Production environment is different from Test environment.

              Finally, If you have plenty of time at your project to apply Unit testing on it, the I would strongly recommend applying it.

How to Solve “Error Creating Control” Error Message (ASP.Net Site)

If you face this error while trying to open a web application project

Error Creating Control – control_Name
‘/LM/W3SVC/1/Root/Project_Name’ is not a valid IIS application.

ErrorCreatingControlSnapshot

 

You can resolve this error by following the below steps , the root cause of this error is the incorrect mapping between web application project and the virtual directory in your IIS.
To Resolve this error , follow the following steps:

1-Right click – you web application project and select Properties -> Web
2- in the server section choose Use IIS Web Server -> then click Create Virtual.
3- Clean your project from any DDLs that was previously complied and compile your project again.

By doing the above steps this issue should got resolved.

Http Handler vs Http Module

What is ASP .Net  HTTP Handler:

      An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser

Reference: http://msdn.microsoft.com/en-us/library/bb398986.aspx

What is ASP.Net HTTP Module:

      An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

Reference: http://msdn.microsoft.com/en-us/library/bb398986.aspx

Note:The basic different between HTTP Handler and HTTP Module, is that HTTP Module is event based processor.

Example of How to implement HTTP Handler:

using System;
using System.Web;
using System.IO;
namespace MyNamespace
{
public class MyHttpHandler  : IHttpHandler
{
    public void ProcessRequest(System.Web.HttpContext context)
    {
           context.Response.Write("The page request is " + context.Request.RawUrl.ToString());
           StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
           try
           {
                sw.WriteLine("Page requested at " + DateTime.Now.ToString() +
                              context.Request.RawUrl); sw.Close();
           }
           finally {  sw.Close();    }
    }
    public bool IsReusable
     {
            get
            {
                    return true;
                }
        }
}

 

Before you will be able to do Call for this HTTP Handler, you need to do the followings:
      1.  Add the following tags into your Web.Config file

<system.web>
    <httpHandlers>
          <add verb="*" path="*.WhatEverExtension" type="MyNamespace.MyHttpHandler  , MyAssemblyName"/>
      </httpHandlers>
</system.web>

2.  You need to add the extension you added on step 1 to your IIS so that IIS will recognize the new extensions… on our example you need to add "WhatEverExtension" to IIS
Example of how to implement HTTP Module:

namespace MyNamespace
{
public class MyHttpModule : IHttpModule
{
public MyHttpModule()
{}
public void Init(HttpApplication objApplication)
{
objApplication.BeginRequest += new EventHandler(context_BeginRequest);
objApplication.EndRequest += new EventHandler(context_EndRequest);
}
public void Dispose()
{
}
public void context_EndRequest(object sender, EventArgs e)
{
try
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("End Request called at " + DateTime.Now.ToString());
}
finally {sw.Close(); }
}
public void context_BeginRequest(object sender, EventArgs e)
{
try
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Begin request called at " + DateTime.Now.ToString());
}
finally { sw.Close(); }
}
}
}

For HTTP Module you need also to register this HTTP Module on your Web.config file… to do so , add the following tags to your Web.config file :

<httpModules>
        <add name="clsMyModule" type="MyNamespace.MyHttpModule, MyAssemblyName"/>
</httpModules>

List of HTTP Module Supported Events by :

 

Event Name Description
AcquireRequestState This event is raised when ASP.NET runtime is ready to acquire the Session state of the current HTTP request.
AuthenticateRequest This event is raised when ASP.NET runtime is ready to authenticate the identity of the user.
AuthorizeRequest This event is raised when ASP.NET runtime is ready to authorize the user for the resources user is trying to access.
BeginRequest This event is raised when ASP.NET runtime receives a new HTTP request.
Disposed This event is raised when ASP.NET completes the processing of HTTP request.
EndRequest This event is raised just before sending the response content to the client.
Error This event is raised when an unhandled exception occurs during the processing of HTTP request.
PostRequestHandlerExecute This event is raised just after HTTP handler finishes execution.
PreRequestHandlerExecute This event is raised just before ASP.NET begins executing a handler for the HTTP request. After this event, ASP.NET will forward the request to the appropriate HTTP handler.
PreSendRequestContent This event is raised just before ASP.NET sends the response contents to the client. This event allows us to change the contents before it gets delivered to the client. We can use this event to add the contents, which are common in all pages, to the page output. For example, a common menu, header or footer.
PreSendRequestHeaders This event is raised just before ASP.NET sends the HTTP response headers to the client. This event allows us to change the headers before they get delivered to the client. We can use this event to add cookies and custom data into headers.
ReleaseRequestState This event is raised after ASP.NET finishes executing all request handlers.
ResolveRequestCache This event is raised to determine whether the request can be fulfilled by returning the contents from the Output Cache. This depends on how the Output Caching has been setup for your web application.
UpdateRequestCache This event is raised when ASP.NET has completed processing the current HTTP request and the output contents are ready to be added to the Output Cache. This depends on how the Output Caching has been setup for your Web application.

Search Issue when using Visual Studio 2003 on Windows Vista Operating system

A couple of days ago, I faced a small issue when I tried to search specific value inside VS 2003 solutions while I have MS Windows Vista OS installed on my PC…. Doing searching will cause VS 2003 to be hanged and stop responding.. I overcome this issue by Disable Visual Themes for VS 2003.. To do so please follow the following steps:

  1. Right click on VS 2003 shortcut

  2. On compatibility tab , make sure to check "Disable Visual Themes" check box

  3. Click on OK button..

Now , You can enjoy Searching your VS 2003 solution.

How to solve XML configuration problem when you use unit testing

One of the first challenges I faced when I decided to use Unit Testing projects to test my Methods/Classes, is how to use XML configuration files with unit testing projects…

Basically the issue appear because my project using XML file as configuration file. And when I compile my Unite testing project, the compiler will copy only DLLs related to project being tested with no other resources including the configuration file(s) … this will cause all of my unit test methods to be failed because there is no configuration file available for Unit Test Project.

The solution is pretty easy… all what you have to do is to add the following attribute to Test Method header. This attribute will tell compiler to copy the file into Bin folder and things will go smooth.

[TestMethod(),DeploymentItem("XmlConfigurationFileName.XML")]

public void TestMethodName()

{

         //Method body goes here….

}

Design Patterns

What is Design Pattern:

Design Pattern: Is a general reusable solution to a commonly occurring problem in software.

Design Patten is a description or template of how to solve the problem we usually face during software development life cycle. It is showing relationship between classes without specifying how the final application will looks like. It is usually show the overall pattern that followed by the entire application/system.

Benefits of using Design Patterns:

  • It is proven solution to solve issues related to Software Development, and it facilitates thedevelopment of higly cohesive modules with minimal coupling .
  • Making the overall system easier to understand and maintain.
  • Making the communication between designers more efficient. Software professionals immediately understand the design when referring to the name of the design pattern used to solve the issue during discussing  system design

Design Patterns Categories:

Creational Design Patterns:

Structural Design Patterns:

Behavioral Design Patterns:

Test Run deployment issue: The location of the file or directory is not trusted… Error Message

Today I faced small problem while I am building Unit testing project to test my class library. in my class library I was using a DLL file located on a shared folder on my company’s network.. when I tried to run the test project I got this error message:
Test Run deployment issue: The location of the file or directory is not trusted

the solution of this issue was about adding the network path to my trusted sites.. to do so I followed the following steps:

1) open "Microsoft .NET Framework 2.0 Configuration" from administrative Tools
2) Go to "Runtime security Policy" –> Machine –> Code Groups –> All Code
3) right click –> New .. then give a name and description for the new group –> click Next
4) in the new form choose "URL" and then type your Network path. you can type it in 2 ways:

a) Y:\* –> for the whole folder
b) y:\AssemblyName.dll –> for single DLL

5) Choose Next… and then choose "Full trust"
6) click Next and then finished
7) finally close you VS and reopen it again
8) have fun in using unit testing 🙂

Thanks Microsoft for such a nice integration between tools:)