DCSIMG

 Subscribe in a reader

December 2007 - Posts - Guy kolbis

December 2007 - Posts

In order to compile Delphi projects during team build we need to use one of the followings:
  1. dcc32.exe
  2. delphi32.exe
The dcc32.exe is the compiler for Delphi and the delphi32.exe is the IDE executable. We can use both in order to compile dpr files. The dpr files are the Delphi project files much like the csproj files in.NET.So, in order to compile it I used the delphi32.exe and created a custom task to execute it. I could have used the built-in Exec task, but I wanted to add some custom operations to the compilation phase. An important issue here is to understand what is the result for the compilation. In order to get this information I had to use a custom task that will wait for the compilation to complete and write the compilation output into a file. Then I parsed it for any errors or warnings and finally I returned the result accordingly.Here is the code for the custom task:  
public class DelpheCompilerTask : Task
{

    bool _del;
    string _dpr;

    string _exec;
    string _compilationOutputDir;

    int _timeout;

    #region Properties
    [Required]

    public bool DeleteResultFileOnCompletion
    {

        get { return _del; }
        set { _del = value; }
    }

    [Required]

    public string DPR
    {

        get { return _dpr; }
        set { _dpr = value; }
    }

    [Required]

    public string CompilationResultFileName
    {

        get { return _compilationOutputDir; }
        set { _compilationOutputDir = value; }
    }

    [Required]

    public string Delphi32ExePath
    {

        get { return _exec; }
        set { _exec = value; }
    }

    [Required]

    public int Timeout
    {

        get { return _timeout; }
        set { _timeout = value; }

    }

    #endregion

    public DelpheCompilerTask()
        : base()
    {

    }

    public override bool Execute()
    {

        bool result = true;
        Process p = null;

        try
        {

            LogMessages(string.Format("Delphe compilation on project {0} started.", DPR));
            ProcessStartInfo psi = new ProcessStartInfo(Delphi32ExePath);

            psi.Arguments = string.Format("{0} {1}/ns /b /o\"{2}\"", Delphi32ExePath, DPR, CompilationResultFileName); p = Process.Start(psi);
            p.WaitForExit(Timeout);

            if (File.Exists(CompilationResultFileName))
            {

                string fileTxt = File.ReadAllText(CompilationResultFileName);

                if (fileTxt.Contains("Error"))
                {

                    LogMessages(fileTxt, BuildTaskLogLevel.Error); result = false;
                }

                else
                {

                    LogMessages(fileTxt, BuildTaskLogLevel.Warning);
                }

                if (DeleteResultFileOnCompletion) File.Delete(CompilationResultFileName);
            }

            LogMessages(string.Format("Delphe compilation on project {0} completed.", DPR));
        }

        catch (Exception ex)
        {

            LogMessages(ex.ToString(), BuildTaskLogLevel.Error);

            result = false;
        }

        finally
        {

            if (p != null)
            {

                p.Close();

                p.Kill();

            }

        }

        return result;
    }

    private void LogMessages(string msg)
    {

        LogMessages(msg, BuildTaskLogLevel.Message);
    }

    private void LogMessages(string msg, BuildTaskLogLevel level)
    {

        string message = "********Compile delphe project Task Message*******";
        message += msg;

        switch (level)
        {

            case BuildTaskLogLevel.Message:
                base.Log.LogMessage(message, null);

                break;
            case BuildTaskLogLevel.Warning:

                base.Log.LogWarning(message, null);
                break;

            case BuildTaskLogLevel.Error:
                base.Log.LogError(message, null);

                break;
            default:

                break;
        }

    }

}
 Here is an example of how to call the custom task from the TFSBuild.proj: 

<UsingTask

TaskName="MyTasks.Tasks.DelphiCompilerTask"

AssemblyFile="C:\B\CustomTasks\MyTasks.Tasks.dll" />

 

<DelpheCompilerTask

DeleteResultFileOnCompletion="true"

