RaviVarma Thumati’s Blog

December 10, 2008

Coding Standards and Best Practices

Filed under: Coding Standards & Best Practices — Ravi Varma Thumati @ 11:02 am
Tags:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Coding Standards and Best Programming Practices

 

 

 


 

 

  1. Author …………………………………………………………………………………………….
  2. Revision History …………………………………………………………………………………
  3. Introduction ………………………………………………………………………………………
  4. Purpose of coding standards and Best programming practices …………………………………..
  5. How to follow the standards across the team …………………………………………………….
  6. Naming conventions and standards ………………………………………………………………
  7. Indentation and Spacing ………………………………………………………………………….
  8. Good Programming practices ……………………………………………………………………
  9. Architecture ………………………………………………………………………………………
  10. ASP.NET …………………………………………………………………………………………
  11. Comments ……………………………………………………………………………………….
  12. Exception Handling ………………………………………………………………………………
  13. Choosing between Convert and Type Parse …………………………………………………….
  14. Using the default keyword in C# ……………………………………………………………….
  15.  The second pillar of Object Oriented Programming – Inheritance ……………………………
  16. Automatic Validation of Objects ………………………………………………………………
  17. Avoid Casting to improve code performance …………………………………………………
  18. Introduction to the Resources .resx and .resource files ………………………………………..


1.      Author

This document is prepared by the DotNet team.

 

Most of the information in this document is compiled from the coding standards and best practices published in various articles in Internet. Also, we referred to the guidelines published by Microsoft and various other sources.

 

2.      Revision History

If you are editing this document, you are required to fill the revision history with your name and time stamp so that anybody can easily distinguish your updates from the original author.

 

S. No#

Date

Changed By

Description

1

 

 

 

2

 

 

 

 

3.      Introduction

Anybody can write code. With a few months of programming experience, you can write ‘working applications’. Making it work is easy, but doing it the right way requires more work, than just making it work.


Believe it, majority of the programmers write ‘working code’, but not ‘good code’. Writing ‘good code’ is an art and you must learn and practice it.

 

Everyone may have different definitions for the term ‘good code’. In my definition, the following are the characteristics of good code.

 

·          Reliable

·          Maintainable

·          Efficient

 

Most of the developers are inclined towards writing code for higher performance, compromising reliability and maintainability. But considering the long term ROI (Return On Investment), efficiency and performance comes below reliability and maintainability. If your code is not reliable and maintainable, you (and your company) will be spending lot of time to identify issues, trying to understand code etc throughout the life of your application

 

4.      Purpose of Coding standards and Best practices

To develop reliable and maintainable applications, you must follow coding standards and best practices.

 

The naming conventions, coding standards and best practices described in this document are compiled from our own experience and by referring to various Microsoft and non-Microsoft guidelines.

 

There are several standards exists in the programming industry. None of them are wrong or bad and you may follow any of them. What is more important is, selecting one standard approach and ensuring that everyone is following it.

 

5.      How to follow the standards across the team

If you have a team of different skills and tastes, you are going to have a tough time convincing everyone to follow the same standards. The best approach is to have a team meeting and developing your own standards document. You may use this document as a template to prepare your own document.

 

Distribute a copy of this document (or your own coding standard document) well ahead of the coding standards meeting. All members should come to the meeting prepared to discuss pros and cons of the various points in the document. Make sure you have a manager present in the meeting to resolve conflicts.

 

Discuss all points in the document. Everyone may have a different opinion about each point, but at the end of the discussion, all members must agree upon the standard you are going to follow. Prepare a new standards document with appropriate changes based on the suggestions from all of the team members. Print copies of it and post it in all workstations.

 

After you start the development, you must schedule code review meetings to ensure that everyone is following the rules. 3 types of code reviews are recommended:

 

1.      Peer review – another team member review the code to ensure that the code follows the coding standards and meets requirements. This level of review can include some unit testing also. Every file in the project must go through this process.

2.      Architect review – the architect of the team must review the core modules of the project to ensure that they adhere to the design and there is no “big” mistakes that can affect the project in the long run.

 

Group review – randomly select one or more files and conduct a group review once in a week. Distribute a printed copy of the files to all team members 30 minutes before the meeting. Let them read and come up with points for discussion. In the group review meeting, use a projector to display the file content in the screen. Go through every sections of the code and let every member give their suggestions on how could that piece of code can be written in a better way. (Don’t forget to appreciate the developer for the good work and also make sure he does not get offended by the “group attack”!)

 

6.      Naming Conventions and Standards

 

Note :

The terms Pascal Casing and Camel Casing are used throughout this document.

Pascal Casing - First character of all words are Upper Case and other characters are lower case.

Example: BackColor

Camel Casing – First character of all words, except the first word are Upper Case and other characters are lower case.

Example: backColor

 

1.      Use Pascal casing for Class names

 

public class HelloWorld

{

           

}

 

2.      Use Pascal casing for Method names

 

void SayHello(string name)

{

           

}

 

 

3.      Use Camel casing for variables and method parameters

 

int totalCount = 0;

void SayHello(string name)

{

            string fullMessage = “Hello ” + name;

           

}

 

4.      Use the prefix “I” with Camel Casing for interfaces ( Example: IEntity )

 

5.      Do not use Hungarian notation to name variables.

 

In earlier days most of the programmers liked it – having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:

 

string m_sName;

int nAge;

 

However, in .NET coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.

 

Some programmers still prefer to use the prefix m_ to represent member variables, since there is no other easy way to identify a member variable.

 

 

6.      Use Meaningful, descriptive words to name variables. Do not use abbreviations.

 

Good:

 

string address

int salary

 

Not Good:

 

string nam

string addr

int sal

 

7.      Do not use single character variable names like i, n, s etc. Use names like index, temp

 

One exception in this case would be variables used for iterations in loops:

 

for ( int i = 0; i < count; i++ )

{

           

}

 

If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

 

8.      Do not use underscores (_) for local variable names.

 

9.      All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.

 

10.  Do not use variable names that resemble keywords.

 

11.  Prefix boolean variables, properties and methods with “is” or similar prefixes.

 

Ex: private bool _isFinished

 

12.  Namespace names should follow the standard pattern

 

<company name>.<product name>.<top level module>.<bottoma level module>

 

