Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, May 9, 2012

Best Practices in coding

  •  Pascal Cashing is First character of all words are Upper Case and other characters are lower case. Ex: CostCenter
  •   Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case. Ex: costCenter
  •  Use the prefix “I” with Camel Casing for interfaces ( Example: IVehicle )
  •  Do not use m_ prefix when declaring member variable name. All variable should use Camel case
  •  Use meaningful and descriptive variable name  like string Address;
  • Do not use single characters like I,s instead of this use like Index, temp
  • Do not use variable name which resemble keyword.
  • Prefix Boolean variable and properties with is . Ex. Boolean IsNameExits
  • Namespace names should follow the standard pattern 
    • companyname.productname.toplevelmodule.bottomlevelmodule
  • Use appropriate prefix ui for different controls. Below is the list of items
  • Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.
  • Control
    Prefix
    Label
    Lbl
    TextBox
    Txt
    DataGrid
    Dtg
    Button
    Btn
    ImageButton
    imb
    Hyperlink
    hlk
    DropDownList
    ddl
    ListBox
    lst
    DataList
    dtl
    Repeater
    rep
    Checkbox
    chk
    CheckBoxList
    cbl
    RadioButton
    rdo
    RadioButtonList
    rbl
    Image
    img
    Panel
    pnl
    PlaceHolder
    phd
    Table
    tbl
    Validators
    val
  •  File name should match with Class name. Use Pascal case while creating file Name.
  • Curley braces and comments should be on same level. Like  below
    • // Format a message and display
    • string fullMessage = "Hello " + name;
    • DateTime currentTime = DateTime.Now;
    • string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
    • MessageBox.Show ( message );
  •  Use one blank line to separate logical code block.
  • The curly braces should be on a separate line and not in the same line as if, for etc. that will increase the readability of the code.
  • Put the logical code block in region and #region so that when developer collapse the definition it will separate the code accordingly.
  • Avoid writing big methods. Try to make the method of 1-40 lines and if the function is getting bigger than separate it in sub functions.
  • Do not put hardcode values in the code instead of use constraints and define it on starting on the file.
  • Use String.compare instead of converting them upper or lower case.
  • Use String.isNullorEmpty instead of “”
  • 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;
              }
       }
  • Never hardcode a path or drive name in code. Get the application path programmatically and use relative path. 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:".
  • 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.
  • 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."
  • 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.
  • 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.
  • 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.
  • 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.
  •  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.
  •  Avoid passing too many parameters to a method. If you have more than 4~5 parameters, better to create a class and then send as parameter.
  • Do not store large objects in session. Storing large objects in session will consume lot of server memory as number of user increases.
  • 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
  • If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.
  • 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.
  •  When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.
  •  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.

Wednesday, April 18, 2012

Performance tips for ASP.net

Performance Tips

1) Always use StringBuilder if you want to Concatenation two strings in a loop. Because if you Concatenation using the string object then both string object will be saved to memory first and then old string will be deleted and values will be read from new string object. It’s time consuming and hit the performance too.

2) Avoid Server Trip- It’s always smart to avoid unnecessary server trip. Some of the methods to avoid server side trips are 1) Do client side validation 2) Implement Ajax control for web application so only partial page will be loaded and not the full page.3) use Page.ISPostBack -Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is loaded the first time and not in response to client post backs.

3) Save View state- Save the view state only when it is must otherwise skip it. When we can avoid to having view state true. 1) Your page does not post back. It just show the data and there is no need to reload it again. 2) you do not handle server control events in your page. 3) If you ignore old data, and if you repopulate the server control each time the page is refreshed

4) Use of Session Variables- When storing the data in session variable make sure you use efficiently. Even though you close the browser but the session variable remain on server for a long time.

5) Use Server.Transfer – whenever you need to redirect to an page within the website you use Server.Transfer and not Response.Redirect. If you need authentication and authorization checks during redirection, use Response.Redirect instead of Server.Transfer

