April 2007 - Posts

A thank you note from by Project's SA

Well as you know today is a holiday in most companies in Malaysia like my company. However my project's production is next week. So there is a lot of preparation for this. As you know I will be going to Singapore tomorrow night, so I am pretty busy with work and making sure I can really go to Singapore.

So I decide to work today and hope to get things done. Earlier in the afternoon, there was a discussion to change a logic which will involve on a number of sections in the software. I was quite stress at first as it would involve a lot of changing and it was kinda last minute to change now.

But after thinking twice it is for the good of the project.

I managed to finish the changes by 6.30 p.m. Around 6.45 p.m. I was on the phone with my friend, looking for a place to have dinner. Then my SA's wrote something on a piece of paper and passed it to me while I was on the line. I never expected to see this :)

Guess hard work and strong determination pay off :P

Posted by chuawenching with no comments
Filed under:

ASP.NET 2.0 Life savior - RegularExpressionValidator for FileUpload control

Why did I say it was a life savior? I believe this tip is very handy for everyone. This was a problem faced by colleague. So I took up the challenge to look into this.

If you browse the internet you will find a lot of people recommending using RegularExpression Validator to validate the FileUpload control on certain file formats to be used. Some disagree on this and recommend on ServerValidate. Take note, I am not here to debate on which one to use. I am here to blog on just RegularExpressionValidator on FileUpload control and explains the best way to achieve the right result. Let me know what you think of this J

Below is the sample code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:Button ID="btnDeleteImg" runat="server" Text="Delete Image" OnClick="btnDeleteImg_Click" /><br />

            <asp:FileUpload ID="fUpload" runat="server" Width="550px" />&nbsp;

            <asp:Button ID="btnUpload" runat="server" Text="Upload" Width="76px" OnClick="btnUpload_Click" />&nbsp;

            <asp:RegularExpressionValidator ID="refImage" SetFocusOnError="True" runat="server" ControlToValidate="fUpload"

                ErrorMessage="Upload Jpegs and Gifs only" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$"

                Display="Dynamic"></asp:RegularExpressionValidator>

        </div>

    </form>

</body>

</html>

 

So the expression is like this "^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$" which is used in this scenario.

Yes it works entirely fine on the validation. But soon later you will realize a problem.

Let’s visualize this in a table view based on the code above.

