Tuesday, October 27, 2020

Coding standards and Best Practices

As a developer, we would have used 75% of office time for coding. Any functionality can be coded in multiple ways. Some being the best and other may be complicated way of doing it.

According to me, the best code is something that is clean, with high quality, high performance and less rework in case of future modifications.

Write comments and documentation


This may be one of the important thing every developer should start practicing early in your career. Write proper comments to your code and add documentation header to every method. This will help other developers who works on your code to understand the algorithm and logic without going through each line of code. 

This may look like a waste of time initially but it is a great help for other developers.

Follow coding standards


Very important step in coding. Each and every language we use have defined  their set of standards to use in coding. This will help developers to follow same coding pattern.

For e.g. Using Camel case for any private variable and Pascal case or methods and classes.

I would recommend to use some tools that can help developers to check coding standards. One we become familiar, then it comes automatically. StyleCop or Resharper can be used for this.

DRY vs WET


This is one important software principle i urge everyone to follow. Don't  Repeat Yourself(DRY) principle aimed at reducing the repetition of code. Write Everything Twice(WET)  is just opposite of DRY principle.

We should try to reduce the repetition of code by moving the common piece code into reusable methods and parametrize as required. Another option can be creating a helper or a utility class and place the reusable methods and it can be used across the project.

This helps in avoiding redundant code and easy to maintain in case of future modifications.

Separation of Concern


This principle talks about segregating your code into different components or parts which performs an independent functionality. A common example would be moving all your business logics to a seperate layer or multiple classes.

Exception Handling


Proper exception handling is one of the important key for a quality application. Implement centralized error handling and try catch blocks on each method. 

Please try to log as details as possible to identify the error. Show user friendly error messages to user about the error.

Dispose Objects


When working with unmanaged resources, please make sure to dispose all the unmanaged objects after use. We can either use dispose pattern or use using statements.

Examples of such unmanaged resources are anything that executes in the control of operating system such as network connection, file objects, database connections etc..









Saturday, July 7, 2018

Angular 5 -Complete guide to build SPA(Part 4)

Routing

Routing in angular is one of the core feature which enable navigation between views based on user input. Router module is defined in @angular/router.

How it works

In single page application, there will be a master view which gets loaded when the app is rendered in browser initially. The child view gets loaded into the master view asynchronously based on the matching url structure.

The same logic applies on the child view as well in case of nested routes. 

The above image explains how routing works from higher master page level to component at lower level.

index.html is by default the initial page which gets loaded when the application gets loaded in the browser. This view contains a <app-root>  tag, which is not a normal html tag but it tells the angular router to load the bootstrapped AppComponent.

<app-root></app-root> get loaded with the app.component.html which is the bootstrapped component in our case.

app.component.html contains <router-outlet></router-outlet> which helps to load the views/components based on the routing url.

Step 1: Navigation Menu

As the initial step, i'm going to design menu navigation menu. It can be done either in app.component.html or create a new header component for better seperation.

Adding a new header component in component folder using below command.

d:\Jithin\Angular.Sample\src\app\component>ng g component header 

header.component.html

header component html looks like below.

<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target= "#appNavigationBar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Angular.Sample</a>
</div>
<div class="collapse navbar-collapse" id="appNavigationBar">
<ul class="nav navbar-nav">
<li>
<a [routerLink]="['/EmployeeDashboard']" routerLinkActive="active">Dashboard</a>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" routerLinkActive="active">Employee
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<a [routerLink]="['Employee/AddEmployee']" routerLinkActive="active">Add Employee</a>
</li>
<li>
<a [routerLink]="['Employee/EditEmployee']" routerLinkActive="active">Edit Employee</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#">
<span class="glyphicon glyphicon-user"></span> Sign Up</a>
</li>
<li>
<a href="#">
<span class="glyphicon glyphicon-log-in"></span> Login</a>
</li>
</ul>
</div>
</div>
</nav>

app.component.html

<!--header component-->
<app-header></app-header>

Step 2: Add child component

Each and every route would need a component to  be created. I'm going to create the child components based on my example.


This is how the component folder looks after adding the necessary components.

Step 3: Configuring the routes

This step is one of the important step in routing. Route configuration is done in app.module.ts .

Import the angular router module as below.
import { RouterModule, Routes } from '@angular/router';

Define the the required routes with its path and component.

const employeeChildRoutes =[
{ path: '', redirectTo: 'AddEmployee', pathMatch: 'full' },
{ path: 'AddEmployee', component: AddEmployeeComponent },
{ path: 'EditEmployee', component: EditEmployeeComponent },
];

const appRoutes: Routes = [
{ path: '', component: EmployeeDashboardComponent },
{ path: 'EmployeeDashboard', component: EmployeeDashboardComponent },
{ path: 'Employee', component: EmployeeComponent, children:employeeChildRoutes },
];

A route array can take different parameters.Below are the main 4 parameter which will come handy in any  normal application.
  1. path which defines the url structure 
  2. component associated with the path
  3. children , this helps in configuring the nested route and its again the type of route array. In the above example, you can see employeeChildRoute which is of type route array is assigned as children of Employee path.
  4. canActivate  is useful  when you want to perform some pre-processing logic before activating the route. Eg: if you want to restrict the page access for logged in user alone, this check can be done using canActivate with the help of an authgaurd.
Add the routes into the imports array. Modify the import array like below.

imports: [
BrowserModule,
RouterModule.forRoot(appRoutes, {useHash: true})
],

There are different location strategy available in angular. In this example , I'm using HashLocationStrategy. {useHash: true}

4. <router-outlet> tag in parent components

Place <router-outlet></router-outlet> tag in all your  parent component which loads the child component based on the route.

In above example, i have placed the above tag in AppComponent and EmployeeComponent which are my parent components according to the defined route.

<!--header component-->
<app-header></app-header>

<router-outlet></router-outlet>

Output 

The final output of above code looks like below.











Saturday, June 2, 2018

Angular 5 -Complete guide to build SPA(Part 3)

Project Structure



When we create a project in angular using angular CLI, It creates the required project structure with all necessary components/files.

Please have a look at the sample project which i created -  Angular.Sample below.



node_modules

node_modules contains all the modules that are part of angular and it can be imported into the project as per need. 

src

src is the source folder which meant to keep the application files. It depends on developer how to organize files in this folder.

It contains an app folder where i am going to place the all the application files. I would like to add this with 5 folders to place components, services, model,pipes and any custom directive. Please refer below.




  • component folder can be used to place all the components.
  • service for app related services.
  • model contains the model.
  • directive can be used to place any utility components like alert component and 
  • pipes are custom filters which can be used apply any transformation logic while data binding.
Again i would like to add that this folder structure depends on the developer how he wants to organize the files for better maintainability.

app.module.ts

app.module.ts contains application module. This application module class defines how different parts of your angular application fit together. We can define any number of modules based on the size of the application and how you want to separate your application into different modules. An angular application contains at least one module which is used to bootstrap the AppComponent and it helps to launch the application.

App module is decorated with NgModule and all the components/services/module which is configured in app module is available for entire application.



The above image is a sample app,module defined in angular app. All the new component which we create should be added to the declaration array.

Imports help you inject any dependencies to the application globally. Providers are used to inject the services.

Routing cofiguration using angular router is done through AppModule and it is imported into the imports array. We can discuss more about routing later.

environments

environments helps to add application configuration related to different deployment environments. This can related to a web.config file.


When creating a new project, it comes with 2 environment files. environment.ts for development and environment.prod.ts for production.

Developer has the freedom to add any number of environments. I would like to add one more environment file environment.qa.ts which will be used for my testing environment.

This how my  environment folder looks like now.


After adding a new environment, same should be added to environment array in .angular-cli.json which is the configuration file for entire angular application. Please refer below.

"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts",
"qa": "environments/environment.qa.ts"
}

When we are building the angular application, we can give the environment name in build command so that it takes the related environment configuration from environment file.

Please refer below example on building the angular app with qa environment file which we added above.


ng build -qa (or) ng build --environment=qa

favicon.ico

favicon.ico is the icon which will be used for the angular application

index.html

index.html is main html file which gets loaded into the browser when running an angular application. All the other components gets loaded inside the <app-root></app-root> based bootstrapped module. By default, AppComponent gets loaded and it can be changed in AppModule.

main.ts

main.ts contains the configuration like what is the app module and what are the available environments for the application to work on. This is starting point of execution and the actual bootstrapping happens here.

pollyfills.ts

This file contains all the polyfills required by angular and this loaded before the app. Angular might not work properly on the older versions of browsers or it may work differently. To solve this issue, developer can include the pollyfills required based on the browser version from this file.

styles.css

This file can be used place any css styles that applies globally to entire angular application.

.angular-cli.json

.angular-cli.json is the json configuration file related to the angular project. This helps you configure everything related to the app starting name of the project to build-ouput folder.

There are other files also in the project related to testing the angular app.

We will be discussing about angular routing which is the core of  SPA in the next blog.





Sunday, March 11, 2018

Angular 5 - Complete guide to build SPA (Part 2)

Angular Architecture


One of the major design considerations in angular is to reduce the size of the final bundle, with this, some of the libraries that are required for angular app to work are provided through core libraries, and other optional libraries can be  imported as per needs.

Components are the basic building blocks of angular applications, this uses other dependencies like services, directives etc to perform its task.

Below architecture diagram can give a better idea on how each parts interact each other.




Modules

Angular Modules contains different parts of the application and are the way to group related component, services, directives and pipes to a single unit.

Component

Major development in angular is done using component. Each component is linked to view. It can be viewed as a reusable component as well.

Components are part of ngModules and each component can use other components as well. It can be viewed as a tree structure.

Template represents the html view and it communicates with the component through property and events.

Services are nothing but reusable functions that are separated from components but can be injected through dependency injection. This is very useful when you want to use same methods or properties in multiple places.

Routing

When it come to Single Page Application(SPA), we often hear angular associated with it. Angular is designed to mainly with the objective of SPA. Angular router framework evolved over the years and become a well matured framework to support all needs of SPA.

Routing works based on the URL structure. It allows us to define the routes and its corresponding components using a Route array.  When the URL matches the defined route, its component get loaded in to main template.

Saturday, March 3, 2018

Angular 5 - Complete guide to build SPA (Part 1)

Angular 5 - Introduction

The purpose of this blog is to provide complete details about building an angular app using typescript and Angular CLI. 

Angular CLI is the new command line interface introduced with angular which helps the developer in the development process. It helps to create, build, run and test the required components through CLI commands.  

Why Angular 5?

Many developers who are familiar with previous version of angular like Angular JS, Angular 2/4 would certainly have doubts in their mind about this. Why angular 5?

To answer this, we need to compare each of these and what new changes have been introduced with  new version. There is a major difference in features with angular js and angular versions but angular 2,4 and 5 are almost same with some improvement iterations in the higher versions.

Angular JS vs Angular

Angular is a major update over angular js in terms of syntax as well as functionality.

  1. JavaScript vs TypeScript   -  Angular is written using TypeScript which is the superset of  JavaScript. It takes the advantage that typescript is the only typed language that compiles into javascript. TypeScript makes code easier to read and understand.
  2. Component based Architecture   - Angular application architecture helps to create components that don't depend on each other, which are loosely coupled as possible.
  3. Mobile Oriented Architecture- Angular was designed keeping in mind about the present needs. It designed a framework that can support both mobile app development as wells as web apps. NativeScript helped in angular mobile development faster and effective.
  4. View Engine -  The new view engine introduced helps in generating a smaller code using Ahead of Time (AOT) manner. 
  5. Animation Package - Animation package was removed from the core package in angular. This was because most of the applications doesn't use animations, so this can be removed from core package which will help to reduce the size of the build. This was also done thinking about mobile application development.
  6. Perfomance  - Angular applications are smaller and faster. It consumes less space and run faster which helps in increasing the overall performance of the application.
These differences listed above are with respect to angular js. There are not much difference in Angular 2 , 4 or 5. Its just the performance improvements or the minor functionality improvements. 

Why Angular 4 Not 3?

This would be a question in all developers mind why not 3 after angular 2.

Answer  is simple and it was nothing related to any functionalities introduced, but with the versioning of packages. 

Please refer below image:


When angular 2 was released, the version of angular/router package was already 3. This created some confusion in the developer mind regarding the versions. 

In order to make the versions of the packages same, version 3 was skipped and all the packages were versioned as 4 in the next major release. 

We will be discussing about angular architecture and development environment setup in next blog.


Tuesday, November 12, 2013

Performance Tuning Techniques for your web page

Some basic performance tuning techniques are shared below.

Minimize HTTP Requests:
Most of this time is tied up in downloading all the components in the page: images, style sheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.
To reduce the number HTTP requests, we can combine  the scripts into a single script page and refer that script in the page.
Loading the scripts in parallel:
          What we usually do is include script files as static links in head tag as shown below.
<head>
    <script type="text/javascript" src="Scripts/JQueryUI/jquery-1.9.1.js "></script>
    <script type="text/javascript" src="Scripts/JQueryUI/jquery-ui-1.10.1.js "></script>
</head>

What browsers usually do is download them serially one after the other. The browsers like IE or Firefox will wait for the first script to get downloaded before it starts downloading second one.
We can make them to download  in parallel by the below code.

<script type="text/javascript">
        document.writeln("<script src='Scripts/JQueryUI/jquery-1.9.1.js ?version=1.0
 ' type='text/javascript'><" +
                         "/script>");

        document.writeln("<script src='Scripts/JQueryUI/jquery-ui-1.10.1.js ?version=1.0
 ' type='text/javascript'><" +
                         "/script>");
</script>



Avoiding the Cache Problem:
          What most of the browsers do is that for the first time they download scripts to webpage but after that they take the script from the browser cache.so sometimes even if we make changes in the script and the style sheet ,that is not getting downloaded and changes are not reflecting.
                We can force the browser to download the latest version of script and style sheet by versioning them.

<script type="text/javascript">
        document.writeln("<script src='Scripts/JQueryUI/jquery-1.9.1.js ?version=1.0
 ' type='text/javascript'><" +
                         "/script>");

        document.writeln("<script src='Scripts/JQueryUI/jquery-ui-1.10.1.js ?version=1.0
 ' type='text/javascript'><" +
                         "/script>");
</script>


<link href="Styles/includes.css?version=1.0" rel="stylesheet" type="text/css" />

We have to increment the version number if we make changes to that script or style sheet.

<script type="text/javascript">
        document.writeln("<script src='Scripts/JQueryUI/jquery-1.9.1.js ?version=1.1
 ' type='text/javascript'><" +
                         "/script>");

        document.writeln("<script src='Scripts/JQueryUI/jquery-ui-1.10.1.js ?version=1.1
 ' type='text/javascript'><" +
                         "/script>");
</script>


<link href="Styles/includes.css?version=1.1" rel="stylesheet" type="text/css" />





Bundling and Minification:
                Bundling and Minification is the new feature included ASP.NET 4.5 to improve request load time.
To use Bundling and Minifcation, we have to add reference to System.Web.Optimization dll.
public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
           
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-1.7.min.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
}
}
The bundled scripts can be rendered by the following code in html page.
  @System.Web.Optimization.Scripts.Render("~/bundles/modernizr")  
   

  @System.Web.Optimization.Scripts.Render("~/bundles/jquery")

SQL Server Parameter Sniffing:
                Parameter sniffing allows you to reduce the time taken to execute the stored procedure considerably.
This permits individual plans recompilation instead of compiling entire execution plan for single store procedure. You could find below some workaround when you are affecting by a performance issue.
       
                Using dummy variables that are not directly displayed on parameters also ensure execution plan stability without need to add recompile hint.

create procedure SearchProducts
    @Keyword varchar(100)
As
Declare @Keyworddummy as varchar(100)
Set @Keyworddummy = @Keyword
select ProductID,ProductName  from Products where Keyword like @Keyworddummy
end


                Here  the parameter @Keyword is assigned to @ Keyworddummy is which is used inside the stored procedure. Like this you can do for all the parameters that are used inside the stored procedure.

Always use the column name in the select list. Avoid using * in select.
This helps you to reduce the execution time considerably and get results faster.

Monday, February 25, 2013

Object Oriented JavaScript

   Some basic concepts in Object oriented JavaScript’s are discussed below
  <input type="button" id="btnCheck" onclick="GetData();" />

We have a button that calls a client side function GetData() on its click.

<script language="javascript" type="text/javascript">

    function GetData() {

        testBL.getTestData();

//calling function in testBLL.js
//with object testBL and function getTestData()
    }
    
   
    </script>


Now we will have to create testBLL.js

In this we can create the methods and expose those methods


Code in testBLL.js:


var testBL = new function () {

    ObjectOreientedScripttest = function () {

//you can write your function code here

    },


getTestDataByDate = function () {
   

//you can write your function code here


}



    return {

        testForObjectOreientedScript:ObjectOreientedScripttest ,
        getTestData: getTestDataByDate
    }

} ();

This return statement is mandatory to expose those methods.

For eg:
Inside the return statement we have the below statements

 getTestData: getTestDataByDate

 
getTestDataByDate  is the function we have created in the testBLL.js and second one getTestData is the name that we get when we are calling the method.

 I.e.    testBL.getTestData();


testBL is the variable name that we used for testBLL.js functions(refer first line testBLL.js)