6) Choose the data viewing control- DataGrid control can be a quick and easy way to display data, but it is frequently the most expensive in terms of performance. Rendering the data yourself by generating the appropriate HTML may work in some simple cases, but customization and browser targeting can quickly offset the extra work involved. A Repeater Web server control is a compromise between convenience and performance. It is efficient, customizable, and programmable.

7) Optimize code and Exception handling- Use for loop instead of for each loop. It’s better to write a code which check the condition and make sure you don’t have exception in your programme flow. Because handling the exception and writing it on server will hit the performance.

8) Use DataReader- Use datareader for fast retrieval. If you want to show just read-only data then better to use datareader instated of dataset.

9) Use Paging- It is general idea that people don’t want to see thousands of data. So it is always better to use paging so that it will increase the performance.

10) Explicitly close resource- Always use try /finally and make sure you close and dispose all the connection and any other objects which is not required any more.

11) Disable Tracking and debugging. Always disable tracking and debugging when you deploy the application on production server. Set debug=false in web.config

12) Use store procedures- In most cases you can get an additional performance boost by using compiled stored procedures instead of ad hoc queries.

13) Always make sure you check Page.IsValid before processing your forms when using Validator Controls.

14) When you can, use toString () instead of format (). In most cases, it will provide you with the functionality you need, with much less overhead.

15) Place StyleSheets into the Header

16) Put Scripts to the end of Document

17) Make JavaScript and CSS External -Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of HTTP requests.

Tuesday, April 21, 2009

Finding Number of Rows in UltraGrid

Hi friends
Today i was working on Ultra Grid provided by
Infragistics. I found out a typical problem. There is a scenario where i have to find the number of rows selected in the grid. These number of rows are not by selecting the check boxes in the grid cell but by CTR-Click combination. i can check the activated row by the active index properties but now i have to select all the rows which i have previously selected with the holding the control button. Below is the code which might be helpful for you.


public ArrayList GetSelectedAccount(Infragistics.Win.UltraWinGrid.UltraGrid dgAccount)
{
ArrayList AccountArray = new ArrayList();
CurrencyManager cmAccount = (CurrencyManager)this.BindingContext [dgAccount.DataSource, dgAccount.DataMember];
DataView dvAccount = (DataView)cmAccount .List;
for (int i = 0; i < dvAccount .Count; ++i)
{
if (dgAccount.Rows[i].Selected)
{
AccountArray.Add(dgAccount.Rows[i].Cells["AccountID"]);
}
}
messagebox.show(AccountArray.length.tostring());
}
[/CODE]

Monday, January 5, 2009

Create a text file using Dataset or Datatable in C#

I am currently working with the Dataset. I had a requirement in which i have to write a functionality in which all the data is written to the text file. The requirement is like create a text file and all the columns will be separated by tilde symbol. Below is the sample code which will solve the problem.
void CreateTextfile(string FilePath,Datatable dt)
{
int i = 0;
StreamWriter swTextFile= null;
try
{
swTextFile= new StreamWriter(filePath, false);
for (i = 0; i < dt.Columns.Count - 1; i++)
{
swTextFile.Write(dt.Columns[i].ColumnName + " ");
}
swTextFile.Write(dt.Columns[i].ColumnName);
swTextFile.WriteLine();
foreach (DataRow row in dt.Rows)
{
object[] array = row.ItemArray;
for (i = 0; i < array.Length - 1; i++)
{
swTextFile.Write(array[i].ToString() + "~");
}
swTextFile.Write(array[i].ToString());
swTextFile.WriteLine();
}
swTextFile.Close();
}
catch (Exception ex)
{
throw ex;
}
}

Friday, January 2, 2009

NSIS Script for 64 Bit Machine

Today i was working on the NSIS scripts. In this perticular script i have to write the registry values in the system. There is a function call WriteRegExpandStr.
syntax: WriteRegExpandStr HKLM "Software\ProductName" "dbServer" "anyvalue"
This function will write the registry value "anyvalue" in the registry with the keyname as dbserver. Now this works good when we have the 32 bit machine. Now when you have 64 bit machine and then this value you won't see under "Software\ProductName" . By default it will be created under the "Software\Wow6432Node\ProductName" . In my case my application reading the data from the Software\ProductName and there is no data as the registry values are written under Software\Wow6432Node\ProductName . Just to keep my code in tacke i have write a small function which will check if the machine is 64 bit or a 32 bit. Depend on the machine type it will get and update the data from the registry. Below is the code
public static string CheckIf64BitOS()
{
int bits = IntPtr.Size * 8;
return bits.ToString();
}

