Vorleak Chy’s Blog
Open your mind to the possibilities

Oct
19

NewBlogImage

As long as several months on this blog, I would like to post more articles relate to software development but it seems creeping to me. So I decided to have a new one called WowKher Tech that is a team blog which I’ve just moved some posts in here to there.

This blog will be no longer update anymore in the future. There we’ll be blogging about high-tech, software development in general, .Net and developing on the web and windows application in particular areas. I’m not sure, something off topic might creep in there also.

We’ve decided to do our blogging more consistently. We read some blogs all the time and love seeing how other people develop what they enjoy and proficiency. We guess we also enjoy just seeing what other people are doing in general as well as all humans do.

One other reason we’ve decided that we’ll do with our blogging is to try and break up topics into separate entries.

Finally, I hope you enjoy and continue reading our blog http://tech.wowkhmer.com/

Aug
17

My colleague have some problems using Selenium to test the website specifically issues with JavaScript and Ajax. Also we would like to include testing nicely and easily integrated into our build process with continuous integration.

So we did together a bit of searching and found the free .Net automation framework for web testing produced by Art Of Test Inc called WebAii. Just see from the demo it seems to do everything we want.

I would think this is more useful framework rather than the others for now even I’ve just started to use it and there are just a small sample codes of its features. I guess it can be a killer web testing application. I tried it with my colleague and how about you?

Here is an example for you to try it:

Configuration file App.config


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="WebAii.Settings" type="ArtOfTest.WebAii.Core.SettingsConfigSectionHandler,ArtOfTest.WebAii, Version=1.1.900.0, Culture=neutral, PublicKeyToken=4FD5F65BE123776C"/>
  </configSections>
  <WebAii.Settings
    annotateExecution="false"
    baseUrl="http://www.google.com/"
    clientReadyTimeout="50000"
    defaultBrowser="InternetExplorer"
    enableScriptLogging="false"
    enableUILessRequestViewing="false"
    executionDelay="0"
    executionTimeout="60000"
    localWebServer="None"
    logLocation="C:\WebAiiLog\"
    queryEventLogErrorsOnExit="false"
    simulatedMouseMoveSpeed="0.3"
    webAppPhysicalPath=""/>
</configuration>

Abstract class PageBase.cs


using ArtOfTest.WebAii.Core;
using NUnit.Framework;

namespace WebAiiUITest
{
    public abstract class PageBase
    {
        public readonly Manager manager = new Manager(true);
        protected Browser browser;
        protected Find find;

        [SetUp]
        public void SetUp()
        {
            manager.Start();
            manager.LaunchNewBrowser();

            browser = manager.ActiveBrowser;
            find = browser.Find;
            browser.NavigateTo("http://www.google.com/");
        }

        [TearDown]
        public void TearDown()
        {
            browser.Close();
        }
    }
}

Testing class KeywordSearch.cs


using ArtOfTest.WebAii.Controls.HtmlControls;
using NUnit.Framework;

namespace WebAiiUITest
{
    [TestFixture]
    public class KeywordSearch : PageBase
    {
        [Test]
        public void Should_keyword_search_found()
        {
            var searchText = "Vorleak Chy’s Blog";

            find.ById<HtmlInputText>("q").Value = searchText;
            find.ById<HtmlInputSubmit>("btnG").Click();

            Assert.IsNotNull(find.ById<HtmlAnchor>(searchText));
        }
    }
}

This example will run with Internet Explorer browser. You can run with Firefox just change defaultBrowser=”Firefox” in App.config you can either write one line of code but I would like keep it easily in configuration file. It still doesn’t work if it opens with a new tab, from my experience unless you need to have a setting in browser. Click Tools -> Options -> Tabs -> select “a new window” option.

Aug
15

The factory method pattern is a design pattern that allows for the creations of objects without specifying the type of object that is to be created in code. A factory class contain a method that allow determination of the created type at run-time. It is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

One example of the use of the factory method pattern is when creating a connection to a data source if the type of the data source will be selected by the end-user using a graphical interface. In this case, an abstract class name “DataSource” may be created that defines the base functionality of all data source. Many concreate subclass may be created, perhaps “SqlDataSource”, “XmlDataSource”, “CsvDataSource”, etc, each with specific functionality for a differenct type of data. At run-time, a further class, perhaps named “DataSourceFactory”, generates objects of the correct class based upon a parameter passed to the factory method.

