Friday, 19 April 2013

Visual Studio Features: Code Analysis, Code Metrics, and Code Clones

In this post I am going to introduce 3 Visual Studio features that are very interesting and helpful; but, alas, may not be that popular. I came to discover them recently and I instantly fell in love with them! I am sure you will love them too after you get to know and try them out. 

They are, namely: Code Analysis, Code Metrics, and Code Clones.

Code Analysis

The Code Analysis feature of Visual Studio examines the code by performing static code analysis to detect common pitfalls, defects, and violations of good programming practices. Thus helping developers identify potential design, globalization, performance, interoperability, and other issues in their code.   

The tool works to raise warnings that differ from compile errors and warnings; because the tool mainly searches for code patterns that are “logically” valid, though may still cause problems on the long run for you or for people who may check/use your code later.

Code Analysis can be run manually on a snippet of code, or even setup to automatically run as part of a Team Build or check-in policy for TFS [Team Foundation Server].  

Learn more about Code Analysis, What's New in Visual Studio 2012, and how to run Code Analysis on your system here.    

Code Metrics

Another feature that I truly like in Visual Studio 2012 is Code Metrics. Code Metrics is a tool introduced within Visual Studio that measures the evolvability and maintainability of a software system by calculating five important metrics. This helps the development team identify potential risks, understand the current state of their project, and track progress during software development.

The five metrics are:
  • Maintainability Indexa value between 0 and 100 that represents the relative ease of maintaining the code. Higher values indicate better maintainability.
  • Cyclomatic Complexity: this metric is a measure of the structural complexity of the code; it calculates the number of different code paths in the flow of the program. The actual value of this metric differs from one Visual Studio version to another. But a rule of thumb is that no individual method or property should have a Cyclomatic Complexity that is greater than ten.
  • Depth of Inheritance: it indicates the number of class definitions that extend to the root of the class hierarchy. The deeper the hierarchy the more difficult it might be to maintain and understand the code. However, a high depth of inheritance can also indicate a greater level of code reuse. So it is difficult to judge what a good depth is.
  • Class Coupling: this one measures the coupling to unique classes through parameters, local variables, return types, method calls, and other types in the source code. High values of coupling limit the value of a type to be reused; so a lower value [lower than ten] is what you should aim for.
  • Lines of Code: a value indicating the approximate number of lines in the code. A very high number indicates that the method/type is trying to do too much and should be split up. It may also indicate that the type/method is hard to maintain. 

More about this important topic and how to generate Code Metrics in Visual Studio 2012 can be found here and here

Code Clones

A personal favorite! It is a new feature introduced in Visual Studio 2012 that detects ALL code fragments that are copied throughout the solution. The tool detects the separate fragments of code that are very similar. Usually, code clones make it hard to change your application because you have to look for each fragment to update. Now it is easier as Visual Studio helps you find these clones so that you can refactor or modify them. Or just get to know the amount of “potential” copy/paste used in the system you are working on! :)

More about this, here

Monday, 8 April 2013

Store Data with sessionStorage

Recently, I began working on a web application that relies heavily on client-side scripting. At some point, I needed to store some key value and use it again within the same context. Sounds easy, no? But hey, I need a client-side solution; so no sessions. And cookies won’t do since they can be disabled by the user; and they get sent to the server on every HTTP request, among other downsides.

After researching our options, we found about a neat solution that does fit the situation: sessionStorage.

What is sessionStorage?

sessionStorage is one of 3 client-side data storage options introduced with HTML5. The 3 main options are sessionStorage, localStorage, and client-side databases.

It is basically an object that exists as a property of the “windows” object. You can use it to store up to 5M [most browsers] or 10M [IE] of key-value pairs to be used locally.

The sessionStorage object persists in the window [tab] in which it is being used. If you close the tab [the top-level browsing context] it will not persist. Though, it will still persist if you refresh the browser tab, or navigate to another site then use “Back” to return to the same window it is defined within.

In short, the data in the sessionStorage object is deleted when the tab [window] is closed, or upon deleting it explicitly. This makes sure the data is not stored indefinitely.

API Methods and Example Usage

The sessionStorage object ships with the following five methods:
  • getItem(key): retrieves the value for the given key or null if the key doesn’t exist.
  • setItem(key, value): sets the value for the given key.
  • removeItem(key): removes the key completely.
  • key(position): returns the key for the value in the given numeric position.
  • clear(): removes all key-value pairs.

And one property, length, used to indicate how many key-value pairs are currently stored in the sessionStorage object.

The most straightforward example to showcase sessionStorage usage would be:

//Setting a key “Name” to the value “Alice” and saving it in the sessionStorage object.
  • sessionStorage.setItem("Name", "Alice"); 
//Retrieving the value of “Name”.
  • alert(sessionStorage.getItem("Name")); 

sessionStorage vs. Cookies

The main advantages of sessionStorage over Cookies are:
  • Cookies don’t allow big objects. sessionStorage on the other hand allows for 5M [most browsers] or 10M [IE] of data.
  • Cookies get sent to the server with each HTTP request which increases the traffic; not the case with sessionStorage.

Browser Support

According to Wikipedia, sessionStorage is supported in IE8+, Firefox 3.5+, Safari 4.0+, and Chrome 4.0+

Further Reading

You can refer to this very good article on NCZOnline for more information about this important and interesting topic.

Sunday, 7 April 2013

Extension Methods in .NET


The extensions methods concept is a way to extend the functionality of any class or data type, by adding new methods to that class or data type and calling these methods directly through the instance of the class or the data type.

There are 2 important notes regarding to the extension methods:
  • You cannot define an extension property, field, or event.
  • Extension methods cannot be used to override existing methods.
Structure of Extension Methods in .NET :
  • An extension method must be marked with the extension attribute <Extension()> from the System.Runtime.CompilerServices namespace.
  • An extension method can be either a sub or a function.
  • An extension method must include at least one argument with which it must be identical to the type of the class that it will be extending. (I.e. if extending a String method, then the first parameter must be of type String).
  • An extension method must be declared within a Module. For ASP.NET , you can add a class and then change its definition to Public Module , instead of Public Class.
Open Source Libraries for .NET Extensions

There is a wide variety of hundredth of ready-made useful .net extensions provided by the community of .NET through CodePlex.
You can start using them today, just add a reference to the library from http://dnpextensions.codeplex.com/
Or even you can get this library from NuGet http://nuget.org/packages/PGK.Extensions/ and immediately start using it without any "import" statements.

Extension Method Sample

Below is a sample extension method that can be used to get the maximum length of a given EDMX EntityObject's field, as defined by the provider source ( i.e. SQL Server) , so if there is a field named 'FirstName' and defined in the database as Varchar(50) , then this extension method will return the number 50.

Imports System.Runtime.CompilerServices
Imports System.Data.Objects.DataClasses
Imports System.Data.Metadata.Edm
Module EntityFrameworkExtensionMethods
    <Extension()>
    Public Function GetMaxLength(EntityObject As EntityObject, PropertyName As String, DB As DB_DAOAs Integer
        Dim queryResult = From meta In DB.MetadataWorkspace.GetItems(DataSpace.CSpace).Where(Function(m) m.BuiltInTypeKind = BuiltInTypeKind.EntityType)
                          From p In TryCast(meta, EntityType).Properties.Where(Function(p) p.DeclaringType.Name = EntityObject.[GetType]().Name AndAlso p.Name = PropertyName AndAlsop.TypeUsage.EdmType.Name = "String")
                          Select p.TypeUsage.Facets("MaxLength").Value
        If queryResult.Count() > 0 Then
            Return Convert.ToInt32(queryResult.First())
        End If
        Return 0
    End Function
End Module
Then you can call this method normally , as it is a part of the instance EntityObject:
Dim _EmployeeRecord As New EmployeeRecord
Dim _FirstNameMaxLength As Integer = EmployeeRecord.GetMaxLength("FirstName", _DBContext)
Note that even though the Extension method has 3 parameters defined, we still call the method using 2 arguments. This is due the fact that, as mentioned above, the first parameter defined in the extension method is the type that has to be identical to the class or datatype, that is being extended.

Saturday, 6 April 2013

Must-Have Tools for Developers

As developers, our laptops and PC’s tend to be somehow “different”. We love to load them with tools and apps that we use to make our job easier. One for writing and editing code, another for analyzing performance, some personal apps, and the list goes on..

Of course, those tools differ from one developer to the other. But for a start, here’s an intriguing collection of tools and apps that every developer should have a look at: Part I | Part II

There are tools for Windows, Online Meetings, Development, Source Control, Database, Time Management, and some more.

Most of the tools here are open-source; which means that you can download and start using them for free. So go surf through the list, give your machine that nerdy look, and post your own additions and favorites in here!

Friday, 5 April 2013

Dynamic PDF Generation using Scryber

Generating PDF files is not a feature any more, in my opinion, you need to have this capability implemented be default in any application you develop. There are a lot of PDF generators around, but this one is by far the best in my humble opinion. It is called Scryber and it is an open source library.

Please refer to this article published on CodeProject to read in-depth about this important topic.

Enjoy.

Visual Studio 2012 - Update

It has been a while since my last post. Today, during my daily reading routine I came across a post introducing the latest update for VS 2012.

For you out there, who are using VS 2012 and eager to get the latest update, please refer to this post.

Enjoy.

SOLID Design Principles

SOLID is an “acronym of acronyms”. It is a set of five Object-Oriented Design principles identified and introduced by the famous Uncle Bob in the early 2000s.

Applying these principles together when creating a software system will make it easier to maintain and extend over time [well, they say!].

The five principles are: Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion.

I found this very good article on Code Project that summarizes each principle and clarifies its concept with a simple real-world comparison.

And lately, I came across a mini-series entitled “My Relationship with SOLID” on CodeofRob.

Each entry in the series elaborates on one of the five SOLID principles; and how we, developers, may or may not agree, use, and adhere to each and every one of them in our daily work.

I find this topic pretty interesting and useful. I urge you to check out the CodeProject article first to refresh your knowledge and get the sense of SOLID, then go through the series below to check the other side of it, just like I did!