Friday, September 28, 2012

Code optimization and Best practices for ASP.Net C# Developers


Last week I had a good time with code review, all the guys who did coding are 3-4 years of experience in Microsoft technologies. But still there is scope for Optimization and best practice. Here in this blog post I’ll show you some of them.

1] A field can be made read-only

Consider the following example, Admin_Settings class has a private object ObjDB (an object of class Database)
Code:
public partial class Admin_Settings : System.Web.UI.Page
{
    private Database ObjDB = new Database();
}
Here, this object can be Readonly, by marking this readonly, we get to ensure that this class will not inadvertently modify this object anywhere within its methods.
Code:
private readonly Database ObjDB = new Database();
The same can be applied for Variables if they they are only being assigned in the constructor and offers to create an additional safeguard



2] Use 'var' keyword when initializer explicitly declares type

The var keyword is fairly contentious in terms of usage, but if there’s one instance where its use is sensible, it’s in initializations alike to the following:
Code:
DataSet DsPaidAmount = new DataSet();
Since the type is declared on both left and right-hand sides of the initialization statement, I suggest to remove the type on the left-hand side and replace it with var, i.e.:
Code:
var DsPaidAmount = new DataSet();
Or even further, you can remove redundant initializer and write it as
Code:
 DataSet DsPaidAmount;


3] Use declaration closer to usage


Consider the following example, where many variables are declared which are not really closer to usage. The Database object DsPaidAmount is declared at the top, and used at the very bottom (so, declaration and usage are not closer).
Code:
public void Receipt()
{
        double PreviousPaidAmount = 0;
        double TaxAmount = 0;
        //variable declared here
        DataSet DsPaidAmount;
        double TotalAmount = 0;
        double PreviousDiscount = 0;
        
        . . . . . . 
        . . . . . . 

        if (some condition)
        {
            . . . . . .
            . . . . . .
        }
        else if (another condition)
        {
            . . . . . .
            . . . . . .
        }
        else if (!another condition)
        {
            . . . . . .
            . . . . . .
        }

        if (statement > 0)
        {  
            //Variable used here! tooooo far from declaration            
            DsPaidAmount = ObjReceipt.GetPaidAmount(somevalue);
        }
        else
        {
            //statement
        }
}
Here, we can move declaration closer to it’s usage, as follows:
Code:
if (statement > 0)
{  
    //Declared and used at same place!
    DataSet DsPaidAmount = ObjReceipt.GetPaidAmount(somevalue);
}
else
{
    //statement
}

Further, for better memory management we can use the “using” constructor, and also remove the type on the left-hand side and replace it with var as follows:
Code:
if (statement > 0)
{  
   using (var DsPaidAmount = ObjReceipt.GetPaidAmount(somevalue))
   {
       // some statements
   }
}
else
{
   //statement
}


4] Remove unneeded 'else' keyword

Some if-else conditions can have their else clause removed. Consider the following method:
Code:
public double roundNum(double num)
{
   double floorValue = Math.Floor(num);
   if ((num - floorValue) > .5)
   {
      return (floorValue + 1);
   }
   else
   {
      return (floorValue);
   }
}
In the above, the else statement can be safely removed because its if clause returns from the method. Thus, even without the else, there’s no way you’ll be able to proceed past the if clause body. We can write it as follows:
Code:
public double roundNum(double num)
{
   var floorValue = Math.Floor(num);
   if ((num - floorValue) > .5)
   {
      return (floorValue + 1);
   }
   return (floorValue);
}
Even better; we can write it by converting it to “?:” operator
Code:
public double roundNum(double num)
{
   var floorValue = Math.Floor(num);
   return (num - floorValue) > .5 ? floorValue + 1 : floorValue;
}


5] Join declaration and assignment

Consider the following example, where Type can use Implicitly typed local variable declaration and Join declaration and assignment
Code:
if (Page.IsValid)
{
     List<string> ServiceList = new List<string>();
     ServiceList = GetChecked(ChkService);
}
Finally by removing redundant initalizer, using Implicitly typed local variable declaration, joining declaration and assignment and with a good naming convention for local variables, we can write this as follows:
Code:
if (Page.IsValid)
{
   var serviceList = GetChecked(ChkService);
}


6] Convert “IF” statements with “?:” operator

Consider the following example
Code:
if (GvVisit.Rows.Count > 0)
{
   BtnCompleteFollowUp.Visible = true;
}
else
{
   BtnCompleteFollowUp.Visible = false;
}
Can be written with pretty optimized version using “?:” operators as follows:
Code:
BtnCompleteFollowUp.Visible = GvVisit.Rows.Count > 0 ? true : false;
Or even better by removing unneeded conditional ternary expression usage. Since condition returns a boolean value
Code:
 BtnCompleteFollowUp.Visible = GvVisit.Rows.Count > 0;

Saturday, September 15, 2012

Best Practices for ASP.NET MVC 3 - Model Suggestions

This blog post presents a set of coding guiding principle intended at helping the ASP.NET MVC developer build concrete applications. Of course, it's up to you as the developer to choose which of these guiding principles are suitable for your application

Model Suggestions


The model is where the domain-specific objects are defined. These definitions should include business logic (how objects behave and relate), validation logic (what is a valid value for a given object), data logic (how data objects are persisted) and session logic (tracking user state for the application).

DO split the model its own project with a separate assembly.

For applications with a large complex model, it's a good initiative to create a separate assembly for the model to avoid accidentally mixing concerns. You can then reference the model assembly in your ASP.NET MVC project

DO place all business logic in the model.

If you put all business logic in the model, you protect the view and controller from making business decisions concerning data. You also harvest the following profits
  • Fewer duplicated business logic
  • The view is easier to read when there is no business logic present
  • Testing business rules is out-of-the-way to the model
For example, if you have a business requirement to display a user's full name, you could put the logic in the view as follows
@if (String.CompareOrdinal((string)TempData["displayFullName"], "on") == 0)
    { 
        <text>Model.firstName, Model.lastName</text>
    }
    else
    {
       <text> Model.firstName</text> 
    } 
However, you would have to duplicate this logic in every place this business requirement was needed. Instead, you could put the business logic in the “display Full Name " rule in the model by adding a property to the model that encapsulates the business logic as follows
public string combinedName
{
   get
   {
       return (displayFullName ? firstName + " " + lastName : firstName);
   }
   private set
   {
      ;
   }
}
This would greatly simplify the view as shown
<p>Welcome,  @Model.combinedName</p>

DO place all validation logic in the model

All input validation should occur in the model layer. This includes client side validation, which is essential to performance. However, client side validation can be circumvented (with, for example, tools like Fiddler)
You can use ModelState to add validation checking. The following example shows how to add validation checks to ModelState explicitly
if (String.IsNullOrEmpty(pageName))
{
   ModelState.AddModelError("pageName", Resources.AddPage.PageNameError);
}  

Nevertheless, given the advances in .NET Framework, the System.ComponentModel.DataAnnotations should be the favored method for validation. These annotations are added as attributes to the properties of a model class, as the following example shows
public class Page
{
   [Required(ErrorMessageResourceName = "nameRequired", ErrorMessageResourceType = typeof(Resources.Page))]
   public String pageName { get; set; }
       ...
}


DO define interfaces for data access

It is favored that interfaces be used to expose methods on a provider for data access. This strengthens the loosely coupled component design of ASP.NET MVC.
Consider using the Entity Framework or LINQ to SQL as the means of creating wrappers around calls to a database. Both Entity Framework and LINQ to SQL allow the use of stored procedures as well

DO place all session logic in the model.

It is outside the scope of this blog discussion to travel around in depth the different mechanisms for storing session state in the model. As a starting point, here are a few of possibilities of session state storage:
  • In Process
    • Strengths : No extra setup needed.
    • Weaknesses : Does not work if the web site needs to balance
  • Session State Service
    • Strengths : Lightweight service runs on each machine in a web farm. Faster than database session storage
    • Weaknesses : Session data is lost if the service goes down
  • Database
    • Strengths : Session data is persisted
    • Weaknesses : Slower than session state, Management cost is relatively high
In Next Blog Post, I'll discuss on View Suggestions
Happy Coding!!

Friday, September 14, 2012

Useful Online Tools for Web Designers and Developers - Part 2

Color Scheme Designer

Color Scheme Designer is an easy to use and efficient tool that can help you choose color schemes for your designs.

Kuler

Similar to Color Scheme Designer, Adobe Kuler is an internet application from Adobe that lets you create and save various color schemes.

Typetester

Typetester is an online application for comparison of the fonts for the screen. Its primary role is to make your life (as a web designer) easier when dealing with web fonts.

Pixlr

Pixlr is a free online photo editor. If you just need something to edit, adjust or filter your images, then Pixlr is the tool you’re searching for.

Browsershots

Browsershots is an online web application that provides developers a convenient way to test their website’s browser compatibility in one place. It can help you to make screenshots of your web design in different operating systems and browsers

Pingdom

Pingdom offers an online tool that can help you test the load time of a web page. Just enter a URL and test the load time of all elements on that page.

Iconfinder

This isn’t really a tool, but Iconfinder is a must-have. Just consider it as your number one “search tool” for free icons.

Code beautifier

As its name says, Code beautifier is a CSS formatter and optimiser tool.

CSS3 Please

Need an online place where you can test your CSS3 skills? Then here’s your playground!

Useful Online Tools for Web Designers and Developers - Part 1

Free Online 3D CSS Button Generator


Loading CSS spinners and bars generator for AJAX & JQuery


0 to 255

0to255 is a simple tool that helps web designers find variations of any color.

Spritebox

Spritebox is a WYSIWYG tool to help web designers quickly and easily create CSS classes and IDs from a single sprite image. It is based on the principle of using the background-position property to align areas of a sprite image into block elements of a web page. It was made using a combination of JQuery, CSS3 and HTML5, and is totally free to use!

JsFiddle

JsFiddle is a playground for web developers, a tool which may be used in many ways. One can use it as an online editor for snippets build from HTML, CSS and JavaScript. The code can then be shared with others, embedded on a blog, etc!


Frame Box

Frame Box is an easy to use online tool for creating and sharing wireframes

CSS3 Generator

CSS3 Generator is a simple tool that creates some cross-browser CSS3 code based on whatever values you want.

ProCSSor

ProCSSor is a powerful (and wholly free) CSS prettifier that lets you format CSS in the exact way you want. It empowers you to turn your CSS into something that is visually more compelling, and with a minimum of effort at that.

Super Conversion Button

This little tool let’s you easily create a beautiful, effective call-to-action button in seconds

wordmark.it

Wordmark.it is a tool that lets you quickly preview how a wordmark looks with the fonts installed on your computer before setting out to find new ones.

Thursday, September 13, 2012

Faster and Efficient Development with Visual Studio 2010 Extension Manager

In the last few years, Visual studio has been evolved much. VS 2010 has been shipped with pretty good features. Most of them are useful for developers to increase their programming efficiency, build better solutions on web space.
In this Blog post, I’ll show you how to extend the Development environment with Visual Studio 2010 Extension Manager and Stack of Tools that helps you for Coding, Best practices, Advanced Intellisense, Optimization, API reference and Deployment on web space.

Installing and Managing Visual Studio Tools and Extensions


The Visual Studio 2010 Extension Manager lets you install a range of tools and extensions for Visual Studio. To open Extension Manager, on the Tools menu, click Extension Manager as show in following figure
You can also download extensions from Web sites, or get them from other developers.
The Extension Manager window is divided into three panes. The left pane lets you select by group: installed extensions, new extensions from the online gallery, or updates to installed extensions.
The extensions in the selected group are displayed in the middle pane. You can use various filters to sort the list

Online Gallery

Extension Manager can install extensions from the Visual Studio Gallery on the MSDN website. These extensions may be packages, templates, or other components that add functionality to Visual Studio.
Extension Types
Extension Manager supports extensions in the VSIX package format, which may include project templates, item templates, toolbox items, Managed Extension Framework (MEF) components, and VSPackages. Extension Manager can also load and install MSI-based extensions, but it cannot enable or disable them. Visual Studio Gallery contains both VSIX and MSI extensions.
Dependency Handling
If a user tries to install an extension that has dependencies, the installer verifies that those dependencies are already installed. If they are not installed, Extension Manager shows the user a list of dependencies that must be installed before the extension can be installed


Visual Studio Tools and Extensions

NuGet Package Manager (Free)

This is a collection of tools to automate the process of downloading, installing, upgrading, configuring, and removing packages from a VS Project. You can download and install it via the Extension Manager (search for NuGet Package Manager to find it) as shown in following figure

Indent Guides (Free)

Adds vertical lines at each indent level. Displays indent guides in Visual Studio text editor windows.

Guides can be displayed at the indent specified in your settings, regardless of tabs or spaces, or wherever text has been indented to as shown in following figure


Indent Guides

There are three styles of guides: solid, dotted and dashed, available in thin and thick varieties and customizable color. The default is dotted teal, as shown in the image. Each indent level can have a different style and color.

The deepest guide that includes the block with the caret is displayed in a different color or a glow, to help you find the start and end of your code. Guides can be shown and customized for any language in Visual Studio. It reads the spaces, not the code.



PowerCommands for Visual Studio 2010 (Free)

PowerCommands 10.0 is a set of useful extensions for the Visual Studio 2010 adding additional functionality to various areas of the IDE

Web Standards (Free)

Web Standards Update provides the much wanted HTML5 & CSS3 support to Visual Studio 2010 SP1. It brings VS 2010 intellisense & validation as close to W3C specification as we could get via means of an extension. The most notable supported features by this extension are:.

HTML5 – Video, Audio, Input Type, Drag & Drop, WAI-ARIA, Microdata, Schema.org
Browser API – GeoLocation & Local Storage
CSS3 – 2D Transforms, 3D Transforms, Animations, Background & Borders, Basic Box Model, Basic UI, Behavior, Color, Flexible Box Layout, Fonts, Paged Media, Hyperlink Presentation, Line, Lists, Marquee, Media Queries, Multi Column, Namespaces, Presentation Levels, Ruby, Selectors, Speech, Syntax, Template Layout, Text & Transitions. It also supports vendor specific prefixes like –ms, -webkit & -moz.

CodeMaid (Free)

CodeMaid is an open source Visual Studio extension to cleanup, dig through and simplify our C#, C++, XAML, XML, ASP, HTML, CSS and JavaScript coding

Image Optimizer(Free)

A Visual Studio extension that optimizes PNG, GIF and JPG file sizes without quality loss. It uses SmushIt and PunyPNG for the optimization

Adds a right-click menu to any folder and image in Solution Explorer that let's you automatically optimize all PNG, GIF and JPEG files in that folder. The optimization doesn't effect the quality of the images, but optimizes them using industry proven algorithms for removing EXIF and other metadata. The extension uses SmushIt and PunyPNG for optimizing the images

GhostDoc (Free)

GhostDoc is a Visual Studio extension that automatically generates XML documentation comments for methods and properties based on their type, parameters, name, and other contextual information

CSSCop (Free)

CSSCop helps you write better and more browser compatible stylesheets. It uses the CSS Lint (csslint.net) rules engine and is completely customizable

CSS Is Less (Free)

Make .less files load with the CSS language service.

Monday, September 3, 2012

Google Like Buttons - A simple CSS

I’m not a CSS guru, but recently I stared playing on this stuff. Just for a snooping, I created Google like small buttons with Icons. 

You can download the necessary 24X24 .png images from Small Gray Images

And add the following styles into you CSS. I’m using this style for Button and Anchor tags. You can customize it based on your UI requirement

btn  { float: left; padding-bottom: 5px; clear: both; }
input[type="submit"].btn, a.btn { color: #6e6e6e; font: normal 11px Helvetica, Arial, sans-serif; text-decoration: none; padding: 5px 12px; position: relative; display: inline-block; text-shadow: 0 1px 0 #fff; -webkit-transition: border-color .218s; -moz-transition: border .218s; -o-transition: border-color .218s; transition: border-color .218s; background: #f3f3f3; background: -webkit-gradient(linear,0% 40%,0% 70%,from(#F5F5F5),to(#F1F1F1)); background: -moz-linear-gradient(linear,0% 40%,0% 70%,from(#F5F5F5),to(#F1F1F1)); border: solid 1px #dcdcdc; border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px; margin-right: 10px; }
input[type="submit"].edit, a.edit { background: url(Images/edit.png) no-repeat #f3f3f3; padding-left: 30px; }
input[type="submit"].trash, a.trash { background: url(Images/delete.png) no-repeat #f3f3f3; padding-left: 30px; }
input[type="submit"].publish, a.publish { background: url(Images/publish.png) no-repeat #f3f3f3; padding-left: 30px; }
input[type="submit"].details, a.details { background: url(Images/details.png) no-repeat #f3f3f3; padding-left: 30px; }

We can make Bigger images just by adding Font-size and Padding attributes as follows

input[type="submit"].edit-big, a.edit-big { background: url(themes/Images/edit.png) no-repeat #f3f3f3; font-size: 16px; padding: 10px 15px 10px 35px; }


For your Buttons / Anchors add the class attribute as follows

<input type="submit" value="Edit" class="btn edit"/>

<a class="btn edit" href="#">Edit</a>


Finally your Buttons / Anchors looks like as follows: