Thursday, December 13, 2012

Differance between Build & Rebuild

This afternoon khurram (another dev) and I were discussing it.

Build means compile and link only the source files that have changed since the last build, while Rebuild means compile and link all source files regardless of whether they changed or not. Build is the normal thing to do and is faster. Sometimes the versions of project target components can get out of sync and rebuild is necessary to make the build successful. In practice, you never need to Clean.

Build or Rebuild Solution builds or rebuilds all projects in the your solution, while Build or Rebuild builds or rebuilds the StartUp project. To set the StartUp project, right click on the desired project name in the Solution Explorer tab and select Set as StartUp project. The project name now appears in bold.

Compile just compiles the source file currently being edited. Useful to quickly check for errors when the rest of your source files are in an incomplete state that would prevent a successful build of the entire project. Ctrl-F7 is the shortcut key for Compile.

 

Wednesday, October 10, 2012

WebWorker in HTML5

 Hi Friends
This blog post  is because of Girish :) He enquire about Worker process and help me out to understand the concept. Thanks to Girish.

Webworker is new concept in HTML5. In earlier days when we execute scripts in HTML page , the page become unresponsive if use start clicking all over the page and script is taking time to execute.

A webworker is a javascript that runs in background ,independent of other scripts and without affecting the performance of the page. User can continue with whatever he wants, webworker works in background.

All major browser which support HTML5 will support this concept.

Before creating webwork you can use this function to check if your broswer support it or not.

