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 to Compress Files in .Net

There is many options to compress files, and .net framework provide you with 2 easy ways to do it. Basically there are 2 class under System.IO.Compression namespace. More specifically those classes are:
            1. GZipStream
            2. DeflateStream

Both of these classes has certain usage. I will start first by explaining how to use each one then jump into a comparison between them on later posts.

   Yasser Jaber wrote an article about how to compress files using GZipStream class at integrant’s blog. Read this article here

Advance Operation using LINQ to object

In certain cases you might find yourself in need to do sum for a field that is a member of object in a list or collection. Doing summation for a certain field is somehow an easy job. What if you want to do Average or more complicated equation. Definitely you will write a long procedure to do the needed job.
Well, if you decided to use LINQ to Object to do the job for you, then you might do the job by writing couple of lines of code. Yes, it will be as simple as that.
Yasser Jaber wrote a short article about this in Integrant’s blog

What is LINQ to Object

LINQ is a new language introduced in .net framework 3.5. it is so much useful for developer as it is freeing developer from writing large number of code lines. If you did not try it yet,  I strongly recommend to read the following article that I posted to my company blog site. this post explain basic things of LINQ to object language..

Read more

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.