Implementation

FactoryMethod

The UML class diagram above describes an implementation of the factory method design pattern. In this diagram there are four classes:

  • FactoryBase: This is an abstract base class for the concrete factory classes that will actually generate new objects. This class could be a simple interface containing the signature for the factory method. However, generally an abstract class will be used so that other standard functionality can included and inherited by subclass. In simple situations the factory method may be implemented in full here. rather than being declared as abstract.
  • ConcreateFactory: Inheriting from the FactoryBase class, the concreate factory classes inherit the actual factory method. This is overridden with the object generation code unless already implemented in full in the base class.
  • ProductBase: This abstract class is the base class for the types of object that the factory can create. It is also the return type for the factory method. Again, this can be a simple interface info general functionality is to be inherited by its subclasses.
  • ConcreateProduct: Multiple subclasses of the Product class are defined, each containing specific functionality. Object of these classes are generated by the factory method.

The basic code of the factory method design pattern implemented using C# is shown in the following:


public abstract class FactoryBase
{
    public abstract Product FactoryMethod(int type);
}

public class ConcreteFactory : FactoryBase
{
    public override Product FactoryMethod(int type)
    {
        switch (type)
        {
            case 1:
                return new ConcreteProduct1();

            case 2:
                return new ConcreteProduct2();

            default:
                throw new ArgumentException("Invalid type.", "type");
        }
    }
}

public abstract class ProductBase { }

public class ConcreteProduct1 : ProductBase { }

public class ConcreteProduct2 : ProductBase { }

Example in C#

Example 1

This is a simple example of the factory method design pattern in action, The factory method GetPhone() will generate Phone object


namespace FactoryMethod
{
    public interface IPhone
    {
        decimal Price { get; }
    }

    public class Nokia : IPhone
    {
        public decimal Price
        {
            get { return 200; }
        }
    }

    public class Motorola : IPhone
    {
        public decimal Price
        {
            get { return 100; }
        }
    }

    public class PhoneFactory
    {
        public IPhone GetPhone(string type)
        {
            switch (type)
            {
                case "Nokia":
                    return new Nokia();
                case "Motorola":
                    return new Motorola();
                default:
                    return null;
            }
        }
    }
}

You just call GetPhone() and pass type as a parameter in your client code you will get a new Phone object


using System;
using FactoryMethod;

namespace FactoryMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            PhoneFactory phoneFactory = new PhoneFactory();
            IPhone phone;

            phone = phoneFactory.GetPhone("Nokia");
            Console.WriteLine("The price for Nokia: {0}", phone.Price);

            phone = phoneFactory.GetPhone("Motorola");
            Console.WriteLine("The price for Motorola: {0}", phone.Price);

            Console.Read();
        }
    }
}

Example 2

This example is similar to the example 1. CreateConnection() will create connection object.


namespace FactoryMethod
{
    public interface IConnectionProvider
    {
        string ConnectionString { get; }
    }

    public class SqlServerConnection : IConnectionProvider
    {
        public string ConnectionString
        {
            get { return "Server=(local);initial catalog=AdventureWorks;Integrated Security=SSPI"; }
        }
    }

    public class OracleConnection : IConnectionProvider
    {
        public string ConnectionString
        {
            get { return "User ID=vorleak;Password=vorleak;Data Source=localhost"; }
        }
    }

    public class MySqlConnection : IConnectionProvider
    {
        public string ConnectionString
        {
            get { return "Database=AdventureWorks;Data Source=192.168.0.1;User Id=vorleak;Password=vorleak"; }
        }
    }

    public class ConnectionProviderFactory
    {
        public IConnectionProvider CreateConnection(string type)
        {
            switch (type)
            {
                case "SQL Server" :
                    return new SqlServerConnection();
                case "Oracle" :
                    return new OracleConnection();
                case "MySQL":
                    return new MySqlConnection();
                default:
                    return null;
            }
        }
    }
}

You don’t need to have condition in the client code just pass parameter type.