[Delete Button

[File Upload control]

[Upload Control]

[RegularExpressionValidator]

 

When you try to browse a music file, you will see an error like below:

[Delete Button

[File Upload control] c:/sgdotnet/elephant.mp3

[Upload Control]

[RegularExpressionValidator] Upload Jpegs and Gifs only

 

When you try to browse a proper image this time, the error will disappear

[Delete Button

[File Upload control] c:/sgdotnet/tortoise.jpg

[Upload Control]

[RegularExpressionValidator]

 

Now guess what when you press upload which will cause a postback, not only the image is being saved but the error message will suddenly appear. Take note, you definitely do not want to see this right.

[Delete Button

[File Upload control]

[Upload Control]

[RegularExpressionValidator] Upload Jpegs and Gifs only

** When you upload the image file, the File Upload’s textbox will be cleaned

So you will be shocked? What is the problem here? It doesn’t make sense for the error message to appear.

Then I came into a conclusion that there might be a slight possibility on the RegularExpression ValidateExpression. Take note, I am not so good in RegularExpression but I believe it helps me to achieve results here and definitely in this context.

So I came out with this instead:

"^.+\.((jpg)|(gif)|(jpeg)|(png)|(bmp))$"

It solved the problem. Yes. Thanks god and I was very happy that I was able to solve this problem. Most people on the internet recommended the 1st way and honestly speaking it did validated, but the error will occurred on postback.

Have fun and hope you find this useful for you.

My MVP Profile

Check this out my MVP profile https://mvp.support.microsoft.com/profile=78F5C4EE-6B72-4072-A34F-25FF5BB61450

Took this picture in office. Thanks to Nazir for editing for me this picture.

I promise I will still remain as active as before in community. Finally finished my hardest business logic for my development. The rest should be light bug fixing.

Posted by chuawenching with 2 comment(s)
Filed under:

High School Musical - Recommended to watch

I know I am kinda outdated on this show. Haha. At first I critisized my friend "Malay Girl" at office in watching a kid's show. So last Sunday my sister borrowed me and she told me that it was superb. Even my elder brother gave thumbs up on the show.

So I decided to watch it. Amazingly, it was quite nice. The songs are superb and that girl is so adorable. I even took the initiative to get the soundtracks for this show.

Check this link below about this movie http://psc.disney.go.com/disneychannel/originalmovies/highschoolmusical/

I heard there will be part 2 for this movie.

Posted by chuawenching with no comments
Filed under:

IASA Architect Synopsium 2007 - Not able to attend

Due to unforseen circumstance, I am not able to attend this event. Well it is quite obvious as I am still working in office at 12.41 a.m. to focus on production's preparation. Sad a bit.. coz I got free pass to this event by both IASA and Microsoft. Basically MIND is an affliation to IASA in promoting this event.

I could't find anyone to replace me so last minute so I had decided to ask my Team Leader from Mesiniaga to replace me. Since he had been very supportive in my events, so he would be a better choice to attend this event :)

Miss the chance to meet Father of UML.

Posted by chuawenching with no comments
Filed under:

ASP.NET 2.0 RegisterStartupScript: Validate IC == Date Of Birth

Take note, I am not a very good JavaScript coder, but I am in process learning and improving. So do forgive me if I make a stupid mistake or write bloated code for this. But the way here is proven working on my scenario J

Here is the scenario.

I have 2 fields in a user details registration form.

Identification Number

:

Field 1

Date of Birth

:

Field 2

 

In Malaysia, our identification card number is broken into 3 sections:

[820904]-[XX]-[XXXX]

[820904] = The 1st part is our birthday probably in a format like yy/mm/dd.

[XX] = state id

[XXXX] = These 4 numbers are unique and represent each Malaysian

So for my case, my Identification Number field I will have 3 Text Boxes.

Identification Number

:

[TextBox1]-[TextBox2]-[TextBox3]

 

Now for the 2nd field which is the Date of Birth. I will have a reusable user control just for this calendar functionality. Let’s assume that this user control has 2 fields: 1 textbox and 1 button. When you click on the button, it will show a div popup which shows Calendar. You selected on the date you want and it will display the value to the textbox in the calendar user control (e.g. 1-April-2007)

Let’s move on.

Now your boss is impressed with your work especially the user interface but he needs you to add a new functionality.

When you selected a date from the calendar control, it needs to validate with the Identification Number. He wants you to do on the client side with probably using JavaScript.

Solution

I will be implementing RegisterStartupScript for this situation as I need to use a CustomValidator. If you have not read my earlier article, check this out http://community.sgdotnet.org/blogs/chuawenching/archive/2007/04/09/ASP.NET-2.0-When-should-you-consider-using-RegisterStartupScript_3F00_.aspx

Let’s see the sample JavaScript code which is written in C#. I will explain further.

Place this static method inside the Global file

  605 public static void IdAndDobValidation(System.Web.UI.Page page, Type type, params string[] args)

  606         {

  607             string jsFunctionName = "IdAndDobValidation";

  608 

  609             StringBuilder jsBuilder = new StringBuilder();

  610             jsBuilder.Append("<script language=\"javascript\">\n");

  611             jsBuilder.Append("function " + jsFunctionName + "(sender, args)\n");

  612             jsBuilder.Append("{\n");

  613 

  614             // args[0] = 820904-XX-XXXX

  615             jsBuilder.Append("\tvar year = document.all('" + args[0] + "').value.substring(0, 2);\n");

  616             jsBuilder.Append("\tvar month = document.all('" + args[0] + "').value.substring(2, 4);\n");

  617             jsBuilder.Append("\tvar day = document.all('" + args[0] + "').value.substring(4, 6);\n");

  618 

  619             // convert it to a actual javascript date object

  620             jsBuilder.Append("\tvar myDate = new Date(month + '/' + day + '/' + year);\n");

  621 

  622             // remove the '-' in DOB

  623             // args[1] = 4-September-1982

  624             jsBuilder.Append("\tvar splitDOB = document.all('" + args[1] + "').value.split('-');\n");

  625 

  626             // Generate a new date object based on dd/mm/yyyy

  627             jsBuilder.Append("\tvar myDOB = new Date(checkMonth(splitDOB[1]) + '/' + splitDOB[0] + '/' + splitDOB[2].substring(2, 4));\n");

  628 

  629             jsBuilder.Append("\tif (+myDate == +myDOB)");

  630             jsBuilder.Append("{\n");

  631             jsBuilder.Append("\t\targs.IsValid = true;");

  632             jsBuilder.Append("}\n");

  633             jsBuilder.Append("\telse");

  634             jsBuilder.Append("{\n");

  635             jsBuilder.Append("\t\targs.IsValid = false;");

  636             jsBuilder.Append("}\n");

  637 

  638             jsBuilder.Append("}\n");

  639             jsBuilder.Append("</script>");

  640 

  641             page.ClientScript.RegisterStartupScript(type, jsFunctionName, jsBuilder.ToString());

  642         }

 

In line 614 – 617, basically it is expecting the 1st argument args[0] which is the the 1st section of the Identification Number. Remember this 1st section represents the 1st 6 numeric numbers of an Identification Number.

I need to break this string “820904” into three sections as below:

“82” “09” “04”

Then I need to create a JavaScript Date object based on these 3 strings. Check line 620.

Now I will focus on the Date of Birth instead. I need to remove the ‘-‘ from the string and create a new Date object like what I did above. When you are using Split method for your string, the string will be broken into 3 parts.

4-September-1982

splitDOB[0] = “4”

splitDOB[1] = “September”

splitDOB[2] = “1982”

Later you will wonder, why should I do this for? Why can’t you compare the date object by the Identification Number with Date of Birth like ‘4-September-1928’.

i) You are expecting a string value from args[1]

ii) You cannot compare a string value with a date object

iii) If you try to cast args[1] to a date object like below:

var myDate = new Date(document.all(‘args[1]’).value)

You will receive a NaN – Not a Number. I am too sure in detail on this, but I will need to investigate more on JavaScript.

Remember you are getting September, so you need to create a reusable function to convert it into an interger. Very simple, just do switch statements like below:

            function checkMonth(varMonth)

          {

              switch(varMonth)

              {

                  case "January":

                      varMonth = "1"

                      break

                  case "February":

                      varMonth = "2"

                      break

                  case "March":

                      varMonth = "3"

                      break   

                  case "April":

                      varMonth = "4"

                      break

                  case "May":

                      varMonth = "5"

                      break

                  case "June":

                      varMonth = "6"

                      break

                  case "July":

                      varMonth = "7"

                      break

                  case "August":

                      varMonth = "8"

                      break

                  case "September":

                      varMonth = "9"

                      break

                  case "October":

                      varMonth = "10"

                      break  

                  case "November":

                      varMonth = "11"

                      break

                  case "December":

                      varMonth = "12"

                      break                                          

              }

     

            return(varMonth);  

        }

Next is the best part.

You cannot simply compare between the 2 dates like below:

If (myDate == myDOB) {}

Trust me, you will always get a false value even it is the same.

So instead use an unary operator ‘+’ in front of each date like line 629. There are recommendations ot use ValueOf instead, but I don’t seem to get the right results. This solves it J

Now, in your user registration form’s page_load event, paste the code below:

  162 TextBox dobTextBox = uclDateOfBirth.FindControl("txtDateValue") as TextBox;

  163             Global.IdAndDobValidation(Page, typeof(Page), txtNewIcNo1.ClientID, dobTextBox.ClientID);

 

Since I mentioned above that the textbox resides inside a calendar user control, so you need to use FindControl for this. You can create a property for this inside this calendar user control if you hate to use FindControl.

Lastly, this is the HTML code for the CustomValidator.

<asp:CustomValidator ID="csvDOB" runat="server" Display="Dynamic" ErrorMessage="DOB must be equivalent with your IC"

                                        ClientValidationFunction="IdAndDobValidation">DOB must be equivalent with your IC</asp:CustomValidator>

Hope you find this useful. But I believe that this concept should work for Identification Numbers in other countries.

Have a nice weekend.

Posted by chuawenching with 2 comment(s)
Filed under:

Trip to Singapore for LOVE event confirmed

Hi, my trip is confirm. I had purchased the tickets earlier today.

See you all in the LOVE event. I hope I am part of the registration list :P

I plan to meet some of my Singapore's friends who I worked with last time. Also my best friend Ms. Gan. Well she is a Malaysian but she works in Singapore because the boyfriend is there. Romantic couple :) Didn't see her for few years.

I will reach Singapore on Saturday morning and back to Malaysia on Sunday night. I plan to stay there longer but I fail to get ticket back to Malaysia on May 1. FYI, May 1 and May 2 are holidays in Malaysia. Will be staying at Yi Shun, friend's place. Apparently in the living room LOL

Thanks.

Figure 1: 2 tickets to-back

Figure 2: Kuala Lumpur - Singapore

Posted by chuawenching with no comments
Filed under:

MVP Recognition in Mesiniaga: Appeared in notice board

Well basically today I appear in the Mesiniaga's notice boards on each floor (total of 12) for being a Microsoft MVP. Honestly speaking I was never being advertised on notice boards since the day I worked till today.

Check out the pictures below.

 Figure 1: Employee Recognition column

 Figure 2: My picture :) Some commented that I should wear coat. :P