function Checkwebworker()
{
if(typeof(Worker)!=="undefined")
  {
  }
else
  {
    alert('Your browser don't support webworker");
  }
}

PostMessage() method is used to post a messageback to HTML page.

you can create web worker object using below code
Worker oWorker= new Worker("javascript file name");

onmessage event listener can be used to send and receive message to the web worker.

oWorker.onmessage=function(event){
document.getElementById("txtresult").innerHTML=event.data;
};

When the webworker posts a message , the code in event listener is executed.

when webworker object is created ,it will continue to listen the messages until it is terminated.

we can use below syntax to terminate web worker process.
oWorker.terminate();

below is a simple html example of web worker process
<html>
<body>

<p>Count value: <output id="txtresult"></output></p>
<button onclick="startWorkerprocess()">Start Worker</button>
<button onclick="stopWorkerprocess()">Stop Worker</button>
<br><br>

<script>
var oWorker;

function startWorkerprocess()
{
if(typeof(Worker)!=="undefined")
{
  if(typeof(w)=="undefined")
    {
    oWorker=new Worker("demoworkers.js");
    }
  oWorker.onmessage = function (event) {
    document.getElementById("txtresult").innerHTML=event.data;
  };
}
else
{
document.getElementById("txtresult").innerHTML="Your browser does not support Web Workers.";
}
}

function stopWorkerprocess()
{
oWorker.terminate();
}
</script>

</body>
</html>

Wednesday, September 5, 2012

SQL Joins

Joins can be categorized as:
Inner joins
The typical join operation, which uses some comparison operator like = or <>. These include equi-joins and natural joins. Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.
 For example, retrieving all rows where the student identification number is the same in both the students and courses tables.

This inner join is known as an equi-join. It returns all the columns in both tables, and returns only the rows for which there is an equal value in the join column.



Natural join- This join will return all the rows depend on the join column you do on the tables. It will return the distinct columns from both the tables and not all the columns on both table.

Outer joins. Outer joins can be a left, a right, or full outer join.
Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:

LEFT JOIN or LEFT OUTER JOIN
The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.

RIGHT JOIN or RIGHT OUTER JOIN.
A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

FULL JOIN or FULL OUTER JOIN.
A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

Cross joins.
Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.

Cookies in asp.net

 Cookies are small text files written to the client's computer by a particular web site. These text files can then be read by scripts on the same web server that wrote those cookies. Since the cookies are written on the client's computer, specific information can be saved for each user. By storing information on the client's computer, the web server doesn't have to save this information.

Cookies are nice because they can be used to store small bits of user-specific information. For example, imagine that you wanted to allow your visitors to create a series of their favorite links on the start page of your site . You could create a Form into which the user could enter a series of URLs. You could then store these URLs on the user's computer using a cookie. Whenever a user visited your start page, you would check to see if the cookie that contained their favorite URLs existed- if it did, you would create HREF tags containing their favorite links.

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.

Tuesday, April 24, 2012

Code matrix in VS 2008


Code metrics is a tool which can show the developer how good is the code. Using set of measurements it will be easier to know how complex the coding is. By taking advantage of code metrics, developers can understand which types and/or methods should be reworked or more thoroughly tested. Development teams can identify potential risks, understand the current state of a project, and track progress during software development.

Below list shows the code metrics results that VS calculates:

Maintainability Index
Maintainability Index, which goes from 0 to 100 and indicates the overall maintainability of a class, member, namespace or project. If the value is higher than it show the code is better maintained. It also comes up with color code for quicker view.

Green - 20 and 100 (good).
Yellow - 10 and 19 (moderate)
Red - 0 and 9 (low)

Cyclomatic Complexity
Cyclomatic Complexity tells you two important things. First, it indicates the general complexity of a method. Lower is better; if the number is high, the method is probably trying to cover too many different situations and needs to be broken up into simpler, specialized methods that cater specifically to individual situations and are much easier to maintain. Second Cyclomatic Complexity tells you the total number of test cases you need to write, to ensure that all possible situations have been covered. So if the value is higher than you have to test the code with more test cases.

Depth of Inheritance
Lower is better; if Depth of Inheritance goes higher than three or four, your code will be difficult to maintain. The higher the number, the more subclasses you will have to modify and it might introduce new bugs when you do changes in base class.

Class Coupling
Lower is better; the higher the number, the more "tied-down" a class is, with more dependencies on the rest of its immediate environment and it will be difficult to reuse.

Lines of Code
Lines of Code (LOC) measure the size of a piece of software by counting the total number of executable lines of code in it. Lower is better. If you have higher value then you can go down to the function and try to break as much as possible. It will be easier to maintain and debug.

Best Practices in framework 2.0


Best Practices in framework 2.0

1)    The runtime optimizes the performance of 32-bit integer types (Int32 and UInt32), so use those types for counters and other frequently accessed integral variables.
2)    For floating-point operations, Double is the most efficient type because those operations are optimized by hardware.
3)    Garbage collection occurs only when needed or when triggered by a call to GC.Collect. Automatic garbage collection is optimized for applications where most instances are short-lived, except for those allocated at the beginning of the application. Following that design pattern will result in the best performance.
string s;
s = "wombat"; // "wombat"
s += " kangaroo"; // "wombat kangaroo"
s += " wallaby"; // "wombat kangaroo wallaby"
s += " koala"; // "wombat kangaroo wallaby koala"
Console.WriteLine(s);
Only the last string has a reference; the other three will be disposed of during garbage collection. Avoiding these types of temporary strings helps avoid unnecessary garbage collection, which improves performance. There are several ways to avoid temporary strings:

BEST PRACTICES Boxing and unboxing
Boxing and unboxing incur overhead, so you should avoid them when programming intensely repetitive tasks. Boxing also occurs when you call virtual methods that a structure inherits from System.Object, such as ToString.
Follow these tips to avoid unnecessary boxing:
4)    Implement type-specific versions (overloads) for procedures that accept various value types. It is better practice to create several overloaded procedures than one that accepts an Object argument.
5)    Use generics whenever possible instead of accepting Object arguments.
6)    Override the ToString, Equals, and GetHash virtual members when defining structures.

Regular Expression
7)    When validating input, always begin regular expressions with a “^” character and end them with “$”. This system ensures that input exactly matches the specified regular expression and does not merely contain matching input.