13.  Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.

 

There are 2 different approaches recommended here.

 

a.      Use a common prefix ( ui_ ) for all UI elements. This will help you group all of the UI elements together and easy to access all of them from the intellisense.

 

b.      Use appropriate prefix for each of the ui element. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using.

 

7.      Indentation and Spacing

 

1.      Use TAB for indentation. Do not use SPACES.  Define the Tab size as 4.

2.      Comments should be in the same level as the code (use the same level of indentation).

 

            Good:

 

// Format a message and display

 

string fullMessage = “Hello ” + name;

DateTime currentTime = DateTime.Now;

string message = fullMessage + “, the time is : ” + currentTime.ToShortTimeString();

MessageBox.Show ( message );

 

            Not Good:

 

// Format a message and display

string fullMessage = “Hello ” + name;

DateTime currentTime = DateTime.Now;

string message = fullMessage + “, the time is : ” + currentTime.ToShortTimeString();

MessageBox.Show ( message );

 

3.      Curly braces ( {} ) should be in the same level as the code outside the braces.

           

4.      Use one blank line to separate logical groups of code.

 

Good:

            bool SayHello ( string name )

            {

                        string fullMessage = “Hello ” + name;

                        DateTime currentTime = DateTime.Now;

 

string message = fullMessage + “, the time is : ” + currentTime.ToShortTimeString();

 

                        MessageBox.Show ( message );

 

                        if ( … )

                        {

                                    // Do something

                                    // …

 

                                    return false;

                        }

 

                        return true;

            }

 

Not Good:

 

            bool SayHello (string name)

            {

                        string fullMessage = “Hello ” + name;

                        DateTime currentTime = DateTime.Now;

                        string message = fullMessage + “, the time is : ” + currentTime.ToShortTimeString();

                        MessageBox.Show ( message );

                        if ( … )

                        {

                                    // Do something

                                    // …

                                    return false;

                        }

                        return true;

            }

 

5.      There should be one and only one single blank line between each method inside the class.

6.      The curly braces should be on a separate line and not in the same line as if, for etc.

 

Good:

               if ( … ) 

               {

                           // Do something

               }

Not Good:

 

               if ( … )  {

                           // Do something

               }

 

7.      Use a single space before and after each operator and brackets.

 

Good:

               if ( showResult == true )

               {

                           for ( int i = 0; i < 10; i++ )

                           {

                                       //

                           }

               }

Not Good:

 

               if(showResult==true)

               {

                           for(int      i= 0;i<10;i++)

                           {

                                       //

                           }

               }

 

8.      Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.

 

             

 

Keep private member variables, properties and methods in the top of the file and public members in the bottom

 

8.      Good Programming Practices

 

1.      Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.

 

2.      Method name should tell what it does. Do not use mis-leading names. If the method name is obvious, there is no need of documentation explaining what the method does.

 

Good:

            void SavePhoneNumber ( string phoneNumber )

            {

                        // Save the phone number.

            }

 

Not Good:

 

            // This method will save the phone number.

            void SaveDetails ( string phoneNumber )

            {

                        // Save the phone number.

            }

 

3.      A method should do only ‘one job’. Do not combine more than one job in a single method, even if those jobs are very small.

 

Good:

            // Save the address.

            SaveAddress (  address );

           

            // Send an email to the supervisor to inform that the address is updated.

            SendEmail ( address, email );             

           

            void SaveAddress ( string address )

            {

                        // Save the address.

                        // …

            }

           

            void SendEmail ( string address, string email )

            {

                        // Send an email to inform the supervisor that the address is changed.

                        // …

            }

 

Not Good:

 

            // Save address and send an email to the supervisor to inform that

// the address is updated.

            SaveAddress ( address, email );

 

            void SaveAddress ( string address, string email )

            {

                        // Job 1.

                        // Save the address.

                        // …

 

                        // Job 2.

                        // Send an email to inform the supervisor that the address is changed.

                        // …

            }

 

4.      Use the c# or VB.NET specific types (aliases), rather than the types defined in System namespace.

 

            int age;   (not Int16)

            string name;  (not String)

            object contactInfo; (not Object)

 

           

Some developers prefer to use types in Common Type System than language specific aliases.

 

5.      Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never assume that if one is not matching then the only possibility is the other value.

 

Good:

 

If ( memberType == eMemberTypes.Registered )

{

            // Registered user… do something…

}

else if ( memberType == eMemberTypes.Guest )

{

            // Guest user… do something…

}

else

{

                        // Un expected user type. Throw an exception

                        throw new Exception (“Un expected value “ + memberType.ToString() + “’.”)

 

                        // If we introduce a new user type in future, we can easily find

// the problem here.

}

 

Not Good:

 

If ( memberType == eMemberTypes.Registered )

{

                        // Registered user… do something…

}

else

{

                        // Guest user… do something…

 

// If we introduce another user type in future, this code will

// fail and will not be noticed.

}

 

6.      Do not hardcode numbers. Use constants instead. Declare constant in the top of the file and use it in your code.

 

However, using constants are also not recommended. You should use the constants in the config file or database so that you can change it later. Declare them as constants only if you are sure this value will never need to be changed.

 

7.      Do not hardcode strings. Use resource files.

 

8.      Convert strings to lowercase or upper case before comparing. This will ensure the string will match even if the string being compared has a different case.

 

if ( name.ToLower() == “john” )

{

                //…

}

 

9.      Use String.Empty instead of “”

 

Good:

 

If ( name == String.Empty )

{

            // do something

}

 

Not Good:

 

If ( name == “” )

{

            // do something

}

 

10.  Avoid using member variables. Declare local variables wherever necessary and pass it to other methods instead of sharing a member variable between methods. If you share a member variable between methods, it will be difficult to track which method changed the value and when.

 

11.  Use enum wherever required. Do not use numbers or strings to indicate discrete values.

 

Good:

            enum MailType

            {

                        Html,

                        PlainText,

                        Attachment

            }

 

            void SendMail (string message, MailType mailType)

            {

                        switch ( mailType )

                        {

                                    case MailType.Html:

                                                // Do something

                                                break;

                                    case MailType.PlainText:

                                                // Do something

                                                break;

                                    case MailType.Attachment:

                                                // Do something

                                                break;

                                    default:

                                                // Do something

                                                break;

                        }

            }

 

 