Posted by chuawenching with no comments
Filed under:

AsiaGamesZone event postponed to August 2007

The organizer of this event had postponed the event to August 2007. Anyway it looks like probably I can go to Singapore :) 90% of chances.

Even though I had booked the train, but I had not purchased it. Once I purchase it, I will confirm with Alvin. Hope to see you guys in Singapore.

Darren, let's play pool. I don't believe I will lose to you again :P That time just 1 ball.. arghhh :(

Hehe.

Posted by chuawenching with no comments
Filed under:

2007 Microsoft Office System Technical Beta Tester - Thanks Microsoft

I just got a Certificate of Appreciation signed by Mr. Bill Gates from Microsoft. I was involved in a beta testing on 2007 Microsoft Office System back then. It was my 1st time doing a technical beta testing for Microsoft products :)

Thanks Microsoft. Cool stuff.

There are only 2 issues haha...

a) the paper quality and the printing were not so good :(

b) There was no my name written on the cert ... only on the mail postal letter :(

See the pictures below:

Figure 1: Cover letter and the Certificate

Figure 2: The Certificate with Mr. Bill Gates signature

Posted by chuawenching with no comments
Filed under:

Singapore Community LOVE 2007 - I might attend

I am thinking a lot whether I want to attend this event or not. Yes I had just registered myself. I had also booked my train tickets and also informed my friend in Singapore to stay for a couple of days.

But I am still wondering whether I should go to Singapore or back to my hometown for a break.

All this while I had been organizing events, I really feel like attending someone events and see how people organizing their events? So I think there is 80% that I will be there in Singapore.

FYI, May 1 and 2 are holidays in Malaysia. So I will take a leave on April 30 :)