using System;
using FactoryMethod;

namespace FactoryMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            ConnectionProviderFactory connectionProviderFactory = new ConnectionProviderFactory();
            IConnectionProvider connectionProvider;

            connectionProvider = connectionProviderFactory.CreateConnection("SQL Server");
            Console.WriteLine("ConnectionString for SQL Server: {0}", connectionProvider.ConnectionString);

            connectionProvider = connectionProviderFactory.CreateConnection("Oracle");
            Console.WriteLine("ConnectionString for Oracle: {0}", connectionProvider.ConnectionString);

            connectionProvider = connectionProviderFactory.CreateConnection("MySQL");
            Console.WriteLine("ConnectionString for MySQL: {0}", connectionProvider.ConnectionString);

            Console.Read();
        }
    }
}
Aug
14

I have two tables which I would like to keep records were changed in DeliveryTypeChanges if user updates the DeliveryCharge in the DeliveryType table.

First time I try to create a trigger that the “SELECT” statement without having “INNER JOIN Deleted” and keep value from “Deleted” to variable before “INSERT”, So what I get is only one record updates to the table.

There are two tables:


Create Table DeliveryType (
	DeliveryTypeID int not null
	Constraint pk_DeliveryType_DeliveryTypeID primary key,
	DeliveryTypeDescription varchar(10) not null,
	DeliveryCharge smallmoney not null
)

Create Table DeliveryTypeChanges (
	ChangeID int identity(1,1) not null
	Constraint pk_DeliveryTypeChanges_ChangeID primary key,
	ChangeDateTime datetime not null,
	DeliveryTypeDescription varchar(10) not null,
	OldDeliveryCharge smallmoney not null,
	NewDeliveryCharge smallmoney not null
)

Here is the trigger to make it works with multiple records:


CREATE TRIGGER trUpdateRecordDeliveryChargeChange
On DeliveryType
FOR UPDATE AS
IF UPDATE (DeliveryCharge)
BEGIN 

	INSERT DeliveryTypeChanges(ChangeDateTime, DeliveryTypeDescription, OldDeliveryCharge, NewDeliveryCharge)
	SELECT GETDATE(), Inserted.DeliveryTypeDescription, Deleted.DeliveryCharge, Inserted.DeliveryCharge
	FROM Inserted INNER JOIN Deleted
	ON Inserted.DeliveryTypeID = Deleted.DeliveryTypeID

END
Aug
11

Working everyday and sitting at your desk in front of your computer, you stare into space, trying to figure out how to write a new feature for your software. You know intuitively what must be done, what data and what objects come into play, but you have this underlying feeling that there is a more elegant and general way to write a software.

In fact, you probably don’t write any code until you can build a picture in your mind of what the code does and how the pieces of the code interact. The more that you can picture, the more likely you are to feel comfortable that you have developed the best solution to the problem.

There are problems rarely stay solved after you’ve handled them once. Developers typically regard their work as tackling individual problems by writing code and solving those problems. But the truth is that in any professional environment, developers almost always end up spending a lot more time on maintenance and adapting code to new situations than writing entirely new code.

A design pattern is a general repeatable solution to a commonly occurring problem in software design. It makes your solution easily reusable, extendable, and maintainable. When you are working on a programming problem, the tendency is to program to the problem, not in terms of reuse, extensibility, maintainability, or other good design issues. And that’s where most developers should be putting in more work because they end up spending far more time on such issues than solving the original problem in the long run. It can also speed up the development process by providing tested, proven development paradigms.

In generally, there are three types: creational, structural, and behavioral.

  • Creational Patterns: create objects for you rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.
  • Structural Patterns: help you compose groups of object into larger structures, such as complex user interfaces or accounting data.
  • Behavioral Patterns: help you define the communication between objects in your system and how the flow is controlled in a complex program.
Jul
24

What is SyntaxHighlighter Plus?

SyntaxHighlighter Plus is a WordPress plugin for code syntax highlighting. it allows you to easily post syntax highlighted code all without loosing it’s formatting or making an manual changes.