DPR="$(SolutionRoot)\Application Services\Common\About\About.dpr"

CompilationResultFileName="C:\delphi_compilation.txt"

Delphi32ExePath="C:\Program Files\Borland\Delphi5\Bin\delphi32.exe"

Timeout="60000"/>

  I hope this helps! 

In order to compile .NET solutions all we need to do is indicate the path to the solution.

It should look something like this:

<SolutionToBuild Include="$(SolutionRoot)\Application Services\Controls\Controls.sln" />

 

However, when it comes to native C++ solutions, the above line will not work. What should we do?We need to compile the solution from the command line. There are three tools that can help us compile the solution:
  1. devenv.exe
  2. cl.exe
  3. vcbuild.exe

The devenv.exe is a process that belongs to the Microsoft Visual Studio. It is possible to use it to compile the solution when given a specific configuration, but when invoking the compilation through it we are opening the entire environment.

 

The second option is the cl.exe which it is the Microsoft® C/C++ Compiler Driver. When we compile C/C++ using any of the options mentioned, we actually invoke it. It compiles file after file and so in order to compile a large project or even a solution, we must provide it with a huge list of files.

 

Finally, there is the vcbuild.exe. You can use it to build Visual C++ projects and Visual Studio solutions from the command line. Invoking this utility is equivalent to running the Build Project or Build Solution command from the Visual Studio IDE.

 

So, in my opinion the best method is to use the vcbuild.exe.

 Luckily for us, there is a VCBuild Task that can be invoked from the build process. This task wraps vcbuild.exe, which builds Visual C++ projects and solutions that contain Visual C++ projects.

For example:

 

<VCBuild Projects="@(vcprojects)" Configuration="$(configuration)" Rebuild="true"/>

 Enjoy! 
This is something I did not expected.Apparently, in order to run unit tests written in Visual Studio Team For Developers during build it is required to install the Tester edition. The Tester Edition comes with a Test Manager window that allows you to create test lists. Team Build will use those test lists during the build process.

I think that Microsoft got it wrong here and they should allow the Developer Edition to create a test list using the Test Manager window.

One of my customers had a really strange problem related to Team System Source Control.

Several developers could not see some projects and folders in the source control explorer, while others could.

In order to solve it I first tried adding all the problematic developers into the Project Administrators role, but still the problem existed and they cannot see the folders and projects.

It turns out that the developers that could not see the items belong to three roles, Project Administrators, Developers and the Build Services.

In the Project Administrators, Developers roles they had the permissions to see all folders and projects, however in the Build Services role they had no permissions to those folders and projects.

Team System Source Control takes the minimum permissions out of all the roles that a user belongs to. For example, if you have a permission to see a folder in your Project Administrator role but you cannot see it in your Developer role, the result will be the minimum permission of the two, thus you will have no permission.

How can you tell which method consumes most of your CPU?

I had an application that consumed a lot of CPU. I have noticed it through the performance monitor. The performance monitor does not give you an indication on what is the most consuming method, rather it give you a general idea on how you critical resources behave during the application run.

However you can use the Visual Studio Profiler or other tools, but believe me, this will take more than one minute. Actually it can take you a few hours.

Here is a trick my friend, Eran Carmel, thought me.

Execute the application in Debug mode, once you see that the CPU usage is high (through the perfmon), pause the debugger and write down the method you are currently executing. Now let the debugger finish the execution and terminate it.

Repeat this process three times, if at all the three times you reach the same method, you have found yourself the method that is consuming your CPU.

Real World Example

I had to create an object that represents a house. The house got windows, doors, kitchen and etc. Each house object can vary and use different type of interior. Beside that there are several house types; there is a Vila, Duplex and etc.

My problem is how to create that object?

Builder

As mentioned before, I had to "create" a house, thus the Builder design pattern falls into the Creational design pattern category. Like the Factory design pattern, it abstracts the instantiation process. The critical distinction between the Builder and Factory patterns is that Builder is used to separate the representation of data and the construction logic of complex objects.

