Wednesday, April 17, 2013

Web Server Control Lable

As what we known, label is one of heavily used control in ASP.NET web application. And you may easily find a label control somewhere of every pages. Therefore, Matering this control is a key to build successfully web application. Although Label control is simple and straightforward to be get involved, I still want to share my own experience how to use it wisely. Hopefully, you will enjoy this topic and find some useful staff.

Web Server Control: Label
NameSpace: System.Web.UI.WebControls

Tip #1: AssociatedControlID is a property by which a Lable can be associated to an input control, like TextBox. And it does provide a way binding two associated controls together. Whenever users click on a label that has an AssociatedControlID, cursor will move to the associated control automatically. To explore the behaviour you may expect, you can click on the demo Amount Financed Lable below.

Code Snippet:
<asp:Label ID="lblAmountFinanced" runat="server" Text="Amount Financed" AssociatedControlID="txtAmountFinanced"></asp:Label>
<asp:TextBox ID="txtAmountFinanced" runat="server"></asp:TextBox>

Demo:

 

There is no surprise that most of C#/VB progrmmers don’t pay much attention on this property. However, using AssociatedControlID with Lable control will definitely improve the users' experience.


Tip #2: Normally, while using Javascript, we use command document.getElementById(“ControlID”).value to retrieve and assign value to a control. However, this command will not work at Lable control. In order to manipulate Lable value, you have to use command document.getElementById(“lblAmountFinanced”).innerHTML instead of document.getElementById(“lblAmountFinanced”).value. Otherwise, you will get undefined value. To compare the diffrence between two command, you can click on the demo buttons below.

Demo:

        


Tip #3: Literal control is similar to Lable control. In most of cases, we can swap these two controls each other. However, in centain particular situation, only either Lable control or Literal control can be applied. For instance, Literal control does not allow you to apply a style to the displayed text; thus, Lable control has be chosen if style will be applied. On the other hand, Literal control will be only choice when we're dynamically creating <title> tags, or <link type="text/javascript"> tags, or <meta name="keywords"> tags, ets....

Code Snippet:
<head>
      <title><asp:Literal id="litTitle" text="Michael Kong's Blog" runat="server" /></title>
      <title><asp:Lable id="lblTitle" text="Michael Kong's Blog" runat="server" /></title>
</head>

Demo:

Literal control will render as:  <title>Michael Kong's Blog</title>
Lable control will render as (invalid HTML):   <title><span>Michael Kong's Blog</span></title>

Monday, April 15, 2013

Web Server Control Regular Expression Validator

RegularExpressionValidator is one of most useful validation controls which automatically provides both client-side and server-side validation. It is simple and straigforward to be invoded. All what you need it to supply an appropriated regular expression. And the web server control will hanlde both client-side and server-side validations for you. As long as you are familiar with the way to construct a regular expression, you will be able to validate lots of inputs by using RegularExpressionValidator. For instance, Email, URL, Phone #, Postal Code, SIN, Strong Password and etc...
Web Server Control: RegularExpressionValidator
NameSpace: System.Web.UI.WebControls