Not Good:

 

            void SendMail (string message, string mailType)

            {

                        switch ( mailType )

                        {

                                    case “Html”:

                                                // Do something

                                                break;

                                    case “PlainText”:

                                                // Do something

                                                break;

                                    case “Attachment”:

                                                // Do something

                                                break;

                                    default:

                                                // Do something

                                                break;

                        }

            }

12.  Do not make the member variables public or protected. Keep them private and expose public/protected Properties.

 

13.  The event handler should not contain the code to perform the required action. Rather call another method from the event handler.

 

14.  Do not programmatically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler.

 

15.  Never hardcode a path or drive name in code. Get the application path programmatically and use relative path.

 

16.  Never assume that your code will run from drive “C:”. You may never know, some users may run it from network or from a “Z:”.

 

17.  In the application start up, do some kind of “self check” and ensure all required files and dependancies are available in the expected locations. Check for database connection in start up, if required. Give a friendly message to the user in case of any problems.

 

18.  If the required configuration file is not found, application should be able to create one with default values.

 

19.  If a wrong value found in the configuration file, application should throw an error or give a message and also should tell the user what are the correct values.

 

20.  Error messages should help the user to solve the problem. Never give error messages like “Error in Application”, “There is an error” etc. Instead give specific messages like “Failed to update database. Please make sure the login id and password are correct.”

 

21.  When displaying error messages, in addition to telling what is wrong, the message should also tell what should the user do to solve the problem. Instead of message like “Failed to update database.”, suggest what should the user do: “Failed to update database. Please make sure the login id and password are correct.”

 

22.  Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.

 

23.  Do not have more than one class in a single file.

 