if (CheckIf64BitOS().Equals("64")) {//Write a logic for 64 bit}
if (CheckIf64BitOS().Equals("32")) {//Write a logic for 32 bit}

Hope this will solve your problem.

Monday, September 15, 2008

Login Error in subreports with Crystal Reports

I am a fan of crystal reports. When ever it is feasible i want to use the Crystal report in my .net application whether it is window or web application. 
While working with one of my window application i got this weird error. It ask me for login in the database. That also happened with my reports which i changed recently.  The reports were working good till they were on my development system. It started giving problem when they are deployed on client machine. 
My client enviourment we have VS 2008 IDE too. So i opened the Report and went in the Dataset and check if it is pointing to correct XSD or not. I am using XSD (Type data set) in  all my crystal reports. Now when i click on the verify database the message came up "Data base is up to Date" . But after that the message box came up for selecting the XSD. I have selected the XSD and then the report start working as expected. 
With all these exercise i came to know that there is some problem with the XSD. The only way to find out the problem is this way
1) Open the .rpt file
2) Go to field Explorer
3) Right Click on database field and then Database Expert
4) Create New connection 
5) Click On ADO.net 
6) It will ask you to select the class
7) If you have some table already  selected then you can just right click the table and see the properties. if Visual Studio Data Class name  is set for the Local directory something like c:\project..
that is the root of the problem. So you have to make it from the project not from the local directory.

 

Wednesday, September 10, 2008

Distinct records in datatable

Here is the easiest way to create a table with the distinct records. I have to add the currency symbols with the Currency name in the brackets. If these currency name was not the constraint then it was be really easy for me to add the items in the Combobox. I was able to add the items in the comboox and before adding just giving this condition 
if (ddlCurrencySymbol.Items.Contains("Textvalue")) continue;
Solve my purpose. But now the problem was i have to add the Currency name also in the list. So i can't just adding the name and use the above condition because it will create Euro for many countries. 

Now here what i have done to solve this issue.
I create two functions and use them to get rid of the Extra values.

public void SelectDistinctCurrency(string TableName, DataTable Table1, string CurrencyName)
        {
            DataTable dt = new DataTable(TableName);
            dt.Columns.Add(CurrencyName, SourceTable.Columns[CurrencyName].DataType);
            dt.Columns.Add("Text", SourceTable.Columns[CurrencyName].DataType);
            object FinalValue= null;
            foreach (DataRow dr in SourceTable.Select("", CurrencyName))
            {
                if (FinalValue == null || !(ColumnEqual(FinalValue, dr[FieldName])))
                {
                    FinalValue = dr[CurrencyName];
                    dt.Rows.Add(new object[] { FinalValue, dr["Text"] });
                }
            }
            ddlCurrencySymbol.DataSource = dt;
            ddlCurrencySymbol.DisplayMember = "Text";
            ddlCurrencySymbol.ValueMember = "Value";
        }
        private bool ColumnEqual(object A, object B)
        {

            if (A == DBNull.Value && B == DBNull.Value) 
                return true;
            if (A == DBNull.Value || B == DBNull.Value) 
                return false;
            return (A.Equals(B));  
        }

Hope this will hep you out.

Tuesday, September 9, 2008

Winform Size

Hi friends 
i fond one intresteing thing today. It was increaing the height of the window form in Visual studio. I have oen collegue he cam up with unique problem. he ask me how to increase the size of the Window form in the VS. The obvoius answer was just go to properties and add the number and the form will increase of that size. But to my surprize what ever value we enter it will revert back to 768 Pixel.  Now how to increase in the size if i want that to 1000. 
The trick was just  change the resolution of your system and then increae the size. now revert back to old resolution this increased sized won't revert back. It will remain 1000 Pixel only :)