It supports the following languages (the alias for use in the post is listed next to the name):

  • Bash — bash, sh
  • C++ — cpp, c, c++
  • C# — c#, c-sharp, csharp
  • CSS — css
  • Delphi — delphi, pascal
  • Java — java
  • JavaScript — js, jscript, javascript
  • PHP — php
  • Python — py, python
  • Ruby — rb, ruby, rails, ror
  • SQL — sql
  • VB — vb, vb.net
  • XML/HTML — xml, html, xhtml, xslt

If you registered account with WordPress.com and you want to post the source code with nice styles on your blog, it is very easy way. You don’t need to find the theme which has a stylesheet defined for PRE or CODE tag. You don’t need to do anything about manual color highlighting for your source code either. You can just paste the sourcecode within

[sourcecode language=’css’]…[/sourcecode]

and specify the language of your sourcecode which is one of example for syntax variants. How easy it is!

SyntaxHighlighter Plus is built upon SyntaxHighlighter with extra features and bug fixes. In addition to the original version, SyntaxHighlighter Plus has the following extra goodies:

  • Valid XHTML markup
  • Background expand fix
  • Corrected Overflow issues
  • More syntax variants:
    • [source language=’css’] … [/source]
    • [code language=’css’] … [/code]
    • [sourcecode lang=’css’] … [/sourcecode]
    • [source lang=’css’] … [/source]
    • [code lang=’css’] … [/code]
    • [sourcecode=’css’] … [/sourcecode]
    • [source=’css’] … [/source]
    • [code=’css’] … [/code]
    • [lang=’css’] … [/lang]
    • [css] … [/css]

Examples

C#


// Select top 5
string[] employees = {
  "Vorleak Chy", "Miika Mäkinen", "Samnang Chhun", "Pong Yem", "Sotra Chhun",
  "Lyna Keat", "Chamnan Nop", "Vathana Keth", "Sopheak Peas"};
IEnumerable<string> items = employees.Take(5);

foreach (string item in items)
  Console.WriteLine(item);

The most of bloggers including me are very happy with this feature.

How is about for self-hosting wordpress bloggers? Is there any plug-in for syntax higtlighting?

Yes, of course.  Please click here to see how to install and configure “SyntaxHighlighter” plug-in.

This plugin uses the SyntaxHighlighter JavaScript package by Alex Gorbatchev.

Jul
24

Currently, you may be running a website for long time which is also more popular and getting more visitors everyday, So it is time to do advertising if you don’t have.

Before that, how do you know your website have more visitors or not? What you need to do is looking to the statistic which is very important for you to sell advertisement.

Even there are more stats plugins available for you such as google stats or the others but you may need to customize for yourself with nice graph and flexible way.

What is a Bar Graph?

A bar graph is a visual display used to compare the amounts or frequency of occurrence of different characteristics of data. This type of display allow us to compare groups of data and to make generalizations about the data quickly.

Vertical CSS Bar Graph

This is a bar graph to display the number of visits per month in year 2007.
You may want to make it like this:

horizontal-bargraph

You need to have two images:

  1. column The column image: For this example the width is always 35px and the height is flexibility which base on formula Value / MaxValue * MaxHeight and rounded to the nearest number. For example data in here is starting from January: 10000 / 100000 * 200 = 20, 17000 / 100000 * 200 = 34, and so on
  2. The background line image
XHTML Codes

<table id="bargraphVertical">
    <tbody><tr><th>Visits 2007</th>
        <td>10000<img src="column.gif" alt="10000" width="35" height="10"></td>
        <td>17000<img src="column.gif" alt="17000" width="35" height="34"></td>
        <td>24000<img src="column.gif" alt="24000" width="35" height="48"></td>
        <td>30000<img src="column.gif" alt="30000" width="35" height="60"></td>
        <td>35000<img src="column.gif" alt="35000" width="35" height="70"></td>
        <td>40000<img src="column.gif" alt="40000" width="35" height="80"></td>
        <td>50000<img src="column.gif" alt="50000" width="35" height="100"></td>
        <td>60000<img src="column.gif" alt="60000" width="35" height="120"></td>
        <td>70000<img src="column.gif" alt="70000" width="35" height="140"></td>
        <td>80000<img src="column.gif" alt="80000" width="35" height="160"></td>
        <td>90000<img src="column.gif" alt="90000" width="35" height="180"></td>
        <td>100000<img src="column.gif" alt="100000" width="35" height="200"></td>
    </tr></tbody>
    <tfoot><tr><th>Month</th>
        <th>Jan</th>
        <th>Feb</th>
        <th>Mar</th>
        <th>Apr</th>
        <th>May</th>
        <th>Jun</th>
        <th>Jul</th>
        <th>Aug</th>
        <th>Sep</th>
        <th>Oct</th>
        <th>Nov</th>
        <th>Dec</th>
	</tr></tfoot>