Posted by chuawenching with no comments
Filed under:

Farewell my fellow buddy Mahzan, Mesiniaga

Mahzan is one of the best colleague I work with in the industry. Today is his last day and he will be heading to Monsters for a new career. All the best and hope to work with you again one day.

Thanks.

Posted by chuawenching with no comments
Filed under:

TDD Anti-Patterns - Interesting to read

This is something interesting to read. All this while I thought there were only Anti-Design Patterns. I didn't notice that there would be Anti-Patterns for Test Driven Development.

http://blog.james-carr.org/?p=44

I recommend this url. It is worth to read and realizes the common pitfalls :)

Posted by chuawenching with no comments
Filed under:

ASP.NET 2.0 When should you consider using RegisterStartupScript?

Remember last Friday I blogged on Deeper into CustomValidator Part 2, I actually mentioned about RegisterStartupScript in the Conclusion. If you have not read about this, check this out here http://community.sgdotnet.org/blogs/chuawenching/archive/2007/04/06/ASP.NET-2.0-Deeper-into-CustomValidator-Part-2.aspx

I am not sure whether most of you are aware of this RegisterStartupScript. I believe some of you had coded it, heard of it or probably new to it.

Since I am not a theory guy, basically you can use RegisterStartupScript to inject JavaScript markup into your web pages. Then think of it, why should do this if you can manually place the JavaScript code block in your html during coding instead of runtime.