24.  Have your own templates for each of the file types in Visual Studio. You can include your company name, copy right information etc in the template. You can view or edit the Visual Studio file templates in the folder C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ItemTemplatesCache\CSharp\1033. (This folder has the templates for C#, but you can easily find the corresponding folders or any other language)

 

25.  Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes.

 

26.  Avoid public methods and properties, unless they really need to be accessed from outside the class. Use “internal” if they are accessed only within the same assembly.

 

27.  Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure.

 

28.  If you have a method returning a collection, return an empty collection instead of null, if you have no data to return. For example, if you have a method returning an ArrayList, always return a valid ArrayList. If you have no items to return, then return a valid ArrayList with 0 items. This will make it easy for the calling application to just check for the “count” rather than doing an additional check for “null”.

 

29.  Use the AssemblyInfo file to fill information like version number, description, company name, copyright notice etc.

 

30.  Logically organize all your files within appropriate folders. Use 2 level folder hierarchies. You can have up to 10 folders in the root folder and each folder can have up to 5 sub folders. If you have too many folders than cannot be accommodated with the above mentioned 2 level hierarchy, you may need re factoring into multiple assemblies.

 

31.  Make sure you have a good logging class which can be configured to log errors, warning or traces. If you configure to log errors, it should only log errors. But if you configure to log traces, it should record all (errors, warnings and trace). Your log class should be written such a way that in future you can change it easily to log to Windows Event Log, SQL Server, or Email to administrator or to a File etc without any change in any other part of the application. Use the log class extensively throughout the code to record errors, warning and even trace messages that can help you trouble shoot a problem.

 

32.  If you are opening database connections, sockets, file stream etc, always close them in the finally block. This will ensure that even if an exception occurs after opening the connection, it will be safely closed in the finally block.

 

33.  Declare variables as close as possible to where it is first used. Use one variable declaration per line.

 

34.  Use StringBuilder class instead of String when you have to manipulate string objects in a loop. The String object works in weird way in .NET. Each time you append a string, it is actually discarding the old string object and recreating a new object, which is a relatively expensive operations.

 

Consider the following example:

 

public string ComposeMessage (string[] lines)

{

   string message = String.Empty;

 

   for (int i = 0; i < lines.Length; i++)

   {

      message += lines [i];

   }

 

   return message;

}

 

In the above example, it may look like we are just appending to the string object ‘message’. But what is happening in reality is, the string object is discarded in each iteration and recreated and appending the line to it.

 

If your loop has several iterations, then it is a good idea to use StringBuilder class instead of String object.

 

See the example where the String object is replaced with StringBuilder.

 

public string ComposeMessage (string[] lines)

{

    StringBuilder message = new StringBuilder();

 

    for (int i = 0; i < lines.Length; i++)

    {

       message.Append( lines[i] );

    }

 

    return message.ToString();

}

 

9.      Architecture

 

1.      Always use multi layer (N-Tier) architecture.

 

2.      Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily.

 

3.      Use try-catch in your data layer to catch all database exceptions. This exception handler should record all exceptions from the database. The details recorded should include the name of the command being executed, stored proc name, parameters, connection string used etc. After recording the exception, it could be re thrown so that another layer in the application can catch it and take appropriate action.

 

Separate your application into multiple assemblies. Group all independent utility classes into a separate class library. All your database related files can be in another class library.

 

10. ASP.NET

 

1.      Do not use session variables throughout the code. Use session variables only within the classes and expose methods to access the value stored in the session variables. A class can access the session using System.Web.HttpCOntext.Current.Session

 

2.      Do not store large objects in session. Storing large objects in session may consume lot of server memory depending on the number of users.

 

3.      Always use style sheet to control the look and feel of the pages. Never specify font name and font size in any of the pages. Use appropriate style class. This will help you to change the UI of your application easily in future. Also, if you like to support customizing the UI for each customer, it is just a matter of developing another style sheet for them

 

11. Comments

 

Good and meaningful comments make code more maintainable. However,

 

1.      Do not write comments for every line of code and every variable declared.

 

2.      Use // or /// for comments. Avoid using /* … */

 

3.      Write comments wherever required. But good readable code will require very less comments. If all variables and method names are meaningful, that would make the code very readable and will not need many comments.

 

4.      Do not write comments if the code is easily understandable without comment. The drawback of having lot of comments is, if you change the code and forget to change the comment, it will lead to more confusion.

 

5.      Fewer lines of comments will make the code more elegant. But if the code is not clean/readable and there are less comments, that is worse.

 

6.      If you have to use some complex or weird logic for any reason, document it very well with sufficient comments.

 

7.      If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.

 

8.      The bottom line is, write clean, readable code such a way that it doesn’t need any comments to understand.

 

Perform spelling check on comments and also make sure proper grammar and punctuation is used

 

12. Exception Handling

 

1.      Never do a ‘catch exception and do nothing’. If you hide an exception, you will never know if the exception happened or not. Lot of developers uses this handy method to ignore non significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed.

 

2.      In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc.

 

3.      Always catch only the specific exception, not generic exception.

 

Good:

 

 

   void ReadFromFile ( string fileName )

   {

               try

               {

                           // read from file.

               }

               catch (FileIOException ex)

               {

                           // log error.

                           //  re-throw exception depending on your case.

                           throw;

               }

   }

 

Not Good:

 

 

void ReadFromFile ( string fileName )

{

   try

   {

      // read from file.

   }

   catch (Exception ex)    

   {

      // Catching general exception is bad… we will never know whether

      // it was a file error or some other error.                 

      // Here you are hiding an exception.

      // In this case no one will ever know that an exception happened.

 

      return “”;                 

   }

}

           

4.      No need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle. You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an ‘unexpected general error’, this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to ‘ignore and proceed’.

 

5.      When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.

 

Good:

 

catch

{

            // do whatever you want to handle the exception

 

            throw; 

}

 

Not Good:

 

catch (Exception ex)

{

            // do whatever you want to handle the exception

 

            throw ex;

}

 

6.      Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exception may occur and it cannot be prevented by any other means. For example, if you want to insert a record if it does not already exists in database, you should try to select record using the key. Some developers try to insert a record without checking if it already exists. If an exception occurs, they will assume that the record already exists. This is strictly not allowed. You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error.

 

7.      Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user.

 

Write your own custom exception classes if required in your application. Do not derive your custom exceptions from the base class SystemException. Instead, inherit from ApplicationException

 

13.  Choosing between Convert and Type Parse

 

A brief story about using TryParse instead of Convert to make life easy

Consider that you are assigned to a project to create a very cool application which captures the name, age and date of birth of the user and saves all the data to the database. Yay!

So you go ahead & design a cool form, complete with two text boxes to capture the name & age and add a date picker control to select the date of birth. Sweet!

Now comes the tough part – saving the values to the database. The DBA’s really out-did themselves on this one and designed a table which could hold all this information like so:

         CREATE TABLE Users
         (Name VARCHAR(50), Age INT(3), DateOfBirth DATETIME)

Oh, the wicked people! You quake in fear, since your controls expose only a text property and return the values a text. Surely the DBA’s could have designed with this in mind. But they work in a different world that you don’t quite understand (or control) & so grudgingly you look at what you could do to convert your string values to the types the table expects.

After burning the midnight oil, you come up with a solution like so:

private void saveUser()
{
    try{
        string name = txtName.Text;
        int age = Convert.ToInt32(txtAge.Text);
        DateTime dateOfBirth = Convert.ToDateTime(txtDateTime.Text);

        // Code to save to the database
    }
    catch(System.Exception ex){
        // Code to do something with the error
    }
}

Nice, so you managed to convert the values to the types needed by the database and you threw in the try-catch block to handle anything going wrong in your code. You think you are almost done so you call in the new fresh-out-of-college-dude who joined your team last week to show off your master-peice. One look & he has the nerve to mention Validation controls on the client-side so that you would save the server round-trip if the data is invalid.

You throw him a few dagger looks and put in some Validator controls so that the data can be validated on the client. You can hear the drums beating, the bugles sounding as you push out your code to your manager for some review & feedback while you head out for a celebration. Surely, he would be impressed.

The next day, you inbox has a single line cryptic mail from your manager: “Doesn’t work, JS disabled.” Now you have two headaches – the hangover and the mail. You need to act on them, fast!

So you make your way out to your geek friend who happens to be good at fixing code issues. “Dude” you say, “could you please look into this code, I think I didnot handle the OnServerValidate event of the Validation controls”. While he peers at you code, you take a walk to find something for that hangover.

By the time you are back, your geek god has changed your code like so:

private void saveUser()
{
    try{
       string name; int age; DateTime dateOfBirth;
        if(!String.IsNullOrEmpty(txtName.Text) && int.TryParse(txtAge.Text, out age) 
            && DateTime.TryParse(txtDateOfBirth.Text, out dateOfBirth))
        {
            // Code to save to the database
        }
        else
        {
            // Show validation error
        }
    }
    catch(System.Exception ex){
        // Code to do something with the error
    }
}
 

You groan out load! You had asked him to handle the OnServerValidate event for each control & he just wrote a few lines of code which you donot understand, you can feel your headache starting up again. You want to ask him about it, but have a reputation to protect. Besides you could always look it up on Google to know what it is & if there is any performance benefit in doing this.

 

14.  Using default keyword in C#

 

The keyword default plays several and important roles in the C# language, therefore, I will enumerate some cases where the default keyword is used.

 

Introduction:

The keyword default plays several and important roles in the C# language, therefore, I will enumerate some cases where the default keyword is used.

First use case:

The keyword default is used within the switch … case bloc, to illustrate how, I propose this example:

Color x = new Color();

switch (x)

{

case Color.Red :

    MessageBox.Show(“This is not a primary color”);

    //TO DO: Perform some task

    break;

case Color.Green :

    MessageBox.Show(“This is not a primary color”);

    //TO DO: Perform some task

    break;

case Color.Blue:

    MessageBox.Show(“This is not a primary color”);

    //TO DO: Perform some task

    break;

default:

    MessageBox.Show(“This is not a primary color”);

}

As you see the default play the role of somewhat the exception catcher or the else keyword within a given condition block, but you tell me OK I know this. Have you any thing new where using the keyword default is necessary. YES of course, here are two other use cases.

Second use case:

Imagine if it is necessary to reset the value of a given generic type, you can employ this code for example:

using System;

using System.Collections.Generic;

using System.Text;

 

public class myType<T>

    {

        public myType() { }

        private T _Attribute1;

        private T _Attribute2;

        public T Attribute1

        {

            get { return _Attribute1; }

            set { _Attribute1 = value; }

        }

        public T Attribute2

        {

            get { return _Attribute1; }

            set { _Attribute2 = value; }

        }

        public T method()

        {

            //TO DO: implement some tasks here else

            return null;

        }

        //To reset the type T defined by the class user

        public void ResetGenericType()

        {

            Attribute1 = default(T);

            Attribute2 = default(T);

        }

}

Third use case

Suppose now that you want to know whether a generic type is of reference like a String or of value like an Int.

using System;

using System.Collections.Generic;

using System.Text;

 

public class myType<T>

{

    public myType()

    {

        if (default(T) == null)

            Console.WriteLine(“T is a type of reference.”);

        else

            Console.WriteLine(“T is a type of value.”);

       

    }

    //TO DO: Implement the rest of the class members

}

The keyword default is certainly used within other contexts but there is a thing that one should keep in mind is that in fact every keyword within the C# syntax has to be appreciate

 

 

 

 

15.  The second pillar of Object Oriented Programming – Inheritance

 

In this part of the object-oriented programming series I will introduce the second pillar of object oriented programming (inheritance); you will see how to use inheritance to create classes based on existing classes.

 

Introduction:

 

Inheritance gives you the ability of building a new classes based on existing class. So that it allows you to extend a base class by enabling a new class to inherit its characteristics and behavior.

 

The greatest thing with inheritance is that it gives you the ability of code reuse, so if you have a class which has some functionality, characteristics and behavior and you want to create another class which will has the same functionality but with some new characteristics and behaviors so instead of create a brand new class that have the same code you done before, all you need to is to create the new class and add to it only the new characteristics and behavior and inherit the other from the old class.

 

The base class:

 

The base class is a normal class that has characteristics (variables) and behaviors (methods) that are common for all subclasses.

 

Example:

 

public class Car

{

 

    string model;

    int currentSpeed;

    int maxSpeed;

 

    public Car()

    { }

 

    public Car(string model, int currentSpeed, int maxSpeed)

    {

 

        this.model = model;

        this.currentSpeed = currentSpeed;

        this.maxSpeed = maxSpeed;

    }

 

    public string Model

    {

        get { return model; }

        set { model = value; }

    }

 

    public int CurrentSpeed

    {

        get { return currentSpeed; }

        set { currentSpeed = value; }

    }

 

    public int MaxSpeed

    {

        get { return maxSpeed; }

        set { maxSpeed = value; }

    }

 

}

As you can see the car class has characteristics that any car of each type can have so it have the general variables that are common for any car.

 

The Subclass (derived class):

 

The subclass is a class that inherit its core functionality from a base class then it add its own functionality

 

Example:

 

public class BMW : Car

{

}

We left our BMW class with out adding any variables or methods so the BMW class is the same as the Car class so if you tried to use it you will see that it have all characteristics of the Car class.

 

Example:

 

BMW bmw1 = new BMW();

bmw1.Model = “X5″;

bmw1.CurrentSpeed = 0;

bmw1.MaxSpeed = 230;

 

So let us see how we can extend our Car type by adding some functionality to its childe BMW.

 

Creating the subclass:

 

As I said all you need to do with your subclass is to add the new functionality to it and it will inherit all the common functionality from the base class.

 

Example:

 

public class BMW : Car

{

    bool isFullOption;

    bool hasDVD;

 

    public BMW()

    { }

 

    public BMW(string model, int currentSpeed, int maxSpeed, bool isFullOption, bool hasDVD)

    {

        //using the BMW class variables

        this.isFullOption = isFullOption;

        this.hasDVD = hasDVD;

 

        //using the CAR class properties

        Model = model;

        CurrentSpeed = currentSpeed;

        MaxSpeed = maxSpeed;

    }

}

As you saw we create the BMW subclass and add two other variables to it (isFullOption, hasDVD) also we created a custom constructor and use it to assign the value of the BMW class variables and the properties inherited from the base class Car.

 

Using the base class constructors:

 

Instead of creating a custom constructor in the subclass that have the same code in the base class constructor, we can create a constructor that call the base class constructor and use the subclass constructor to assign values to the variables that belongs to the subclass.

 

Example:

 

public class BMW : Car

{

    bool isFullOption;

    bool hasDVD;

 

    public BMW()

    { }

 

    public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

        : base(model, currentSpeed, maxSpeed)

    {

        //using the BMW class variables

        this.isFullOption = isFullOption;

        this.hasDVD = hasDVD;

    }

}

 

We here create a custom constructor in the subclass and we will use it to receive values from the object user like (isFullOption, hasDVD, model, currentSpeed, and maxSpeed) and then we assigned the (isFullOption, hasDVD) values in the subclass constructor and pass the (model, currentSpeed, and maxSpeed) values to the base class constructor.

 

BMW bmw1 = new BMW(true, true, “X5″, 100, 230);

the first two parameters will be used by the subclass constructor and the last three will be use by the base class constructor.

 

Allowing the subclass to see the base class variables (the protected keyword):

 

as you saw previously all the base class members are private so the subclass can not see it and can only deal with it by its properties, so if we want the subclasses to see the variables of the base class we have to redefine these variables as protected.

 

public class Car

{

    protected string model;

    protected int currentSpeed;

    protected int maxSpeed;

 

    public Car()

    { }

 

    public Car(string model, int currentSpeed, int maxSpeed)

    {

        this.model = model;

        this.currentSpeed = currentSpeed;

        this.maxSpeed = maxSpeed;

    }

}

The protected keyword means that the base class variables are accessible only by the subclasses and private to all other classes.

 

By using protected members we created a level of trust between the base and derived classes.

 

We now can use the Car class variables directly in the BMW subclass with out using any properties.

 

public class BMW : Car

{

    bool isFullOption;

    bool hasDVD;

 

    public BMW()

    {

        //we now can use the member of the base class

        currentSpeed = 0;

        maxSpeed = 230;

    }

 

    public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

        : base(model, currentSpeed, maxSpeed)

    {

        //using the BMW class variables

        this.isFullOption = isFullOption;

        this.hasDVD = hasDVD;

    }

}

 

The sealed classes:

 

We can create classes that can not be inherited by using sealed keyword in the class definition, so if we tried to inherit from a sealed class we will have a compile time error.

 

Example:

 

We can define our BMW class as sealed class

 

public sealed class BMW : Car

{

    bool isFullOption;

    bool hasDVD;

 

    public BMW()

    {

        //we now can use the member of the base class

        currentSpeed = 0;

        maxSpeed = 230;

    }

 

    public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

        : base(model, currentSpeed, maxSpeed)

    {

        //using the BMW class variables

        this.isFullOption = isFullOption;

        this.hasDVD = hasDVD;

    }

}

 

If we tried to inherit from BMW class we will have a compile time error.

 

//Compile time error

public class MiniCoper : BMW

{

}

Note: C# dose not allow multiple base classes, so any class can inherit only from one base class

 

16.  Automatic Validation of Objects

 

When we deal with objects, we are forced to do validations of values set to its properties (or public members) before doing any data layer activities. How better would it be if there is an Automatic validation mechanism in place for my objects?

 

Introduction

 

Any project development is inevitable from client side validations.  Especially when we deal with objects, we are forced to do validations of values set to its properties (or public members) before doing any data layer activities.

 

Problem

 

Couple of projects I recently worked has a lot of validations to do for the business objects, that too very frequent. We forced to do the validation logic whenever there is a value change happens. Sometimes we forget and it ends up with an SqlException. 

 

That made me to think, how better it would be if there is an Automatic validation mechanism in place for my objects!!!  It should be like just setting the conditions in my class and the objects have to be taken care off.  Attributes gave me a hand.

 

Concept

 

ValidationAttribute is the class which is used to define our business classes for validations. Each public member and property can be set for its own validation rule.

 

ValidationAttribute class has two properties; Condition and ErrorMessage.  Condition is an enumerated type that describes the type of validation you require and ErrorMessage holds the message that needs to be shown to the user if in case the validation is failed.

 

Our business classes will be decorated with a ValidationAttribute tag along with the two properties; message and condition.  On a different note, I would like to add; this is meant for only web applications with 2.0 framework. As a disclaimer, this code is just halfway through and I am yet to include as many rules as I could think of.

 

Class diagram

 

 

         

  

 

Example - A quick start

 

Take an example of a Customer class that has two properties Name and EmployeeID.  The conditions are;

1.      Customer name is mandatory. Hence check for null and empty

2.      EmployeeID should accept only integer values.

 

Step 1: Our first step is to make the Customer class inherited from Attributable which is an abstract class.  Having said this, our business class is all set for its automatic validation.

 

Step 2:  Set Condition and required Error message.

Add attributes for the properties (or public members) as shown below.

 

public class Customer:Attributable

{

   

    private string _Name;

    [ValidationAttribute("Name cannot be empty", ValidationAttribute.Conditions.IsNotEmpty)]

    [ValidationAttribute("Name cannot be null", ValidationAttribute.Conditions.IsNotNull)]

    public string Name

    {

        get { return _Name; }

        set { _Name = value; }

    }

           

 

    [ValidationAttribute("Employee Id has to be integer",

ValidationAttribute.Conditions.IsNumeric)]

    public string EmployeeId;

}

 

Notice that you are allowed to add as many numbers of rules as needed.

 

That’s it. You are all set to use your object in your presentation layer.

 

Step 3:  And from my ASPX page?

 

  Customer c = new Customer();

        c.EmployeeId = “ABC”;                      // this should throw me a failure

        c.Name = “dfgdsg”;                              // this is valid. Try changing this to empty

    c.IsValid(c);

 

As your Customer class is inherited from Attributable, you would find a method IsValid() available in your Customer object.

 

c.IsValid(c); will tell you whether your object is valid or not, according to the conditions you set.

 

You are free to extend your own customized rules as you wish. You can very well extend the enumerated type and add your logic in the ProcessFields method of Attributable class.

           

You can iterate through each message from the Exceptions property.

 

  if (c.Exceptions != null)

        {

            foreach (AttributeException arEx in c.Exceptions)

            {

                Response.Write(arEx.Message + “<BR>”);

            }

        }

 

Notice that c.Exceptions will be always null until and unless the object is failed in at least one rule you set in the class level.

 

 

17.  Avoid casting to improve Code performance (Generics)

 

Casting is a big problem when it comes to the code performance. This article talks about how we can take advantage of generics in C# 2.0 to avoid casting.

 

Introduction:

Question to C#:

Hello. C# I’m Developer, I want to know why you advice me to use Generic instead of Casting Objects and what is the meaning of a Generic?

Answer: One of the important issues in the code development is the [Coding Quality], because your Coding Quality separates you from other developers. So let us see what the basics of the coding quality are:

  • Application Performance.
  • Reducing of Casting Object-based data structures.
  • Reuse data processing Algorithms (code).

Question to C#!

You say “reduce Casting” of Objects. So what about casting Objects when using Collections (Boxing in general)?

Answer: Ooh…I would like to see the following example which explains the advantage of using generics and how it is more efficient than using non-generic code and how does this matter in coding quality.

Getting Started

What is a Generic: Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR).