Metacharacters for Matching Type of Characters
Character Class Description
. Matches any character except \n
[aeiou] Matches any single character specified in the set
[^aeiou] Matches any character not specified in the set
[3-7a-dA-D] Matches any character specified in the specified ranges
\w Matches any word character; that is, any alphanumeric character or the underscore.
\W Matches any nonword character
\s Matches any whitespace (space, tab, form feed, newline, carriage return, or vertical feed).
\S Matched any nonwhitespace character
\d Matches any decimal character
\D Matched any nondecimal character
Metacharacters for Matching Single Characters
Character Escapes Description
Ordinary characters Characters other than .$^{[(|)*+?\
\b Matches a backspace
\t Matches a tab
\r Matches a carriage return
\v Matches a vertical tab
\n Matches a newline
\f Matches a form feed
\ If followd by a special character (one of .$^{[(|)*+?\), this character escape matches that character leteral.
Quantifiers
Quantifier Description
* Zero or more matches
+ One or more matches
? Zero or one matches
{N} N matches
{N,} N or more matched
{N,M} Between N and M matches (inclusive)
Demo #1: Validate Canadian Postal Code: [a-zA-Z]\d[a-zA-Z]\s?\d[a-zA-Z]\d"

   

Demo #2: Validate USA Zip Code: \d{5}(-\d{4})?

   

Demo #4: Validate Internet Email Address: \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

   

Demo #5: Validate Internet URL: ([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

   

Demo #6: Validate North America Phone Number: \d{3}-?\d{3}-?\d{4}

   

Demo #7: Validate USA Social Security Number: \d{3}-?\d{2}-?\d{4}

   

Demo #8: Validate Canadian Social Insurance Number: \d{3}-?\d{3}-?\d{3}

   

Saturday, April 13, 2013

C# Naming Convention Design Guideline

C# naming convention design guideline

A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library. Widespread use and understanding of these naming guidelines should eliminate unclear code and make it easier for developers to understand shared code.

Pascal case: The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized.
Camel case: The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.
Upper case: Only use all upper case separated by underscore "_" for identifiers.

  1. Namespace naming convention: CompanyName.SolutionName.ProjectName.ModualName (Pascal Case)
    • MicNets.Blog.Web
    • MicNets.Blog.DAL
    • MicNets.Blog.Biz
  2. Class naming convention: Use a noun or noun phrase to name a class, and avoid using the underscore character "_" (Pascal Case)
    • Account
    • BookStore
    • Department
  3. Interface naming convention: Prefix Interface name with a character "I", and avoid using the underscore character "_" (Pascal Case)
    • IAccount
    • IStore
    • IDepartment
  4. Method parameters & Local method variables naming convention: Use descriptive parameter name (Camel Case)
    • depositAmount
    • days
    • isWeekend
  5. Constants naming convention: Use all uppercase with noun words separated by underscore "_" to name constant (Upper Case)
    • MAXIMUM_DAILY_TRASACTION_AMOUNT
    • HOURS_OF_DAY
    • MINNUTES_OF_HOUR
  6. Enumerations naming convention: Use a singlton noun begins with an "N" prefix (Pascal Case)
    • NAccountType
    • NCategory
    • NFontSize
  7. Private Member variables naming convention: Prefix private member variable with an underscore "_" (Camel Case)
    • _price
    • _balance
    • _description
  8. Properties naming convention: Must exactly match the member variable name without an underscore "_" prefix (Pascal Case)
        private decimal _price;
        public decimal Price 
        {
            get { return _price; }
            set { _price = value; }
        }
    
  9. Methods/Functions naming convention: Use verbs or verb phrases to name methods or functions (Pascal Case)
    • LoadAllApplication()
    • InsertOneCustomer()
    • ReserveTicket()
  10. Code blocks opening and closing braces: Code blocks always be opened on the next line as a statement.
        for (int i = 0; i < 10; i++)
        {
            // do something;
        }
    
  11. Spacing: Spaces improve readability by decreasing code density.
    • Use a space after a comma between function parameters
      • Bad:  GetCustomerList(int CountryID,int StateID,bool blnMale)
      • Good: GetCustomerList(int CountryID,  int StateID,  bool blnMale)
    • Use a space before flow control statements
      • Bad:   while(true)
      • Good: while  (true)
    • Use a space before and after comparison operators
      • Bad:   if (amountDeposit>=amountWithdraw)
      • Good: if (amountDeposit  >=  amountWithdraw)
    • Do not use spaces before or after the parenthesis and function parameters
      • Bad:  SelectAllBook(  string storeName  )
      • Good: SelectAllBook(string storeName)
    • Do not use spaces between a function name and parenthesis
      • Bad:   InsertOne  ()
      • Good: InsertOne()
    • Do not use spaces inside brackets
      • Bad:   Customer[  "Index"  ]
      • Good: Customer["Index"]
  12. Magic number: No magic number should be used in coding, except -1, 0 and 1. Using descriptive constant or variable to hold the value.
    • Bad:  if (NumOfPaymentPerYear == 12)
    • Good: int const MONTHLY_NUM_PAYMENT_PER_YEAR = 12; if (NumOfPaymentPerYear == MONTHLY_NUM_PAYMENT_PER_YEAR)
    • Bad:  for (int i = 0; i < 10; i++)
    • Good: int maxCount = 10; (int i = 0; i < maxCount; i++)
  13. Local variable: Local variable names should be descriptive enough. And initialize local variables as soon as they are declared
    • string errorMeg = string.Empty;
    • decimal interestRate = decimal.Zero;
    • int numOfPayment = 0;
    • bool blnIsWeekend = false;
  14. The length of class and method: Class and method should be kept them short and neat.
    • Any classes with more than 2000 lines of coding should be broken down to other sub classes.
    • Any methods that have more than 30 lines of coding should be broken down to other sub methods.