Here is a Class Diagram that describes it:

image

The code will look as follows:

The first class is the abstract builder that represents the creation for the complex object, in my case this is the House. This class contains the steps required for building a house, however it does not contain the implementation on how to build the house. The steps are those abstract methods that the class defines.

public abstract class AbstractHouseBuilder
{
    public object House { get; set; }

    public AbstractHouseBuilder()
    {

    }

    public abstract void BuildWindows();
    public abstract void BuildRoof();
    public abstract void BuildFloor();
    //more abstraction methods goes here

    public virtual object GetHouse()
    {
        return House;
    }
}

Deriving from the AbstractHouseBuilder is the concrete implementation of the steps. The following classes represenets different implementation for building windows, doors, roofs and etc.

public class DuplexBuilder : AbstractHouseBuilder
{
    public override void BuildWindows()
    {
        //implement windows for duplex...
    }

    public override void BuildRoof()
    {
        //implement roof for duplex...
    }

    public override void BuildFloor()
    {
        //implement foor for duplex...
    }
}
public class VilaBuilder : AbstractHouseBuilder
{
    public override void BuildWindows()
    {
        //implement windows for vila...
    }

    public override void BuildRoof()
    {
        //implement roof for vila...
    }

    public override void BuildFloor()
    {
        //implement foor for vila...
    }
}

Finally, there is the director which is in charge for constructing the house.

public class HouseDirector
{
    public void ConstractHouse(AbstractHouseBuilder builder)
    {
        if (builder == null)
            throw new ArgumentNullException();

        builder.BuildFloor();
        builder.BuildRoof();
        builder.BuildWindows();
    }
}

You can download the code here.

Summary

We use the Builder design pattern to design an object that can serve as an object factory, but separate the creation of the object from the representation of the object.

  • The Builder design pattern is used when the creation of complex objects needs to be independent of its representation.
  • The creation process must allow different representations or the object that is constructed