·         Generics introduce you to the .NET Framework the concept of type parameters, which makes it possible to design classes, and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

·         Generics allow you to define type-safe data structures, without committing to actual data types.

Let us see Simple Example about Using and benefits of Generics:

Let us see the difference between a non-generic class and a generic class with your eyes only:

In Figure 1:

Tip!! :
ArrayList is a highly convenient collection class that can be used without modification to store any reference or value type.

Disadvantage of Casting (Boxing)

·         Any reference or value type that is added to an ArrayList is implicitly upcast to the Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. Both the casting and the boxing and un-boxing operations degrade the code performance; the effect of boxing and un-boxing can be quite significant in scenarios where you must iterate over large collections of data.

·         The other limitation is lack of compile-time type checking; since an ArrayList casts everything to Object.

So if you think about generalizing you collection class, what you will do in C# 1.1?

You could avoid the dangers of generalized code in the .NET Framework base class library collection classes by writing your own type specific collections. Of course, since such a class is not reusable for more than one data type, you lose the benefits of generalization, and you have to rewrite the class for each type that will be stored.

In Figure 2:

Let us see what is happen in C# 2.0 to solve these problems:

What ArrayList and other similar classes really need is:

  • A way for client code to specify, on a per-instance basis, the particular data type that they intend to use. That would eliminate the need for the upcast to T:System.Object and would also make it possible for the compiler to do type checking. In other words, ArrayList needs a type parameter. That is precisely what generics provide. In the generic List<T> collection, in the N:System.Collections.Generic namespace.

        static void GenericTest()

        {

            // The .NET Framework 2.0 way to create a list

            List<int> list1 = new List<int>();

 

            // No boxing, no casting:

            list1.Add(3);

 

            // Compile-time error:

            // list1.Add(“It is raining in Redmond.”);

        }