</table>
CSS Codes

  #bargraphVertical{
    font:0.7em Arial;
    width:475px;
    border:1px solid #ccc;
  }
  #bargraphVertical td{
    padding:0;
    margin:0;
    vertical-align:bottom;
    text-align:center;
    background:#eee url(graphbg.gif) 15px bottom;
  }
  #bargraphVertical img{
    display:block;
    border-right:1px solid #fff;
  }
  #bargraphVertical th{
    font-weight:normal;
  }

Horizontal CSS Bar Graph

This is a bar graph to display the number of visitors within countries.
It is very similar to the Vertical Bar Graph implementation. We use this when the label is longer text such “REPUBLIC OF KOREA” as an example.

horizontal-bargraph

You need to have one image:

row
The row image: For this example the height is always 10px and the width is flexibility which base on formula Value / MaxValue * MaxWidth and rounded to the nearest number. For example data in here is starting from CAMBODIA: 100000 / 100000 * 200 = 20, 90000 / 100000 * 200 = 180, and so on

XHTML Codes

<table id="bargraphHorizontal"><tbody>
  <tr>
    <th class="label">Country</th>
    <th class="val">Visitors</th>
  </tr>
  <tr>
    <td class="label">CAMBODIA</td>
    <td class="val"><img src="row.gif" width="200" height="10"> 100000</td>
  </tr>
  <tr>
    <td class="label">UNITED STATES</td>
    <td class="val"><img src="row.gif" width="180" height="10"> 90000</td>
  </tr>
  <tr>
    <td class="label">AUSTRALIA</td>
    <td class="val"><img src="row.gif" width="160" height="10"> 80000</td>
  </tr>
  <tr>
    <td class="label">Unknown</td>
    <td class="val"><img src="row.gif" width="140" height="10"> 70000</td>
  </tr>
  <tr>
    <td class="label">FRANCE</td>
    <td class="val"><img src="row.gif" width="120" height="10"> 60000</td>
  </tr>
  <tr>
    <td class="label">THAILAND</td>
    <td class="val"><img src="row.gif" width="100" height="10"> 50000</td>
  </tr>
  <tr>
    <td class="label">REPUBLIC OF KOREA</td>
    <td class="val"><img src="row.gif" width="80" height="10"> 40000</td>
  </tr>
  <tr>
    <td class="label">CANADA</td>
    <td class="val"><img src="row.gif" width="70" height="10"> 35000</td>
  </tr>
  <tr>
    <td class="label">JAPAN</td>
    <td class="val"><img src="row.gif" width="60" height="10"> 30000</td>
  </tr>
  <tr>
    <td class="label">SINGAPORE</td>
    <td class="val"><img src="row.gif" width="48" height="10"> 24000</td>
  </tr>
</tbody></table>
CSS Codes

#bargraphHorizontal{
  font:0.7em Arial;
  border:1px solid #ccc;
}
#bargraphHorizontal th{
  font-weight:normal;
}
#bargraphHorizontal td{
  padding:1px 0;
  margin:0;
}
#bargraphHorizontal .label{
  text-align:right;
}
#bargraphHorizontal .val{
  text-align:left;
}
#bargraphHorizontal img{
  vertical-align:middle;
}
Jul
21

I would say I like Twitter. Ideally, you can post a short message about what you are up to and it then appears to anyone who has subscribed to your updates. Facebook is also included it.

The nice thing about updates is that they are passive. They don’t fill up an inbox like email so you can let others know about something you are up to that is interesting. It is a great way to start conversations that never would have happened otherwise.

Jul
21

While I was trying to display nicely formatted .Net codes on my blog I found  CopySourceAsHtml which is a Visual Studio plugin.