Whenever I consider using it I ask myself the following questions:

  • Do my classes share common elements?
  • Do I want or need to build objects in a step wise manner?
  • Will I need to build different complex classes comprised of common elements?

    Finaly they are here, all the sessions from Microsoft Developers Academy 2. For those who missed it and for those who want to see it again...

    Enjoy!

    For those of you who tried the 2005 WebTest recorder know that there were several issues about it that made working with it hard, for example Dynamic Parameters Discovery and AJAX based Recording. If you wanted to record AJAX based application you had to use a supporting tool such as Fiddler, which is a debugging proxy that integrates with VS WebTest. There were several issues with it such as HTTPS support and Extraction Rules support that made it a bit difficult to use.

    In VS 2008, Microsoft fixed those issues and much more. Now there is a Summary page at the end of a load test run, Dynamic parameters detection, Redirection handling, Request filtering and etc.

    Ed Glass wrote a post describing the new features for the Team System Web and Load Test.

    You can read more about it here.

    Would you find a screen cast helpful?

    Real World Example

    I will start with a real world example.

    Let's say that you are developing an application that consists of several roles, for example Administrator, Visitor and Power User.

    Each role has its own set of permissions that allows it to perform deferent operations in the application. For example the Administrator can navigate to the admin page while other roles cannot.

    You have to create each role with the specified set of operations that it allowed to perform.

    Template Method

    Here is the definition from the Go4:

    "Template Method defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses".

    So, if we get back to the real world example, we have all the roles as motioned before and a set of operations. Each role should create a set of operations specific to its permissions.

    In order to achieve that first we need those three roles and an abstract class named role that they all inherits from.

    Each Role must implement the GetOperation method and by doing so each one is responsible for instantiating deferent set of operations related to it.

    Here is a Class Diagram that describes it:

    image

    So, the code will look as follows:

    public abstract class Role
    {
        public string Name { get; set; }
    
        public Role(string name)
        {
            Name = name;
        }
    
        /// <summary>
        /// This is the template method.
        /// </summary>
        /// <returns></returns>
        public abstract List<Operation> GetOperations();
    }
    public class AdminRole : Role
    {
        public AdminRole()
            : base("Administrator")
        {
    
        }
    
        public override List<Operation> GetOperations()
        {
            List<Operation> operations = new List<Operation>();
    
            operations.Add(new Operation("GoToAdminPage"));
            operations.Add(new Operation("GoToMainPage"));
            operations.Add(new Operation("SeeUserInformation"));
            //and the list goes on...
    
            return operations;
        }
    }
    public class PowerUserRole : Role
    {
        public PowerUserRole()
            : base("PowerUser")
        {
    
        }
    
        public override List<Operation> GetOperations()
        {
            List<Operation> operations = new List<Operation>();
    
            operations.Add(new Operation("EditUserInfo"));
            operations.Add(new Operation("RemoveUsers"));
            operations.Add(new Operation("AddNewUsers"));
            //and the list goes on...
    
            return operations;
        }
    }
    public class VisitorRole : Role
    {
        public VisitorRole()
            : base("Visitor")
        {
    
        }
    
        public override List<Operation> GetOperations()
        {
            List<Operation> operations = new List<Operation>();
    
            operations.Add(new Operation("GoToVisitorPage"));
            operations.Add(new Operation("SeeAboutPage"));
            //and the list goes on...
    
            return operations;
        }
    }
    public class Operation
    {
        public string Name { get; set; }
    
        public Operation(string name)
        {
            Name = name;
        }
    }

    You can download the code from here.

    Summary

    Template Method is a very common design pattern.

    Whenever I consider using it I ask myself the following questions:

    1. Are there several objects that inherit from a base object?
    2. Do they have a common operation for creating something?
    3. It the objects they all create derive from a common object?

    If the answer to all those questions is yes, than my scenario is a good candidate for using Template Factory.

    This is the first post I intend on writing in regard to design patterns.

    In each post I will write about a specific pattern, I will give a sample real world code to follow it and the "Why - When" to use it.

    But first thing is first. Lets first understand what are those design patterns are.

    Here is a definition I got from the web:

    "Design patterns are recurring solutions to software design problems you find again and again in real-world application development"

    There is a saying "you do not want to invent the wheel all over again". If you have something that has been checked and proven to work, use it!

    The same thing goes here. Whenever you encounter a design issue, first check to see if there is a solution for it, if there is a solution than use it, else make a solution that can serve you in the future.

    Each design pattern is target to answer a specific design issue. Once you understand what each design pattern does, you can use it as a design implementation.

    The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns.

    The GoF Design patterns are divided into three categories:

    1. Creational.
    2. Structural.
    3. Behavioral.

    In the Creational category you will find all the design patterns that deal with creating instances for example Singleton, Builder, Abstract Factory, Factory Method and Prototype.

    In the Structural category you will find all the design patterns that combine a structure such as a tree structure or bridge. For example Adapter, Bridge, Composite, Decorator, Facade, Flywieght and Proxy.

    In the Behavioral category you will find the design patterns that will help you with behavioral design issue, such as Command, Memento, State, Observer, Iterator, Visitor, Template Method, Interpreter, Strategy, Mediator and Chain Of Responsibility.

    In the posts to follow, I will dive into the patterns.

    A rumor has it that next Sunday, the 16th of December 2007, Microsoft Israel will publish the videos from the DevAcademy2.

    I cannot wait to see and hear all the presentations I have missed.

    I am working on an automatic build for one of my customers.

    When I initiate the Get task that gets all the sources from the Team System Version Control, the operation failed with an error that the path exceeds 260 characters. This is apparently a common issue in Team Build.

    The limit for the 260 characters comes from windows. That means that this is not a Team build limit, rather a windows limit.

    Aaron Hallberg wrote a good post about it.