I will provide a simple scenario, so you can visualize on what you need this for?

Scenario

 

Below is the web project hierarchy

Master Page

è frmA

o   uclA

è frmB

o   uclB

You have a standard and reusable control called uclBizLogic which is part of both uclA and uclB.

In this user control, you have a lot of textboxes, 2 checkbox lists, 1 button and validation controls. When you click on the button in frmA, it will redirect to frmB.

Let’s drill down on the CheckBoxLists validation logic.

Check the tables diagram below:

Parent Item

:

[CheckBoxListParent] [CustomValidator here]

[ListItem index=”0” value=”Yes”]

Child Item

:

[CheckBoxListChild]

[ListItem index=”0” value=”MIND”]

[ListItem index=”1” value=”INETA APAC”]

 

Okay you will have only one item in the Parent CheckBoxList. It is either you checked it or you don’t. In Child CheckBoxList, you have 2 items (MIND and INETA APAC).

You have logic here. If you checked the Parent CheckBoxList’s ListItem, you must check either one of the ListItem in Child’s CheckBoxList or you can check both of them. But you cannot leave both of them unchecked or else you will be prompt an error “Please checked either one in Child”.

Now looking at this scenario, you will be wondering why can’t I code JavaScript and place this in the MasterPage head element.

<script language="javascript">

function ParentValidation(sender, args)

{   

    if (document.all('_ctl0_ContentPlaceHolder1_uclA_ uclBizLogic _cblParent_0').checked == true)

    {

        if (document.all('_ctl0_ContentPlaceHolder1_uclA_uclBizLogic_cblChild_0').checked != true

            && document.all('_ctl0_ContentPlaceHolder1_ uclA_uclBizLogic_cblChild _1').checked != true)

       {

            args.IsValid = false;

       }

       else

       {

            args.IsValid = true;

       }

    } 

    else

    {

        args.IsValid = true;

}

</script>

If you do notice one thing here, I am actually hardcoding the ClientID of all the controls here. But remember this; you actually have uclBizLogic in both frmA and frmB. If you only have this user control in 1 form, you can just follow the code above. What do I mean by this?

In frmA, you will have ID like this:

_ctl0_ContentPlaceHolder1_uclA_uclBizLogic_cblChild_0

In frmB, you will have ID like this:

_ctl0_ContentPlaceHolder1_uclB_uclBizLogic_cblChild_0

So now what? How can I dynamically pass in the ClientID of the controls into my JavaScript and still using ClientSideValidation of a CustomValidator?

This is where RegisterStartupScript comes in handy.

Just take note one more thing, on the syntax changes

Previously:

this.Page.RegisterStartupScript(jsFunctionName, jsBuilder.ToString()); 

Now:

this.Page.ClientScript.RegisterStartupScript(typeof(Page), jsFunctionName, jsBuilder.ToString());