If you want to try please download and it’s installed simply. The code on your blog looks exactly like it would in Visual Studio. It also works with almost any blog which is just Html there is nothing that needs to be done on the server.

How to use it

In Visual Studio, Just select the code you want to display -> right click -> select Copy As HTML. A clean HTML representation of you code will be copied onto the clipboard which can then be pasted into your blog editor.
I like Windows Live Writer as my blog editor which I can save in local first before publish to online and there are many good plugins are available.
It supports with Visual Studio 2005 for now. So if you are using newer version which is Visual Studio 2008 then.

How to make CopySourceAsHtml works with Visual Studio 2008

Currently there is no Visual Studio 2008 version of this Add-in available to download but it is very easy way to make it works with VS 2008.
In the Addins path of VS 2005
(If you are using Window Vista it is usually in C:\Users\USERNAME\Documents\Visual Studio 2005\Addins)
You will find the following files:

  • CopySourceAsHtml.dll
  • CopySourceAsHtml.AddIn
  • CopySourceAsHtml.dll.config
  1. Copy those files to the Addins path for VS 2008
  2. Open CopySourceAsHtml.AddIn file in a text or XML editor in the Addins folder of VS 2008
  3. Change as seen below and save the changed file back into the VS 2008 Addins folder.
    The original file contained text <Version>8.0</Version> instead of <Version>9.0</Version>

    
    <?xml version="1.0" encoding="UTF-16" standalone="no"?>
    <Extensibility xmlns="http://schemas.microsoft.com/AutomationExtensibility">
        <HostApplication>
            <Name>Microsoft Visual Studio Macros</Name>
            <Version>9.0</Version>
        </HostApplication>
        <HostApplication>
            <Name>Microsoft Visual Studio</Name>
            <Version>9.0</Version>
        </HostApplication>
        <Addin>
            <FriendlyName>CopySourceAsHtml</FriendlyName>
            <Description>Adds support to Microsoft Visual Studio 2005 for copying source code, syntax highlighting, and line numbers as HTML.</Description>
            <Assembly>CopySourceAsHtml.dll</Assembly>
            <FullClassName>JTLeigh.Tools.CopySourceAsHtml.Connect</FullClassName>
            <LoadBehavior>5</LoadBehavior>
            <CommandPreload>0</CommandPreload>
            <CommandLineSafe>0</CommandLineSafe>
        </Addin>
    </Extensibility>
    
  4. In Visual Studio 2008 go to Tools -> Add-in-Manager -> Activate the AddIn

Now you can get CopySourceAsHtml works with Visual Studio 2008.

Jul
17

After one of the applications is done successfully completed with automatic unit tests and send to users, what else I need to do is that waiting to get feedback from users. You know what the user compliant is user interface (I am wondering how I can test user interface to meet the user requirement beforehand, maybe no way for now). So I add codes to my application but not much is to set background color to be Kaki of TextBox or ComboBox if the cursor is in. Also, if you press enter key the cursor will focus to next control it depends on Tab Order.

Here is the example with User Information form as one of them:

user-information

Implementation

Create one class Utility

using System;
using System.Drawing;
using System.Windows.Forms;

public static class Utility
{
    public static void AddEventHandler(Control panel)
    {
        foreach (Control control in panel.Controls)
        {
            if (control is TextBox || control is ComboBox)
            {
                control.KeyDown += control_KeyDown;
                control.Enter += control_Enter;
                control.Leave += control_Leave;
            }

            if (control.HasChildren)
            {
                AddEventHandler(control);
            }
        }
    }

    private static void control_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData != Keys.Return) return;

        e.Handled = false;
        SendKeys.Send("{TAB}");
    }

    private static void control_Enter(object sender, EventArgs e)
    {
        ((Control) sender).BackColor = Color.Khaki;
    }

    private static void control_Leave(object sender, EventArgs e)
    {
        ((Control) sender).BackColor = Color.FromKnownColor(KnownColor.Window);
    }
}

Call AddEventHandler(this) method in the form load event

private void frmUserInformation_Load(object sender, EventArgs e)
{
    Utility.AddEventHandler(this);
}