Archive for the ‘Asp.Net’ Category

To use sonar for code analysis you need to have some perquisites installed. We will go through step by step installation of all of the required software.

Note that the versions of software we have used are not necessary, you may use the latest versions but they need to compatible with each other.

Java Development Kit (JDK) 1.8.0_91 -32/64 bit

Download and install the JDK 1.8.0_91, if you don’t have it installed.

Install JDK, by default it will be installed in Program Files of your OS drive, which you can change.

After installation of JDK you will find a folder named Java in your Program Files folder. Note down this path as you will need it later: C:\Program Files\Java\jdk1.8.0_91\

Installing Sonar

Download Sonar 6.5. You can use this link to download it


It may be downloaded in a zip file. Unzip the file and place the folder in any drive of your choice.

We have placed it in: D:\Projects\TestProject\Sonar\

Download Sonar Runner

You also need to download Sonar Runner 2.4. It can be downloaded from the same link. Unzip the downloaded file and place it in any directory of your choice. We have placed in the same directory where we placed the sonar i.e. D:\Projects\TestProject\Sonar\ as shown above

Installing C# Plugins

You need the CSharp Plugins Ecosystem plugin which you may download from the link below:


Unzip the file (if it is zipped) and copy the file sonar-csharp-plugin-3.2.jar to plugins directory of Sonar.

In our case it is to be copied in in here: D:\Projects\TestProject\Sonar\sonarqube-6.4\extensions\plugins\sonar-csharp-plugin-

Configuring Sonar

Before starting sonar server we will need to do certain configuration changes:

  • Go to conf folder of sonar. In our case it will be found at: D:\Projects\ TestProject \Sonar\sonarqube-6.4\conf\. Here you will find the sonar.properties file.
  • Open file in Notepad or in some other editor.
  • Try to find “sonar.jdbc.username” within the file (without quotes).

Uncomment these lines (by deleting the # before the line), if they are commented (having # sign in the beginning) so that the file contains the below contents.

Configuring Sonar-Runner

Now it is time to configure Sonar-Runner:

  • In our case it could be found at: D:\Projects\ TestProject \Sonar\ sonar-runner-2.4\conf\.
  • Open sonar-runner.properties file in Notepad or in some other editor.
  • Try to find this text “sonar.sourceEncoding=UTF-8”. If it is commented un-comment it (by deleting the prefix # sign) so that the file contains the below contents.

Setting the Environment Variables

To set up the environment variables, you need to go to System Settings:

  • Press window key+brek button to open System settings or Go to Start->Control Panel->System.
  • Click on Advance system settings link. It will open a dialog.
  • Click on Environment Variables button. It will open another dialog box.
  • If you find variable named JAVA_HOME in the System variables, select it and click Edit Button. Otherwise click New button.
  • Fill the following in the dialog box:
    • Variable name: JAVA_HOME
    • Variable value: C:\Program Files\Java\jdk1.8.0_91
  • Note: Remember the variable value is same path where the JDK has been installed as mentioned earlier.
  • Click Ok.
  • Use the same steps to create another System variable name SONAR_RUNNER_HOME.
  • Fill the following for the variable SONAR_RUNNER_HOME.
    • Variable name: SONAR_RUNNER_HOME
    • Variable value: D:\Projects\TestProject\Sonar\
  • Click OK.
  • Finally try to find Path system variable in the list. If it is not there create it.
  • However if it already exists, select it and click Edit button.
  • Do not change the existing value of the variable, just add the following at the end of the value: ;%JAVA_HOME%\bin;%SONAR_RUNNER_HOME%\bin
  • If you have put sonar server at different path you will have to change the underline text accordingly.
  • Click OK and we are done with defining the Environment Variables.

Running Sonar Server

You have everything set to get the sonar server running. To run the sonar server do the following steps:

  • Go to bin directory of your sonar server. In our case it is D:\Projects\TestProject\Sonar\sonarqube-6.4\bin\
  • Where you will see different directories for different OS. Since we have installed 64 bit JDK, we will go to windows-x86-64 directory.
  • Right click on StartSonar.bat file and choose Run as administrator to open it. You may get a popup, click on Run button to open the file.
  • It will open a command prompt. Wait for some time until the sonar server is started as shown below:ConfigureSonarQubeWithDotNetProject.PNG
  • Now you have successfully started the sonar server.
  • Note: Depending upon the sonar version, you may get different message at the end in the command prompt.

Log on to sonar server

After the sonar server has started you can log on to sonar server by visiting the url: http://localhost:9000/ and you will see the below page:


Click on the log in link and enter the following credentials:

Login: admin

Password: admin

Note: Both username and password are case sensitive.

After you are logged in as an administrator you will see the dash board. This is sonar dash board where see the list of projects, Menus etc.

C# Plugins

Click on the Settings link the top right corner. From the menu on the left click on Update Center (in newer versions you may find it under system tab), Click on the Installed Plugins tab. You should be seeing C# [csharp] 3.2 under Installed plugins. You can also install other plugins related to c# from Available Plugins tab.

Creating Project Properties file

Open notepad or some other editor to create project properties file. Create a new file. Where you will write the following project properties:

  • Project key which must be unique for all the projects. It is defined by sonar.projectkey as shown: sonar.projectKey=Tutorial:SonarCsharp.
  • Project Version It is defined by sonar.projectVersion as show: sonar.projectVersion=1.
  • Project Name this is the name of project that will appear in the sonar project list. It could be different from your solution name: sonar.projectName=My C# Project for Sonar Analysis

Sonar Related Settings

Here you are going to specify the properties required by sonar to work for .Net projects. As shown below:



C# Setting

Here you will be defining the properties for C# by specifying where the c# plugins are installed and the location of project.

  • Project location project location is specified by sonar.dotnet.visualstudio.solution.file property. It value is the actual name of solution file along with extension, as shown below. sonar.dotnet.visualstudio.solution.file=MySonarProject.sln
  • .NET Installation Directory here you have to specify the installation directory of .NET, as shown belo sonar.dotnet.4.0.sdk.directory=C:/WIndows/Microsoft.NET/Framework/v4.0.30319
  • .NET Version specify the .Net version as below sonar.dotnet.version=4.0
  • Test Project if you have created any unit test project in your project, you can specify it with the following property sonar.donet.visualstudio.testProjectPattern=*UnitTests*;*test*;*Test*

Saving Project Properties File

Save the above file in the same directory where your project solution file (with extension .sln) exists with the name sonar-project.properties.

Note: the file must not have any other extension than .properties like txt etc. Extension should be .properties only.

Analyzing .Net project with Sonar

Now finally we will analyze our .NET project with SonarQube.

To run Sonar Analysis on .NET project do the following steps:

  • Start the sonar server as explained earlier.
  • Run command prompt as Adminstrator.
  • Reach to the directory where you have kept the sonar-project.properties file.(where .sln file exists) with the following command cd [path of properties file].
  • When you reach to your solution directory enter the following command sonar-runner.
  • Note: The sonar server must be running when you enter this command.

Wait for some time until the analysis is run on the project and you get the success message as shown below:


Getting Sonar Analysis Reports

The sonar analysis has been done and we can see the analysis reports on the sonar server.

To see the analysis server just refresh the page (Dash Board page) on http://localhost:9000/ and log in if you are not logged in already.

And you will be seeing your project in projects section. To see the detailed Analysis Report of you .Net Project just click on the name of your project, displayed under Projects section and you will be able to see the reports.


Read Full Post »

We all .Net developers use Microsoft Visual Studio 2005/2008/2010. We do lots of operation/action in the visual studio by clicking mouse on the icon though Microsoft provides us shortcut keys for those actions. Now a general question may raise that why we need those shortcuts when I have the mouse and I can easily click on the icon within a second. Believe me, as a .Net developer I am telling you if you use some common shortcut regularly your development time will be decreased by at least 10% – 12%. I am not expressing this information from my imagination. I myself experimented this situation several times. So guys start using shortcuts from today.

  1. CTRL + M, L (Toggle all outlining): Toggles all previously collapsed outlining regions between collapsed and expanded states.
  2. CTRL + M, P (Stop outlining): Removes all outlining information from the whole document.
  3. CTRL + K, C (Comment selection): Inserts // at the beginning of the current line or every line of the current selection.
  4. CTRL + K, U (Uncomment selection): Removes the // at the beginning of the current line or every line of the current selection.
  5. CTRL + K, D (Format document): Formats the current document according to the indentation and code formatting settings specified on the Formatting pane under Tools | Options | Text Editor | C#.
  6. CTRL + SHIFT + N (New project): Displays the New Project dialog box.
  7. CTRL + SHIFT + 0 (Open project): Displays the Open Project dialog box, where existing projects can be added to the solution.
  8. SHIFT + ALT + C (Add class): Displays the Add New Item dialog box and selects Class template as default.
  9. SHIFT + ALT + A (Add existing item): Displays the Add Existing Item dialog box, where existing files can be added to the current project.
  10. CTRL + SHIFT + A (Add new item): Displays the Add New Item dialog box, where a new file can be added to the current project.
  11. CTRL + K, W (Complete Work Intelligence): Completes the current word in the completion list.
  12. CTRL + K, I (Quick info): Displays the complete declaration for the specified identifier in your code in a Quick Info tooltip.
  13. CTRL + K, P (Parameter info): Displays the name, number, and type of parameters required for the specified method.
  14. CTRL + K, R (Find all references): Displays a list of all references for the symbol selected.
  15. F12 (Go to definition): Navigates to the declaration for the selected symbol in code.
  16. F7 (View Code): Displays the selected item in Code view of the editor.
  17. SHIFT + F7 (View designer, View markup): Switches between Design and Source views for the current document
  18. CTRL + W, C (Class view): Displays the Class View window.
  19. CTRL + W, D (Definition window): Displays the Code Definition window.
  20. CTRL + W, E (Error list): Displays the Error List window.
  21. CTRL + W, O (Output): Displays the Output window, where status messages can be viewed at run time.
  22. CTRL + W, P (Properties window): Displays the Properties window, which lists the design-time properties and events for the currently selected item.
  23. CTRL + W, S (Solution explorer): Displays Solution Explorer, which lists the projects and files in the current solution.
  24. CTRL + W, X (Toolbox): Displays the Toolbox, which contains controls that can be included or used with your code.
  25. CTRL + W, L (Server explorer): Displays Server Explorer, which lets you view and manipulate database servers, event logs, message queues, Web services, and other operating system services.
  26. CTRL + TAB (Next document window navigation): Displays the IDE Navigator, with the first document window selected.
  27. CTRL + D, C (Debug callstack): Displays the Call Stack window, which displays a list of all active methods or stack frames for the current thread of execution.
  28. CTRL + D, I (Debug immediate): Displays the Immediate window, where expressions can be evaluated.
  29. CTRL + D, Q (Debug quickwatch): Displays the QuickWatch dialog box that has the current value of the selected expression.
  30. F5 (Debug start): Launches the application under the debugger based on the settings from the startup project. When in Break mode, invoking this command will run the application until the next breakpoint.
  31. SHIFT + F5 (Stop debugging): Stops running the current application under the debugger.
  32. F9 (Toggle breakpoint): Sets or removes a breakpoint at the current line.
  33. F10 (Debug step into specific): Executes the next line of code, but does not follow execution through any method calls.
  34. F11 (Debug step into): Executes code one statement at a time, following execution into method calls.
  35. CTRL + D, W (Watch): Displays the Watch window, which displays the values of selected variables or watch expressions.
  36. CTRL + F9 (Enable breakpoint): Toggles the breakpoint between disabled and enabled.
  37. CTRL + R, E (Encapsulate field): Displays the Encapsulate Field dialog box, which allows creation of a property from an existing field and updates all references to use the new property.
  38. CTRL + R, I (Extract interface): Displays the Extract Interface dialog box, which allows creation of a new interface with members derived from an existing class, struct, or interface.
  39. CTRL + R, M (Extract method): Displays the Extract Method dialog box, which allows creation of a new method from the selected code.
  40. F6 (Build solution): Builds all the projects in the solution.

Read Full Post »

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, knowledge and experience. Believe it, majority of the programmers write ‘working code’, not ‘good code’. Writing ‘good code’ is an art and we all should learn and practice it. Some of the characteristics of good code are:

  1. Reliable
  2. Maintainable
  3. Efficient

Now i will tell some way to write your code with these characteristics.

Naming Conventions and Standards:

  1. Pascal casing for Class and Method names. Pascal casing means first character of all words are Upper Case and other characters are lower case. Example: “SaveProduct”.
  2. Camel casing for variables and method parameters. Camel casing means first character of all words, except the first word are Upper Case and other characters are lower case. Example: “totalCount”.
  3. Use the prefix “I” with Camel Casing for interfaces ( Example: IEntity ).
  4. Use meaningful, descriptive words to name variables. Do not use abbreviations like “num” or single character variable names like “i”, “n”, “s” etc. Example: “number”.
  5. Do not use underscores (_) for local variable names.
  6. All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.
  7. Prefix boolean variables, properties and methods with “is” or similar prefixes. Example: “isFinished”.

Indenting and Spacing:

  1. Use TAB for indentation. Do not use SPACES.  Define the Tab size as 4.
  2. Curly braces ( {} ) should be in the same level as the code outside the braces.
  3. There should be one and only one single blank line between each method inside  the class.
  4. Use one blank line to separate logical groups of code.
  5. Use #region to group related pieces of code together.

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.
  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.
  4. Do not hardcode numbers. Use constants instead.
  5. Do not hardcode strings. Use resource files i.e.  a separate constant file.
  6. 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.
  7. 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.
  8. Use String.Empty instead of “”.
  9. Do not make the member variables public or protected. Keep them private and expose public/protected Properties.
  10. 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.”
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. Use StringBuilder class instead of String when you have to manipulate string objects in a loop.
  16. Do not store large objects in session. Storing large objects in session may consume lot of server memory depending on the number of users.
  17. 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.
  18. Use try-catch in your data layer to catch all database exceptions.

Read Full Post »

Sort List/IList by Linq

As an Asp.net developer i have to work with List/IList very often. Another common requirement is to sort the list. Previously we had to do the sorting in database level or if we want to do it in application level then we had to implement the IComparer class.

But the amazing thing is we don’t have to do either of these two to do the sorting in List/IList. We can do it by writing only one line code using Linq.

public class Employee
  public string FirstName {set; get;}
  public string LastName {set; get;}
  public DateTime DOB {set; get;}

public void Sort(ref List<Employee> list, string sortBy, string sortDirection)
  //Example data:
  //sortBy = “FirstName”
  //sortDirection = “ASC” or “DESC”

  if (sortBy == “FirstName”)
  var list = list.OrderBy(x => x.FirstName).toList();

Read Full Post »