For example using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations.

    // Declare the generic class

    public class GenericList<T>

    {

        void Add(T input)

        {

 

        }

    }

    class TestGenericList

    {

        private class ExampleClass

        {

 

        }

 

        static void Main()

        {

            // Declare a list of type int

            GenericList<int> list1 = new GenericList<int>();

 

            // Declare a list of type string

            GenericList<string> list2 = new GenericList<string>();

 

            // Declare a list of type ExampleClass

            GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();

        }

    }

Get Started:

The boxing and Un-Boxing:

What is boxing and Un-Boxing in C#?

Boxing a value type packages it inside an instance of the Object reference type.

Boxing Example:

(a) most used Boxing:

            int i = 10;

            object Obj = i;

(b) It also possible to perform the boxing explicitly as in the following:

            int i = 10;

            // Casting the value type [ int ] to Object Reference type boxing

            object Obj = (object)i;

How Boxing performed?

        

1- Declare a value-type variable [i] as int

int i = 10;

2- then applies the boxing operation on the variable [i]

object Obj = i;

3- The result of this statement is creating an object reference Obj on the stack.

4- This Object references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable [i] which equal 10.

What are the Benefits of this concept?

To allow the value type to be stored on the garbage collected heap.

Un-Boxing Example:

            Obj = 10;

            // Unboxing extracts the value type from the object Ref Type

            i = (int)Obj;

