NDepend – A Static Code Analysis Tool

In this post I am going to review one of the static code analysis tool Ndepend by Patrick Smacchia. Before that I would like to explain few things about Static Analysis of Code.

Static Analysis of Code:

I would like to quote the great Alan Turing (Father of computing) words here

”There is no automated (or mechanical method) and completely reliable way to decide whether a program will work without any errors”

This is the result of experiment done by Turing in the 1930s which lead to Undecidable problem. (Please Google for more details).

But due to the complexity of modern software, it’s impossible to read and review entire source code of a program. We need a smart automated tool or software to do the same.

I have been coding in C# from last 3 years after my graduation. When I first heard about static analysis code tools I used to have few assumptions or I can say myths which are proved to be wrong after some time.

  • Static analysis tools does not actually execute the Code, they examine the source code based on few rules and regulations gives information to the user (For instance language compiler also a static analysis code tool eg:c# compiler list out the unused variable as warning).
  • Testing and static analysis are not the same. A code analysis tool will examine the code give some warnings, if you are not getting any warnings that indicates the quality of code. But at the same if you are getting warnings that don’t mean that your code is buggy. But with these tools you can find hard to catch errors (eg: Object reference not set to an instance of an object, yes if you are new to C# you cannot escape this error J) and edge case scenarios that can cause problems in near future so that we can fix them in early phase of development.

I have not used any quality tool till now, I was asked to review Ndepend static code analysis tool for C#, Thanks to Patrick Smacchia, I learnt few things about static analysis tools, purpose of them and Here is my experience with Ndepend.

NDepend static Code Analysis Tool:

First I took a visual studio project for instance I examined a simple MVC application. (Installing Ndepend and integrating it with visual studio you can have a look at the Videos and tutorials in Ndepend official Website)

It takes few minutes to analyze the project for the first time generates reports about current project.

The reports consists

  • Application Metrics like Lines Of Code, percentage of comments, method complexity, code coverage etc.
  • Few graphs like Dependency graph, Dependency metrics, Tree map view etc.
  • And also few predefined rules violation details

Please have a look at the below screenshot for more details

Ndepend Dashboard

Ndepend Dashboard

You might be thinking these reports we can get it with other static analysis code tools as well, but the real exciting feature of Ndepend is Code Query LINQ.

For example to get all methods having lines of Code more than 50 lines we can simply open the CQ linq editor and write

 

And to know whether code is properly commented or not

 

And know methods which are having high CyclomaticComplexity just type the following query

 

And double click on the methods you can directly edit them in visual studio.

When you run analysis NDepend will check against few built-in code quality queries

Ndepend Rules

Ndepend Rules

 

I have received one warning saying “Instances size shouldn’t be too big” when I click on the warning it displays query

 

I learnt so many quality code rules while experimenting with NDepend

For example under .Net framework usage category I saw a rule saying

Don’t create threads explicitely : which consist a nice explanation

 

Here I am listing out few quality code rules by Ndepend

  • Types should not extend System.ApplicationException
  • Collection properties should be read only
  • UI layer shouldn’t use directly DB types

Internally the tool executing few queries to generate reports in user friendly format. So if you are familiar with the query language you can write our own custom queries and you can generate our own reports.

And also the tool generates few graphs explaining about your code quality.

I tried summarize the important features of NDepend in this post. I recommend you people to install Ndepend trail version and explore the features on your own.

You can see complete list of NDepend features here http://www.ndepend.com/Features/

Final Word:

As a C# developer, I found NDepend very useful and I really think that the CQLinq language best feature of the tool. I did some research on other tools as well, but didn’t find anything as good as NDepend.

Checked and UnChecked Keywords in C#

In this tutorial I will explain about little known keywords called checked and unchecked in C#.

I came to know about these keywords accidentally, I will share the story with you people.

One of my friends’s project simple arithmetic addition failing and returning some garbage value (No exceptions). The code is something like this

 

CheckedandUnchecked

CheckedandUnchecked

 

The NumberOfOrders and newOrders are integer variables and after couple of minutes of investigation we came to know that it got reached it’s maximum value, To our surprise there is no compile time error as well as runtime error.

 

Then we came to know about checked and unchecked keywords.

In C# language we have two types of execution contexts checked and unchecked(Which is very new to me). And this context is depend on compiler most of the cases it’s unchecked.

In Unchecked context arithmetic exceptions are ignored and result will be truncated. The following operations are affected due to this contexts

  • Statements using ++       – (unary)   +   –   *   /  on integral types(byte ,char, short, int, long variables types).
  • Explicit numeric conversions between integral types.
Checked and UnChecked Csharp

Checked and UnChecked Csharp

So the correct code will be

 

Just include the code in “checked” block. And now at runtime code will through arithmetic overflow exception. So to handle the exception I will add try catch blocks. So the final code is

 

Now you might be thinking that why we required two contexts , instead we can maintain only one checked context. In real world projects chances of getting arithmetic overflow exceptions are very low(that’s why default context is unchecked).

So checking for exceptions for each such statements at runtime will be extra overhead for CLR. So the code that might cause overflow exception should be executed in a checked context.Remaining code will be executed in unchecked environment for which performance is priority

The ideal solution for this is to write code like below

 

 Checked and Unchecked contexts with Constant variables:

For constant variables compiler itself will throw the error “Overflow in constant value computation”.

 

The above code will not compile and throws the error. And If you want to skip the exception just execute them in unchecked context as shown below

 

We can specify the context for single statements also as shown below.Just add the checked or unchecked keyword before the statements and enclose the statements in brackets.

 

I hope you’ve enjoyed this article and that it gives you more ideas on checked and unchecked keywords in C# .If so share this post with your friends, follow me on social networks and also join our mailing list. 

 

Ref and Out parameters in C#

In this C# tutorial I will explain about main difference between ref and out parameters with simple C# examples.ref and out  parameters allows us to pass the parameters by reference instead of Value in C# language.

The simple way of declaring methods with ref and out parameters are as follows

 

Now we will understand the difference between ref and out parameters by writing a small program

 

Out Parameter in C#:

If you execute the above program you will get following errors

  • The out parameter ‘a’ must be assigned to before control leaves the current method
  • Use of unassigned out parameter ‘a’

i.e., If you are using “out” parameters you must initialize the out parameter in CalledMethod (MethodOut). It’s not necessary to initialize the out parameter before calling the method.Even though you initializes the variable, called method cannot read it. Called method should write the “out” parameter before returning to calling method.

We can have only one return type to a particular Method. So “out” parameter is useful when you want a method to return multiple values.

 

In the above example we are updating “a” to Database the method will return true or false. If its failed we want the reason why it got failed. In that case we can “out” parameter as reason and assign corresponding error to that “out” parameter.(You must assign out parameter that’ y I assigned to Empty in the success case)

Ref Parameter in C#:

Now we will come to “ref” parameter . I slightly modified the starting program as shown below.

 

The code will throw following error

  • Use of unassigned local variable ‘aref’

That means you must assign the value before calling the function.(Same for normal variables but the difference is ref parameter called by reference and normal parameters called by Value).

This is the main difference between ref and out parameter.Out parameters is not required to assign the value before calling the function where as ref parameter should assign the value like normal parameters.

So When to use “ref” parameters If you want to do manipulations on parameters (For example swapping two variables) we can use the ref parameters. Please see the below example

 

Few Similarities between ref and out Parameters:

  • Both allows us to pass parameters by reference instead of by Value
  • For CLR(Common Language Run time) both ref and out parameters are identical that means same Intermediate code will generate for both keywords. and the metadata also same except for one bit which specifies whether you specified out or ref when declaring the method.
  • The difference is that the C# Compiler ensures that we write the correct code.(That’s why compile time error will come when didn’t initialize the ref parameter).

A ref or Out parameter cannot have default values as normal parameters. The following code snippet will not compile

 

Overloading of Methods with ref and out Parameters in C#:

This is an interesting question just execute the following code snippet

 

This will throw the following error

  • Cannot define overloaded method ‘Add’ because it differs from another method only on ref and out

As I mentioned in similarities (second point) as the CLR treat both keywords are same their Metadata representation of the method signature and everything will be identical. It’s not correct to declare a method with same signatures and parameters.

It’s again C# Compiler responsibility to ensure we write the correct code(third point in similarities) So that’s why it’s returned an error.

I hope you’ve enjoyed this article and that it gives you more ideas on ref  and out parameters in C# and similarities and differences between them.If so share this post with your friends and also join our mailing list

 

Online shopping Discount Coupons Application For Windows 8 Phone

   All smartphones that are available in the market these days run on operating systems such as Android, Windows, iOS, etc. If you have a smartphone with any of these three operating systems, then you will surely find a plethora of apps for them. In fact, most people look at the operating system first and then buy the smartphone.

In addition to communication, there are many other uses of smartphones. These devices are also being used very frequently for online shopping. Smartphones and tablets are considered to be the most favourite gadgets for online shopping on the go. There are some very good Windows phone apps that enable you to buy items from online stores with exciting offers and deals. A typical windows phone app may connect you to multiple online stores to show you the lowest prices for the same product. For example, if you are searching for Nike sports shoes, you can use the Windows Phone App for searching the best deals on the internet for Nike sports shoes.

 The Amazing Concept of Coupons for Online Shopping:  

When you browse the online stores on the internet, you will find most of them asking for coupon codes. What are these coupon codes? Why are they used? What are their benefits? Are they just a marketing gimmick? These are some questions that most people have in mind if they have not used coupon codes or discount coupons on the internet. The concept of coupon codes is very simple and you will find that it is very convenient as well. You can check out a Couponraja App for Windows Phone and see how this coupon concept works.

CouponRaja

CouponRaja

In a typical scenario, you will have to choose the product that you desire to buy first. Then you will have to browse the internet to search for the coupon code for that particular product. When you get the coupon code, you will have to save it on your smartphone. When you are on the check out page of the online store, you will have to use the coupon code to further reduce the price of the product that you have selected.

Coupon codes are meant to encourage customers to shop online. Shopping online is not only exciting but also convenient as you can save upon a great deal of time and money. Moreover, the discounts offered online help to save money as well. With the latest applications available in the marketplace, you will not have any problem in selecting the right product for you.

CouponRaja

CouponRaja

Before you download any application, you will have to check for the authenticity of the developer. If the developer is a company, then you can be rest assured that you are getting a genuine application. For some applications, you will have to make an online payment to get those applications. Some free applications for mobile phones may be free for a few months, but then they would be available at a nominal charge. If you feel that an application is good for your smartphone, then paying a nominal amount is not a big deal at all.  Most online shopping apps are provided for free and are equally safe to download.  So, if you are avid shopper, downloading a couple of them could be the best thing you can do.

Introduction to Responsive Web Design Using Twitter Bootstrap3

 

I started learning responsive web design using Twitter Bootstrap Framework. This is my first tutorial on responsive Web design, I will start with the introduction Bootstrap framework and responsive web design, and at the end of the post you will get an idea how to build responsive web pages using bootstrap framework.

What is Responsive Web Design?

      Instead of telling What is Responsive Web design It’s better to explain What problem does responsive web design solve? Earlier we used to build separate versions of websites for devices like Iphone Blackberry Ipad and Kindle etc because of different resolutions of devices. But daily one new device with new resolution coming into the mobile industry. Building again one more version of website for those new device is foolishness.

     In simple words we should built webpages in such a way that they should look uniformly(best viewing experience) across all the devices irrespective of devices and resolutions.This is nothing but responsive web design.

      Twitter Bootstrap framework provides a great platform for building such responsive web pages.

Introduction To Twitter Bootstrap Framework:

So What is Bootstrap Framework? Initially UI designers has to give design of the website to the developers so that they can proceed further development. But this is waste of time.

  • Twitter Bootstrap is a CSS framework which helps developers in building web pages even though you don’t have any designing experience.
  • All you have to do is write HTML code according to the Bootstrap specifications.
  • There are so many inbuilt classes written in Bootstrap framework. Just you should learn how to use those classes.

I know it’s too high level explanation but once you started learning the framework you will understand.

Responsive web designing became very easy with the help of Twitter Bootstrap framework.

We will start with one simple example First we will decide some design for the webpage.

Setting Up Twitter Bootstrap Framework:

Download the twitter Bootstrap framework zip file and extract them you will find three folders css,js and fonts. and create one html file I created as Index.html.

Twitter Bootstrap Framework Structure

Twitter Bootstrap Framework Structure

Setting up Bootstrap Responsive HTML page:

Before starting our example we will include the all necessary CSS and Js files and attributes to the html file. Have a look at the sample HTML page.Don’t forget to add jQuery file.

 

No need to explain all fields all are self explanatory. The only new thing is viewport meta attribute.

 

The viewport attribute sets the width of the webpage to Device Width and Initially scaling to default size 1. And if you want to increase the zoom or decrease the Zoom you may change this value.

That’s it.Set up is Done. Now we will learn how to write HTML mark up according to bootstrap framework.

Responsive Web Page Using Bootstrap

Responsive Web Page Using Bootstrap

Our webpage contains

  • One Header with Navigation bar
  • One Featured Content
  • Content with 4 horizontal Divisions.

We will write appropriate HTML mark up according to our needs

Bootstrap Header with Responsive Navigation bar:

Our page content should be in center of the screen. Bootstrap provides a “container” class with correct padding and margin values. We will use this container as our parent element. Just write the following Code.

 

Now we will add Title of the web page inside this Div Container

 

No need to add any external styles to H1 tags Bootstrap provides default styling for H1 element.

Now we will add responsive Navigation bar.First have a look at our navigation bar.

Bootstrap Navigation Bar

Bootstrap Navigation Bar

 

The Navigation Bar contains one heading Navigation,Navigation Bar Menu and One search box with submit button.

Bootstrap provides  “navbar” class for navigation bar. Add following HTML code below the title of the website(Inside container Only)

 

I have added one more class “navbar-default” which will add default styles to Navigation bar. Now we will add navigation menu elements

 

Just create a list of elements and Add classes named “nav navbar-nav”. and “Active” class refers to the selected navigation element. Our Menu is ready.

But we have one more search box in navigation Menu To add that search box just add following Code.

 

Normally search box is a form so I added form element And To include it in navigation Bar add “navbar-form”. And I added one more class called “navbar-right” which tells that the search should be in right side of the navigation bar. You can play with this settings by giving “navbar-left” ,”navbar-top” etc.

Just go and look at your webpage. And if you tested it in Mobile or Tab you might observe that this is not responsive. How a responsive menu look like in mobile devices. Have a look at the below image

Bootstrap Responsive Navigation Bar

Bootstrap Responsive Navigation Bar

 

The above menu design is used in Mobile devices. We have Navigation Header (Brand) and Navigation elements in drop box and when you touch the button it will collapse.

So we will slightly modify our code to make it responsive menu

 

First I added entire navigation menu inside “container-fluid” class.We are collapsing and expanding the menu so width and height should be varied accordingly. So I have added “container-fluid” class.

Now I added “navbar-header” class which contains a Button and Navigation header text. The button contains three horizontal icons as shown above figure.

So I have added three span elements with class “”icon-bar”.

And we have to give target and class “navbar-toggle” to button.Target is nothing but our Navigation Menu elements.

The list and search box I moved inside the “collapse navbar-collapse” class. which refers that this is Collapsable Menu. And gave some Id. The Id should be target of Button.

Our responsive Menu is Ready. Now we will add Featured Content.

Featured Content in Twitter Bootstrap:

Now a days most of the webpages contains featured content which will hi-lite the important information of webpages. And some web pages contains carousel.

Bootstrap provides “”jumbotron” class to display featured content. Just add below code under the navigation menu code.

 

And I gave few classes like btn btn-primary btn-lg etc. in anchor tags. those are all classes provided by the bootstrap. You can play around with them. In my coming posts I will try to explain all types of button classes.

Now we will add our main content. Now I am going to explain important feature of Bootstrap framework.

Grid System in Twitter Bootstrap:

Bootstrap is famous because of this Grid System.Bootstrap provides a 12 grid column layout to build web pages. i.e., you can place 12 vertical grids or columns inside any parent element.

This is responsive and mobile first fluid system.More technical words rite I will explain it in simple words.

Our webpage design contains four horizontal divs(Heading1, Heading2, Heading3 and Heading4).

To add this horizontal divs add the following Code

 

The four grid elements should be inside the class “row”. and I gave class names as “col-md-3”. We want four equal grids so 3+3+3+3=12. To put four equally width elements you should give class name as “col-md-3”. Here md-refers to medium devices normally desktops, should display 4 columns inside a row element.

If you want two unequal columns just give classes names as “col-md-8” “col-md-4” and again (8+4=12.) You can play around with this grid system according to your requirements.

And I said this grid system is responsive rite. What does it mean? In medium devices it shows 4 columns and in small devices it shows only one column according to device width. Look at the above gif image. I tested it in my Moto X mobile it’s showing one column per row.

But it’s better to mention this values explicitly so add following classes to the divs

 

Have a look at the below images

Responsive Grid in Desktops

Responsive Grid in Desktops

 

In Desktops medium devices Bootstrap displays 4 columns are in a row. i.e.,”col-md-3″ (3+3+3+3=12)

Responsive Grid in Tabs

Responsive Grid in Tabs

 

In tabs i.e., small devices Bootstrap displays Two columns in a row. col-sd-6 (6+6=12)

Responsive Grid in Mobiles

Responsive Grid in Mobiles

 

In Extra small devices i.e., Bootstrap displays one column in a row .col-xs-12

That means according to width of the device the webpage will adjust.

If you want to create any page layout you should use row- column grid system.

Here is the Final Demo

Responsive Web Design Using Twitter Bootstrap.

Check the responsiveness of web page here and Download the source Code from Here.

Follow my blog for bootstrap tutorials.

I hope you enjoyed this article If so share with your friends and also subscribe to my blog and connect me at social networks.