Friday, 7 September 2018

Parent-Child class declaration and initialization

using System;

namespace CSharpDemo
{
    public class A
    {
        public void print()
        {
            Console.Write("A \n");            
        }

        // private method decalaration
        private void securePrint(){
            Console.Write("secure print A \n");
        }

        public void allowPublicAccessToSecurePrint(){
            this.securePrint();
        }
    }

    public class B : A
    {
        public void print()
        {
            Console.Write("B \n");
        }

        // base keyword will allow to access parent class's public methods
        public void printFromA(){
            base.print();
            //// parent's private methods are not accessible in child
            //// base.securePrint();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A aa = new A();
            aa.print(); // -------------------------------------------- output: A
            //// private member not accessible
            //// aa.securePrint();
            aa.allowPublicAccessToSecurePrint(); //-------------------- output: secure print A

            A ab = new B();
            ab.print(); // -------------------------------------------- output: A
            ab.allowPublicAccessToSecurePrint(); //-------------------- output: secure print A

            //// below code will give you compile time error
            //// An explicit conversion exists (are you missing a cast?) 
            //// B ba = new A();
            //// ba.print();

            B bb = new B();
            bb.print(); // -------------------------------------------- output: B
            bb.printFromA(); // --------------------------------------- output: A
            bb.allowPublicAccessToSecurePrint(); //-------------------- output: secure print A
        }
    }
}

Sunday, 24 June 2018

Some basic dotnet core command for beginners

Install framework .Net Core 1.X or 2.X from Microsoft website.

go to command line interface

1) Check dotnet framework version
dotnet --version

2)create new dotnet project
dotnet new classlib | MVC | console  -o myFirstProj
where classlib, MVC, console are project type.

This command will create new project at current directory as per given argument.
using this command you can create new class library, MVC web application or console appliation.

3)Create solution and add project to that solution.
First create folder with name, which you want to give to solution.
now run command "dotnet new sln"
this command will create new solution file with same name as folder.

now create new project in that folder using command line interface.

To add that project to solution use below command
dotnet sln myFristSln.sln add myFirstProj/myFirstProj.csproj

To remove project from solution run below command
dotnet sln myFristSln.sln remove myFirstProj/myFirstProj.csproj

4) To resotre all packages/dependencies for all projects run below command
dotnet restore

5) To build solution file
dotnet build
build will restore packages first. To skip packages restore use "dotnet build --no-restore".

6) To run your project in your solution
dotnet run --project myFirstProj.csproj

To run single project only use "dotnet run" command.

7)To run test cases
dotnet test

8) To pack and publish your application for deployment run below command
dotnet publish

9) Help for any command
dotnet <command> -h

Monday, 25 September 2017

expressjs API with tedious and SQL server connection

In below example I have used node.js, express js and tedious.
for more details about tedious go to tedious

/*
* Install below packages using node package manager
* 1) $ npm install express --save
* 2) $ npm install tedious --save
*
* Run Application using
* $ node index.js
/
                (function () {
    var express = require('express')
    var app = express()
    
    app.get('/', function (req, res) {
    
        // tedious package is used for SQL server connection
        var Connection = require('tedious').Connection;
        var Request = require('tedious').Request;
    
        // add SQL server configurations here
        var config = {
            server: '[server_name]',
            userName: '[user_name]',
            password: '[password]',        
            options: {            
                instanceName: '[instance_name]',
                database: '[database_name]'            
            }
        }
    
        var connection = new Connection(config);
    
        connection.on('connect', function (err,resp) {
            if (err) {
                console.log(err);
            } else {
                executeStatement(resp);            
            }
        });
    
        function executeStatement(resp) {
            // add SQL query here
            request = new Request('select * from [table_name] with (nolock)', function (err, rowCount) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(rowCount + ' rows');
                }
                connection.close();
                // return rowCount from API
                res.json(rowCount);
            });
    
            // row iteratore for result
            request.on('row', function (columns) {
                columns.forEach(function (column) {
                    if (column.value === null) {
                        console.log('NULL');
                    } else {
                        console.log(column.value);
                    }
                });
            });
            
            // execute query
            connection.execSql(request);        
        }
    });
    
    var server = app.listen(5000, function () {
        console.log('Server is running..');
    });
})();

Tuesday, 19 September 2017

Best Loader in Angularjs

Add Loader to your application using http request interceptor.
Here for Loader will continue till any of your http request is running.
As soon as all requests are return, loader will disapear.
Here we have used Interceptors for HTTP requests. For more details visit here

index.html

<div ng-class="{'modal-color': isShowLoader}"></div>
<!-- add background modal color-->
<div ng-class="{'loader': isShowLoader}"></div>
<!-- add loader-->


style.css

Add style for classes .loader and .modal-color for laoder design.

app.controller.js

$rootScope.$on('loading:progress', function () {
// show loading gif
  $scope.isShowLoader = true;
});

$rootScope.$on('loading:finish', function () {
// hide loading gif
  $scope.isShowLoader = false;
});


app.interceptor.js

app.factory('httpRequestInterceptor', ['$rootScope', '$q', function ($rootScope, $q) {

var loadingCount = 0;

return {

  request: function (config) {
   if (++loadingCount === 1) {
    $rootScope.$broadcast('loading:progress');
   }
   return config || $q.when(config);
  },

  response: function (response) {
   if (--loadingCount === 0) {
    $rootScope.$broadcast('loading:finish');
   }
   return response || $q.when(response);
  },

  responseError: function (response) {
   if (--loadingCount === 0) {
    $rootScope.$broadcast('loading:finish');
   }
   return $q.reject(response);
  }
 };
}]);

Wednesday, 3 August 2016

Custom JSON Response class for MVC

Custom JSON Response class for MVC


using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Demo.Util
{
/// <summary>
/// A Newtonsoft.Json based JsonResult for ASP.NET MVC
/// </summary>
public class CustomJsonResult : ActionResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

/// <summary>
/// Initializes a new instance of the <see cref="JsonNetResult"/> class.
/// </summary>
public CustomJsonResult()
{
this.SerializerSettings = new JsonSerializerSettings();
}

/// <summary>
/// Gets or sets the content encoding.
/// </summary>
/// <value>The content encoding.</value>
public Encoding ContentEncoding { get; set; }

/// <summary>
/// Gets or sets the type of the content.
/// </summary>
/// <value>The type of the content.</value>
public string ContentType { get; set; }

/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data object.</value>
public object Data { get; set; }

/// <summary>
/// Gets or sets the serializer settings.
/// </summary>
/// <value>The serializer settings.</value>
public JsonSerializerSettings SerializerSettings { get; set; }

/// <summary>
/// Gets or sets the formatting.
/// </summary>
/// <value>The formatting.</value>
public Formatting Formatting { get; set; }

/// <summary>
/// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
/// </summary>
/// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;

response.ContentType = !String.IsNullOrWhiteSpace(this.ContentType) ? this.ContentType : "application/json";

if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}

if (this.Data != null)
{
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;

response.Write(JsonConvert.SerializeObject(Data, isoConvert));

JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = this.Formatting };

JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings);
serializer.Serialize(writer, this.Data);

writer.Flush();
}
}
}
}

Friday, 13 May 2016

WCF Basics :

WCF basic concepts :

SOAP

  • Simple Object Access Protocol
  • HTTP/HTTPS/SMTP
  • Only XML
  • web service security (ws-security)
  • WSDL (Web Services Description Language), XSD (XML Schema definition)

REST

  • Representational State Transfer
  • HTTP/HTTPS
  • text, JSON, XML
  • No ws-security
  • No WSDL, XSD

Interface has below annotation:
[ServiceContract]
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]

Only those methods are interacted outside which has annotation [OperationContract]
[OperationContract] => methods in interface
[OperationContract(IsOneWay=true)] => not wait for response

Below annotation is used to invoke methods:
[WebInvoke(Method="GET/POST/PUT/DELETE",
RequestFormat=WebMessageFormat.Json/Xml,
ResponseFormat=WebMessageFormat.Json/Xml,
UriTemplate="MethodName/{ParameterName}")]

To return fault, use fault contract:
[FaultContract(typeof(InvalidOperationException))]

Add below annotation on your data contract class:
[DataContracrt] => data class

Only those properties are interacted outside, which has [DataMember] annotation.
[DataMember] => property in class

Message contracts are rarely used.
[MessageContract] //Message Contract
[MessageHeader]
[MessageBodyMember]


Various binding protocols:

Example of different types of bindings supported by WCF.

<add binding="basicHttpsBinding" scheme="https" /> => For SOAP service
<add binding="wsHttpsBinding" scheme="https" /> => For SOAP service (Web service security)
<add binding="webHttpBinding" scheme="http" /> => For REST service

Custom Binding configuration

Service endpoint contains 3 parameters:

  1. address: URL address of service
  2. binding: binding type
  3. contract: Interface name
Here we have created custom binding configuration "LargeWeb" for webHttpBinding.
And assign that "LargeWeb" binding configuration in services section.

<bindings>
  <webHttpBinding>
    <binding name="LargeWeb"
             maxBufferPoolSize="1500000"
             maxReceivedMessageSize="1500000"
             maxBufferSize="1500000"
    openTimeout="00:10:00"
             closeTimeout="00:10:00"
             sendTimeout="00:10:00"
             receiveTimeout="00:10:00">
      <readerQuotas
            maxArrayLength="656000"
            maxBytesPerRead="656000"
            maxDepth="32"
            maxNameTableCharCount="656000"
            maxStringContentLength="656000"
            />
    </binding>
  </webHttpBinding>
</bindings>

<services>
    <service name="--service name--" // service name
      behaviorConfiguration="longTimeoutBehavior">
      <endpoint address="http://localhost:8080/people" // service address using which service can be accessed
        binding="webHttpBinding"
Contract="MyService.Contracts.Ipeople" // Interface address with namespace
bindingConfiguration="LargeWeb" /> // bindingConfiguration name defined in <bindings> section
    </service>
</services>

=====================================================

<system.web>
  <httpRuntime maxRequestLength=”4000″
    enable = “True”
    requestLengthDiskThreshold=”512
    shutdownTimeout=”90″
    executionTimeout=”110″
    versionHeader=”1.1.4128″/>
</system.web>

=====================================================
In web.config file , make includeExceptionDetailInFaults="false" to hide exception details
from user.

<serviceDebug includeExceptionDetailInFaults="false"/> // true for devloper's build and false for production build

SOAP Service Message Example

POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 299
SOAPAction: "http://www.w3.org/2003/05/soap-envelope"

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetStockPrice xmlns:m="http://www.example.org/nilav">
      <m:StockName>IBM</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>

Custom JSON result class

Custom JSON result class that convert resopnse to JSON format in  Web API.

CustomJsonResult.cs


using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public class CustomJsonResult : JsonResult
{

    public string FormateStr { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (string.IsNullOrEmpty(this.ContentType))
        {
            response.ContentType = this.ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }

        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }

        if (this.Data != null)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            string jsonString = jsSerializer.Serialize(Data);
            MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
            Regex reg = new Regex(@"\\/Date\((\d+)\)\\/");
            jsonString = reg.Replace(jsonString, matchEvaluator);
            response.Write(jsonString);
        }
    }

    private string ConvertJsonDateToDateString(Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)).ToLocalTime();
        return dt.ToString(FormateStr);
    }
}

How to use class in controllers ?


1.  return new CustomJsonResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior,
                FormateStr = "yyyy-MM-dd HH:mm:ss"
            };

2. return new CustomJsonResult
            {
                Data = data,
                JsonRequestBehavior = behavior,
                FormateStr = format
            };
3. return new CustomJsonResult
            {
                Data = data,
                FormateStr = format
            };
4. return new CustomJsonResult
            {
                Data = data,
                FormateStr = "yyyy-MM-dd HH:mm:ss"
            };

Thursday, 12 May 2016

jQuery.parseJSON vs JSON.parse


jQuery.parseJSON and JSON.parse are two functions that perform the same task.

But If the jQuery library is already loaded, would using jQuery.parseJSON be better than 
using JSON.parse.
jQuery will use the native JSON.parse method if it is available, and otherwise it will try to evaluate the data with new Function, which is kind of like eval.

So yes, you should definitely use jQuery.parseJSON. 

Split WCF service class using partial

In WCF service, If you have lots of methods in your single service then you can physically split those methods ,and arrange them as per your requirements.


Interface:  

ICalculator.cs

[ServiceContract] 
public interface ICalculator 
{ 
   [OperationContract]
   double Add(double n1, double n2);
   [OperationContract]
   double Subtract(double n1, double n2);
   [OperationContract]
   double Multiply(double n1, double n2);
   [OperationContract]
   double Divide(double n1, double n2);
}

Service Class:

1. CalculatorService.cs
public partial class CalculatorService : ICalculator
{
  double Add(double n1, double n2){}
  double Subtract(double n1, double n2){}
}

2. CalculatorService2.cs
public partial class CalculatorService : ICalculator
{
  double Multiply(double n1, double n2){}
  double Divide(double n1, double n2){}
}



Tuesday, 10 May 2016

Using Templates with Bootstrap Modal

HTML:

<button id="btnOpenPopUp">Open</button>

JavaScript:

function openModal(){

  var popUpHTML = "<div class='modal' id='test'>"+
"    <div class='modal-dialog'>"+
"        <div class='modal-content'>"+
"            <div class='modal-header'>"+
"                <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>"+
"                <h4 class='modal-title'>Title</h4>"+
"            </div>"+
"            <div class='modal-body'>"+
"                        Nilav Patel.<br>"+
"                        nilavpatel1992@gmail.com"+
"            </div>"+
"            <div class='modal-footer'>"+
"                <a href='#' data-dismiss='modal' class='btn'>Close</a><a href='#' class='btn btn-primary'>Save changes</a>"+
"            </div>"+
"      </div>"+
"   </div>"+
"</div>";

  var popUp = $.parseHTML( popUpHTML );
  $(popUp).modal();
};

$(document).ready(function(){
     $("#btnOpenPopUp").click(function(){
openModal();
});
});

Get Tree structure data from Array using JQuery :

// json data
var data = [
{
"name": "root",
"parent": 0,
"id": "root",
},
{
"name": "a1",
"parent": "root",
"id": "a1",
},
{
"name": "a2",
"parent": "a1",
"id": "a2",
},
{
"name": "a3",
"parent": "a2",
"id": "a3",
},
{
"name": "b1",
"parent": "root",
"id": "b1",
},
{
"name": "b2",
"parent": "b1",
"id": "b2",
},
{
"name": "b3",
"parent": "b1",
"id": "b3",
}
];

/**
 * get tree structure data
 * @author Nilav Patel
 * @param   {array}  data      -json data
 * @param   {string} id        -id field property name
 * @param   {string} parent    -parent field property name
 * @param   {object} rootValue -value of root
 * @returns {array}  -array with tree structure
 */
function getTreeStructure (data, id, parent, rootValue) {

var idToNodeMap = {};
var root = null;

for (var i = 0, datum; node = data[i]; i++) {
node.children = [];
idToNodeMap[node[id]] = node;
if (node[parent] === rootValue) {
root = node;
}
   else {
parentNode = idToNodeMap[node[parent]];
parentNode.children.push(node);
}
}
return root;
}

var result = getTreeStructure(data, "id", "parent", 0);
console.log(result);

Wednesday, 27 April 2016

Generic Class for data access layer with ADO.Net

This class contains methods for 

1) For query execution

2) For Stored Procedures execution

3) Transaction



/*
 * @desc This file contains generic class for SQL connection with ado.net
 * @author NILAV PATEL <nilavpatel1992@gmail.com>
 */

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;

/// <summary>
/// SQL generic connection class
/// </summary>
public class SqlGenericConnection : IDisposable
{
    #region private variables

    /// <summary>
    /// Connection string to connect with database
    /// </summary>
    private static string connectionString { get; set; }

    /// <summary>
    /// SQL connection
    /// </summary>
    private SqlConnection connection { get; set; }

    /// <summary>
    /// SQL command
    /// </summary>
    private SqlCommand command { get; set; }

    /// <summary>
    /// SQL transaction
    /// </summary>
    private SqlTransaction transaction { get; set; }

    /// <summary>
    /// output parameters
    /// </summary>
    public List<DbParameter> outParameters { get; private set; }

    /// <summary>
    /// is object disposed ?
    /// </summary>
    private bool disposed = false;

    #endregion

    #region constructor

    /// <summary>
    /// SqlGenericConnection class constructor
    /// </summary>
    /// <param name="str">connection string</param>
    /// <param name="oldConnection">pass connection if exist</param>
    /// <param name="oldTransaction">pass transaction if exist</param>
    public SqlGenericConnection(string str = "", SqlConnection oldConnection = null, SqlTransaction oldTransaction = null)
    {


        //create new connection if not exist
        connection = oldConnection ?? new SqlConnection(connectionString);

        connectionString = ConfigurationManager.ConnectionStrings[str].ConnectionString;

        //assign transaction if exist
        if (oldTransaction != null)
        {
            transaction = oldTransaction;
        }
    }

    #endregion

    #region private methods

    /// <summary>
    /// open connection
    /// </summary>
    private void Open()
    {
        try
        {
            if (connection != null && connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
        }
        catch (Exception ex)
        {
            Close();
        }
    }

    /// <summary>
    /// close connection
    /// </summary>
    private void Close()
    {
        if (connection != null)
        {
            connection.Close();
        }
    }

    /// <summary>
    /// executes stored procedure with DB parameters if they are passed
    /// </summary>
    /// <param name="procedureName"></param>
    /// <param name="executeType"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    private object ExecuteProcedure(string procedureName, ExecuteType executeType, List<DbParameter> parameters)
    {
        object returnObject = null;

        if (connection != null)
        {
            if (connection.State == ConnectionState.Open)
            {
                command = new SqlCommand(procedureName, connection);
                command.CommandType = CommandType.StoredProcedure;

                if (transaction != null)
                {
                    command.Transaction = transaction;
                }

                // pass stored procedure parameters to command
                if (parameters != null)
                {
                    command.Parameters.Clear();

                    foreach (DbParameter dbParameter in parameters)
                    {
                        SqlParameter parameter = new SqlParameter();
                        parameter.ParameterName = "@" + dbParameter.Name;
                        parameter.Direction = dbParameter.Direction;
                        parameter.Value = dbParameter.Value;
                        command.Parameters.Add(parameter);
                    }
                }

                switch (executeType)
                {
                    case ExecuteType.ExecuteReader:
                        returnObject = command.ExecuteReader();
                        break;
                    case ExecuteType.ExecuteNonQuery:
                        returnObject = command.ExecuteNonQuery();
                        break;
                    case ExecuteType.ExecuteScalar:
                        returnObject = command.ExecuteScalar();
                        break;
                    default:
                        break;
                }
            }
        }

        return returnObject;
    }

    /// <summary>
    /// execute query with DB parameters if they are passed
    /// </summary>
    /// <param name="text"></param>
    /// <param name="executeType"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    private object ExecuteQuery(string text, ExecuteType executeType, List<DbParameter> parameters)
    {
        object returnObject = null;

        if (connection != null)
        {
            if (connection.State == ConnectionState.Open)
            {
                command = new SqlCommand(text, connection);
                command.CommandType = CommandType.Text;

                if (transaction != null)
                {
                    command.Transaction = transaction;
                }

                // pass stored procedure parameters to command
                if (parameters != null)
                {
                    command.Parameters.Clear();

                    foreach (DbParameter dbParameter in parameters)
                    {
                        SqlParameter parameter = new SqlParameter();
                        parameter.ParameterName = "@" + dbParameter.Name;
                        parameter.Direction = dbParameter.Direction;
                        parameter.Value = dbParameter.Value;
                        command.Parameters.Add(parameter);
                    }
                }

                switch (executeType)
                {
                    case ExecuteType.ExecuteReader:
                        returnObject = command.ExecuteReader();
                        break;
                    case ExecuteType.ExecuteNonQuery:
                        returnObject = command.ExecuteNonQuery();
                        break;
                    case ExecuteType.ExecuteScalar:
                        returnObject = command.ExecuteScalar();
                        break;
                    default:
                        break;
                }
            }
        }

        return returnObject;
    }

    /// <summary>
    /// updates output parameters from stored procedure
    /// </summary>
    private void UpdateOutParameters()
    {
        if (command.Parameters.Count > 0)
        {
            outParameters = new List<DbParameter>();
            outParameters.Clear();

            for (int i = 0; i < command.Parameters.Count; i++)
            {
                if (command.Parameters[i].Direction == ParameterDirection.Output)
                {
                    outParameters.Add(new DbParameter(command.Parameters[i].ParameterName,
                                                      ParameterDirection.Output,
                                                      command.Parameters[i].Value));
                }
            }
        }
    }

    #endregion

    #region protected methods

    /// <summary>
    /// Dispose SqlGenericConnection class object
    /// </summary>
    /// <param name="disposing"></param>
    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                transaction.Dispose();
                command.Dispose();
                connection.Dispose();
            }

            disposed = true;
        }
    }

    #endregion

    #region public methods

    #region stored procedure methods

    /// <summary>
    /// executes scalar query stored procedure without parameters
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public T ExecuteSingleProc<T>(string procedureName) where T : new()
    {
        return ExecuteSingleProc<T>(procedureName, null);
    }

    /// <summary>
    /// executes scalar query stored procedure and maps result to single object
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public T ExecuteSingleProc<T>(string procedureName, List<DbParameter> parameters) where T : new()
    {
        Open();

        IDataReader reader = (IDataReader)ExecuteProcedure(procedureName, ExecuteType.ExecuteReader, parameters);
        T tempObject = new T();

        if (reader.Read())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                PropertyInfo propertyInfo = typeof(T).GetProperty(reader.GetName(i));
                propertyInfo.SetValue(tempObject, reader.GetValue(i), null);
            }
        }

        reader.Close();

        UpdateOutParameters();

        Close();

        return tempObject;
    }

    /// <summary>
    /// executes list query stored procedure without parameters (Select)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public List<T> ExecuteListProc<T>(string procedureName) where T : new()
    {
        return ExecuteListProc<T>(procedureName, null);
    }

    /// <summary>
    /// executes list query stored procedure and maps result generic list of objects (Select with parameters)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public List<T> ExecuteListProc<T>(string procedureName, List<DbParameter> parameters) where T : new()
    {
        List<T> objects = new List<T>();

        Open();

        IDataReader reader = (IDataReader)ExecuteProcedure(procedureName, ExecuteType.ExecuteReader, parameters);

        while (reader.Read())
        {
            T tempObject = new T();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                if (reader.GetValue(i) != DBNull.Value)
                {
                    PropertyInfo propertyInfo = typeof(T).GetProperty(reader.GetName(i));
                    propertyInfo.SetValue(tempObject, reader.GetValue(i), null);
                }
            }

            objects.Add(tempObject);
        }

        reader.Close();

        UpdateOutParameters();

        Close();

        return objects;
    }

    /// <summary>
    /// executes non query stored procedure with parameters (Insert, Update, Delete)
    /// </summary>
    /// <param name="procedureName"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public int ExecuteNonQueryProc(string procedureName, List<DbParameter> parameters)
    {
        int returnValue;

        Open();

        returnValue = (int)ExecuteProcedure(procedureName, ExecuteType.ExecuteNonQuery, parameters);

        UpdateOutParameters();

        Close();

        return returnValue;
    }

    /// <summary>
    /// executes scalar query stored procedure without parameters (Count(), Sum(), Min(), Max() etc...)
    /// </summary>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public object ExecuteScalarProc(string procedureName)
    {
        return ExecuteScalarProc(procedureName, null);
    }

    /// <summary>
    /// executes scalar query stored procedure with parameters (Count(), Sum(), Min(), Max() etc...)
    /// </summary>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public object ExecuteScalarProc(string procedureName, List<DbParameter> parameters)
    {
        object returnValue;

        Open();

        returnValue = ExecuteProcedure(procedureName, ExecuteType.ExecuteScalar, parameters);

        UpdateOutParameters();

        Close();

        return returnValue;
    }

    #endregion

    #region query methods

    /// <summary>
    /// executes scalar query stored procedure without parameters
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public T ExecuteSingle<T>(string text) where T : new()
    {
        return ExecuteSingle<T>(text, null);
    }

    /// <summary>
    /// executes scalar query stored procedure and maps result to single object
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public T ExecuteSingle<T>(string text, List<DbParameter> parameters) where T : new()
    {
        Open();

        IDataReader reader = (IDataReader)ExecuteQuery(text, ExecuteType.ExecuteReader, parameters);
        T tempObject = new T();

        if (reader.Read())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                PropertyInfo propertyInfo = typeof(T).GetProperty(reader.GetName(i));
                propertyInfo.SetValue(tempObject, reader.GetValue(i), null);
            }
        }

        reader.Close();

        UpdateOutParameters();

        Close();

        return tempObject;
    }

    /// <summary>
    /// executes list query stored procedure without parameters (Select)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public List<T> ExecuteList<T>(string text) where T : new()
    {
        return ExecuteList<T>(text, null);
    }

    /// <summary>
    /// executes list query stored procedure and maps result generic list of objects (Select with parameters)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="procedureName"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public List<T> ExecuteList<T>(string text, List<DbParameter> parameters) where T : new()
    {
        List<T> objects = new List<T>();

        Open();

        IDataReader reader = (IDataReader)ExecuteQuery(text, ExecuteType.ExecuteReader, parameters);

        while (reader.Read())
        {
            T tempObject = new T();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                if (reader.GetValue(i) != DBNull.Value)
                {
                    PropertyInfo propertyInfo = typeof(T).GetProperty(reader.GetName(i));
                    propertyInfo.SetValue(tempObject, reader.GetValue(i), null);
                }
            }

            objects.Add(tempObject);
        }

        reader.Close();

        UpdateOutParameters();

        Close();

        return objects;
    }

    /// <summary>
    /// executes non query stored procedure with parameters (Insert, Update, Delete)
    /// </summary>
    /// <param name="procedureName"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public int ExecuteNonQuery(string text, List<DbParameter> parameters)
    {
        int returnValue;

        Open();

        returnValue = (int)ExecuteQuery(text, ExecuteType.ExecuteNonQuery, parameters);

        UpdateOutParameters();

        Close();

        return returnValue;
    }

    /// <summary>
    /// executes scalar query stored procedure without parameters (Count(), Sum(), Min(), Max() etc...)
    /// </summary>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public object ExecuteScalar(string text)
    {
        return ExecuteScalar(text, null);
    }

    /// <summary>
    /// executes scalar query stored procedure with parameters (Count(), Sum(), Min(), Max() etc...)
    /// </summary>
    /// <param name="procedureName"></param>
    /// <returns></returns>
    public object ExecuteScalar(string text, List<DbParameter> parameters)
    {
        object returnValue;

        Open();

        returnValue = ExecuteQuery(text, ExecuteType.ExecuteScalar, parameters);

        UpdateOutParameters();

        Close();

        return returnValue;
    }

    #endregion

    #region transaction methods

    /// <summary>
    /// begin transaction
    /// </summary>
    public void BeginTransaction()
    {
        if (connection != null)
        {
            transaction = connection.BeginTransaction();
        }
    }

    /// <summary>
    /// commit transaction
    /// </summary>
    public void CommitTransaction()
    {
        if (transaction != null)
        {
            transaction.Commit();
        }
    }

    /// <summary>
    /// rollback transaction
    /// </summary>
    public void RollbackTransaction()
    {
        if (transaction != null)
        {
            transaction.Rollback();
        }
    }

    #endregion

    #region dispose method

    /// <summary>
    /// Dispose SqlGenericConnection class object
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    #endregion

    #endregion
}

/// <summary>
/// execution type enumerations
/// </summary>
public enum ExecuteType
{
    ExecuteReader,
    ExecuteNonQuery,
    ExecuteScalar
}

/// <summary>
/// Db parameter class
/// </summary>
public class DbParameter
{
    public string Name { get; set; }
    public ParameterDirection Direction { get; set; }
    public object Value { get; set; }

    public DbParameter(string paramName, ParameterDirection paramDirection, object paramValue)
    {
        Name = paramName;
        Direction = paramDirection;
        Value = paramValue;
    }
}

Dynamically load js and css files in your html page :


<!doctype html>
<html lang="en" ng-app="" ng-strict-di ng-controller="">

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="Description" content="Discription about your web site">

<title ng-bind-template="AngularJS: {{ currentArea.name }}: {{ currentPage.name || 'Error: Page not found'}}">AngularJS</title>

<script type="text/javascript">

// dynamically add base tag as well as css and javascript files.
// we can't add css/js the usual way, because some browsers (FF) eagerly prefetch resources
// before the base attribute is added, causing 404 and terribly slow loading of the docs app.
(function() {

var indexFile = (location.pathname.match(/\/(index[^\.]*\.html)/) || ['', ''])[1],
rUrl = /(#!\/|api|guide|misc|tutorial|error|index[^\.]*\.html).*$/,
baseUrl = location.href.replace(rUrl, indexFile),
production = location.hostname === 'docs.angularjs.org',
headEl = document.getElementsByTagName('head')[0],
sync = true;

addTag('base', {href: baseUrl});

// add all css file's relative url
addTag('link', {rel: 'stylesheet',href: 'components/bootstrap-3.1.1/css/bootstrap.min.css',type: 'text/css'});
addTag('link', {rel: 'stylesheet',href: 'css/app.css',type: 'text/css'});

// add all js file's relative url
addTag('script', {src: '//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js'}, sync);
addTag('script', {src: 'components/app.js'}, sync);

function addTag(name, attributes, sync) {
var el = document.createElement(name),
attrName;

for (attrName in attributes) {
el.setAttribute(attrName, attributes[attrName]);
}

sync ? document.write(outerHTML(el)) : headEl.appendChild(el);
}

function outerHTML(node) {
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n) {
var div = document.createElement('div'),
h;
div.appendChild(n);
h = div.innerHTML;
div = null;
return h;
})(node);
}

})();
</script>

</head>

<body>

<div id="wrapper">

<!--header section start-->
<header class="header">
header
</header>
<!--header section end-->

<!--main content section start-->
<section role="main" class="container main-body">
content
</section>
<!--main content section end-->

<!--footer section start-->
<footer class="footer">
footer
</footer>
<!--footer section end-->

</div>

</body>

</html>

Parent-Child class declaration and initialization

using System; namespace CSharpDemo {     public class A     {         public void print()         {             Console.Wr...