! Disadvantage of Boxing

Boxing and un-Boxing are expensive processes because of the following:

1.      When a value type is boxed, an entirely new instance object must be allocated and constructed.

2.      The cast required for un-boxing is also expensive computationally.

Generic is better than using Object based Solution to reducing Object casting Let us see how?

With using Boxing:

        readonly int m_Size;

        int m_StackPointer = 0;

        object[] m_Items;

 

 

        public void Push(object item)

        {

            if (m_StackPointer >= m_Size)

                throw new StackOverflowException();

            m_Items[m_StackPointer] = item;

            m_StackPointer++;

        }

With using Generic:

        readonly int m_Size;

        int m_StackPointer = 0;

        T[] m_Items;

        public void Push(T item)

        {

            if (m_StackPointer >= m_Size)

                throw new StackOverflowException();

            m_Items[m_StackPointer] = item;

            m_StackPointer++;

        }

 

18.  Introduction to the Resources .resx and resource files

 

In some cases an application needs some external resources to perform specified tasks. And I mean by external resources, those none executables data logically deployed with a given application.

Introduction

In some cases an application needs some external resources to perform specified tasks. And I mean by external resources, those none executables data logically deployed with a given application. The final purpose by doing so is to prevent recompiling the given application for each time one or more elements are supposed to be necessarily changed according to some environmental exceptions, contexts or external conditions. You tell me OK understood, but the same task or mission is covered by the configuration files. I can say resources files and configuration files exist for the same goal is to prevent recompiling applications, the nature and the mission covered by each kind of file differs in practice, however.

Configuration files “*.config” vs. resource files “*.resource”

The configuration files “*.exe.config” have as a mission giving the developer the ability to control and/ or modify settings inside the application logical environment, among the missions covered by the “*.exe.config” files:

·         Define witch assemblies could be consumed by the application core.

·         Specify witch runtime version processes.

·         Define application settings such as connection strings and other settings.

·         Register remote objects

·         Define some configuration sections especially used to certain properties assignments

So, each of those elements belongs logically to the internal application environment. In the other hand, the resources files “*.resource” are designed to provide information contained in a tierce parts those belong to the external logical application environment such as bitmaps images, text files, icons and so forth.

You can save those files types most used as a part of your resources:

Open file as

Save file as

Description

32-bit .res

.rc or 32-bit .res

The famous (*.rc) files used in VC++6.0 if you have some backgrounds according to C++ programming, the .rc files are added automatically within a VC++ application as resources files

.bmp or .dib

.bmp or .dib

Bitmaps image files and device independent bitmap image files

.ico

.ico

Icon files

.cur

.cur

A type of specified Icon files used to design cursors

.htm, .html

.htm or .html

The html files

Resx files vs. resources files

The question now, is why there are two different formats, I mean, resx and resource format or extension to represent the same kind of files, namely, the resource files. And why, for each time, that I use the resx format file, I encounter problems to embed it in a run time executable environment.

Well, for the first question I can say that there is a difference in nature between a (*.resx) and (*.resource) file.

Resx file:

The first one is a kind of structured XML format file, such as the XSD files those used to stock information about datasets elements and structures. It is, normally, used for structuring and organizing data in a given order. Within a resx file you can add, modify or delete given information about resources through the code or even by using a simple text editor if you have a strong background concerning the XML files handling and, of Corse, good knowledge according to the resx files elements and structure. It is possible to use a text file instead of the resx file for the same purpose, but it should be better to use the last one. In addition, it is not a good idea to store sensitive information such as passwords, visa cards data or personal data in a resx file as they can be easily seen by everyone who has access to it.

And this is a resx file example in which I stocked my name and my country in string variables; I give this example to see how such file can look like:

<?xml version=1.0 encoding=utf-8?>

<root>

  <!–

    Microsoft ResX Schema Version 2.0

   

    The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types.

    Example:
   

    … ado.net/XML headers & schema …

    <resheader name=”resmimetype”>text/microsoft-resx</resheader>

    <resheader name=”version”>2.0</resheader>

    <resheader name=”reader”>System.Resources.ResXResourceReader, System.Windows.Forms, …</resheader>

    <resheader name=”writer”>System.Resources.ResXResourceWriter, System.Windows.Forms, …</resheader>

    <data name=”Name1″><value>this is my long string</value><comment>this is a comment</comment></data>

    <data name=”Color1″ type=”System.Drawing.Color, System.Drawing”>Blue</data>

    <data name=”Bitmap1″ mimetype=”application/x-microsoft.net.object.binary.base64″>

        <value>[base64 mime encoded serialized .NET Framework object]</value>

    </data>

    <data name=”Icon1″ type=”System.Drawing.Icon, System.Drawing” mimetype=”application/x-microsoft.net.object.bytearray.base64″>

        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>

        <comment>This is a comment</comment>

    </data>
               

    There are any number of “resheader” rows that contain simple name/value pairs.

   

    Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture.Classes that don’t support this are serialized and stored with the mimetype set.

   

    The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly:

   

    Note – application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below.

   

    mimetype: application/x-microsoft.net.object.binary.base64

    value: The object must be serialized with

            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            : and then encoded with base64 encoding.

   

    mimetype: application/x-microsoft.net.object.soap.base64

    value   : The object must be serialized with

            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter

            : and then encoded with base64 encoding.

 

    mimetype: application/x-microsoft.net.object.bytearray.base64

    value   : The object must be serialized into a byte array

            : using a System.ComponentModel.TypeConverter

            : and then encoded with base64 encoding.

    –>

  <xsd:schema id=root xmlns=“” xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:msdata=urn:schemas-microsoft-com:xml-msdata>

    <xsd:import namespace=http://www.w3.org/XML/1998/namespace />

    <xsd:element name=root msdata:IsDataSet=true>

      <xsd:complexType>

        <xsd:choice maxOccurs=unbounded>

          <xsd:element name=metadata>

            <xsd:complexType>

              <xsd:sequence>

                <xsd:element name=value type=xsd:string minOccurs=0 />

              </xsd:sequence>

              <xsd:attribute name=name use=required type=xsd:string />

              <xsd:attribute name=type type=xsd:string />

              <xsd:attribute name=mimetype type=xsd:string />

              <xsd:attribute ref=xml:space />

            </xsd:complexType>

          </xsd:element>

          <xsd:element name=assembly>

            <xsd:complexType>

              <xsd:attribute name=alias type=xsd:string />

              <xsd:attribute name=name type=xsd:string />

            </xsd:complexType>

          </xsd:element>

          <xsd:element name=data>

            <xsd:complexType>

              <xsd:sequence>

                <xsd:element name=value type=xsd:string minOccurs=0 msdata:Ordinal=1 />

                <xsd:element name=comment type=xsd:string minOccurs=0 msdata:Ordinal=2 />

              </xsd:sequence>

              <xsd:attribute name=name type=xsd:string use=required msdata:Ordinal=1 />

              <xsd:attribute name=type type=xsd:string msdata:Ordinal=3 />

              <xsd:attribute name=mimetype type=xsd:string msdata:Ordinal=4 />

              <xsd:attribute ref=xml:space />

            </xsd:complexType>

          </xsd:element>

          <xsd:element name=resheader>

            <xsd:complexType>

              <xsd:sequence>

                <xsd:element name=value type=xsd:string minOccurs=0 msdata:Ordinal=1 />

              </xsd:sequence>

              <xsd:attribute name=name type=xsd:string use=required />

            </xsd:complexType>

          </xsd:element>

        </xsd:choice>

      </xsd:complexType>

    </xsd:element>

  </xsd:schema>

  <resheader name=resmimetype>

    <value>text/microsoft-resx</value>

  </resheader>

  <resheader name=version>

    <value>2.0</value>

  </resheader>

  <resheader name=reader>

    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>

  </resheader>

  <resheader name=writer>

    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>

  </resheader>

  <data name=Name xml:space=preserve>

    <value>Bejaoui Bechir</value>

  </data>

  <data name=Country xml:space=preserve>

    <value>North Africa</value>

  </data>
</
root>

You shouldn’t be worry about all the content at first glance, as you see, all inserted parameters are located in the bottom of the page and nested within the

<data><value></value></datatags.

<data name=Name xml:space=preserve>

    <value>Bejaoui Bechir</value>

  </data>

  <data name=Country xml:space=preserve>

    <value>North Africa</value>

 </data>

The above elements are described in the table bellow:

Element

Description

data

The data tag is used to specify the resource attributes.

name(Necessary),
type(Optional but recommended), we should indicate the type it self like System.Int32, the name space such as System, the version, the culture and finally the public key token.

value

It is the tag that value is wrapped in

xml: space

It is used to identify the document if a white space is considered as important

This attribute accepts two values:

default: This option will treat the white space within a document as something neglected.
preserve:This option will treat the white space within a document as something that has meaning.


Concerning the part just above the first data tag, it’s called the header or the resx file header. It provides a detailed description about resources. So, if I try to represent the above resx file, the figure should be as bellow:

The resx file


<?
xml version=1.0 encoding=utf-8?>

<root>

Contains comments added by Microsoft to explain in adavantage the resx improuvements

<xsd:element 1>

Contains the resources descriptions according to the element1, namely, root in our case

</xsd:element 1>

<xsd:element 2>

Contains the resources descriptions according to the element2, namely, data in our case

<xsd:element 2

<resheader name=resmimetype><value>The resource file type</value></resheader>

<resheader name=version><value>2.0</value></resheader>

<resheader name=reader><value>resx reader object</value></resheader>

<resheader name=writer><value>resx writer object</value></resheader>

<data name=Name xml:space=preserve>

    <value>Bejaoui Bechir</value>

</data>

<data name=Country xml:space=preserve>

    <value>North Africa</value>

</data>

</root>

As a response to the second question, I can say, that a resx file can’t be directly embedded in a runtime environment; it has to be converted to a resource file before. Therefore, they are two different resource files formats. And we will talk about how to generate a resource file form a resx file in subsequent articles. 

 

Resource file:


I can define this kind of file as a common language runtime binary file that one can embed within a runtime environment. In order to be used by the application core later. To understand better the approach, I suggest this kind of analogy.


In this case the code source can’t used directly except that it will be compiled to (*.exe) or (*.dll) assembly, same think can be said according to the resx and resource file, the resx file represents the code source and the resource file represents the binary file either resource format file or an assembly satellite. We will see in next articles a walkthrough of how to generate assembly satellites from resx and text files and what for

  

 

About these ads

1 Comment »

  1. You have blown it man.. Beyond awesome. Thanks a ton.

    Comment by Chand — September 9, 2011 @ 6:54 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Rubric Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: