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>

Tuesday, 19 April 2016

Gulp JS Example V2.0

  1. Contains build for test and production version with debug and minified js files.
  2. Change global variables as per the build configurations.
  3. Change css and js file refrences in index.html page as per build configurations.


/******************************
Author: Nilav Patel(nilavpatel.blogspot.com)
version: 2.0
******************************/

/******************************
run below command to install all dependencies:

npm install gulp gulp-clean gulp-minify gulp-cssmin gulp-rename gulp-concat gulp-ng-html2js gulp-minify-html gulp-inject gulp-preprocess gulp-sequence gulp-util gulp-imagemin imagemin-pngquant --save-dev
******************************/

/******************************
default task (it will run task "build-test") => $ gulp,

for Production build, run task => $ gulp build-prod ,

for test build, run task => $ gulp build-test
******************************/

var gulp = require('gulp');
var clean = require('gulp-clean');
var minify = require('gulp-minify');
var cssmin = require('gulp-cssmin');
var rename = require("gulp-rename");
var concat = require('gulp-concat');
var ngHtml2Js = require("gulp-ng-html2js");
var minifyHtml = require("gulp-minify-html");
var inject = require('gulp-inject');
var preprocess = require('gulp-preprocess');
var gulpSequence = require('gulp-sequence');
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');

// ------------default task-------------------------------------------------------
gulp.task('default', ['build-test']);

// ------------build-test task----------------------------------------------------
gulp.task('build-test', gulpSequence(
 'clean', // clean the build
 'copy-html', // copy index.html to /dist folder
 'copy-assets', // copy all assets to /dist folder
 'copy-js', // copy all js files to /dist folder
 'concat-js-test', // concat all application js to app.js file
 'copy-css', // copy all css to
 'partials', // create html to js for all .template.html files
 'rename-js', // rename all js files in /dist/js folder
 'minify-css', // minify all css files in /dist/style folder
 'rename-css', // rename css files with .min prefix
 'clean-junk-test', // remove other junk files
 'image-opt', // image optimization
 'index-test' // inject js and css files in index.html
));

// ------------build-prod task-----------------------------------------------------
gulp.task('build-prod', gulpSequence(
 'clean', // clean the build
 'copy-html', // copy index.html to /dist folder
 'copy-assets', // copy all assets to /dist folder
 'copy-js', // copy all js files to /dist folder
 'concat-js-prod', // concat all application js to app.js file
 'copy-css', // copy all css to
 'partials', // create html to js for all .template.html files
 'minify-js', // minify all js files in /dist/js folder
 'minify-css', // minify all css files in /dist/style folder
 'rename-css', // rename css files with .min prefix
 'clean-junk-prod', // remove other junk files
 'image-opt', // image optimization
 'index-prod' // inject js and css files in index.html
));

// ------------clean dist folder---------------------------------------------------
// This task will clean the ./dist folder
gulp.task('clean', function () {
 return gulp.src('./dist')
  .pipe(clean());
});

// ------------copy html to dist folder--------------------------------------------
// This task will copy html files to ./dist folder
gulp.task('copy-html', function () {
 return gulp.src('./src/index.html')
  .pipe(gulp.dest('./dist'));
});

// ------------copy assets to dist folder------------------------------------------
// This task will copy all assets to ./dist folder
gulp.task('copy-assets', function () {
 return gulp.src([
        './src/assets/**/*.*',
        '!./src/assets/**/*.css'
    ])
  .pipe(gulp.dest('./dist'));
});

// ------------copy all js files to dist folder after minification------------------
// This task will copy all vendor js files to ./dist/js folder for both test and prod
gulp.task('copy-js', function () {
 return gulp.src([
        './node_modules/angular/angular.js',
        './node_modules/angular-material/angular-material.js'
    ])
  .pipe(gulp.dest('./dist/js'));
});

// ------------list all application js files-----------------------------------------
var appJS = [
    './src/common/global.js',
    './src/common/constants.js',
    './src/app/app.module.js',
    './src/app/app.config.js',
    './src/app/app.route.js',
    './src/app/app.run.js',
    './src/app/app.controller.js'
];

// ------------concat all application js files----------------------------------------
// This task will concat all application js files to ./dist/js folder for test
gulp.task('concat-js-test', function () {
 return gulp.src(appJS)
  .pipe(preprocess({
   context: {
    NODE_ENV: 'test',
    DEBUG: true
   }
  }))
  .pipe(concat('app.js'))
  .pipe(gulp.dest('./dist/js'))
  .on('error', gutil.log);
});

// ------------concat all application js files------------------------- ---------------
// This task will copy all js application files to ./dist/js folder for prod
gulp.task('concat-js-prod', function () {
 return gulp.src(appJS)
  .pipe(preprocess({
   context: {
    NODE_ENV: 'production',
    DEBUG: false
   }
  }))
  .pipe(concat('app.js'))
  .pipe(gulp.dest('./dist/js'));
});

// ------------copy all css files to dist folder-------------------------------------
// This task will copy all css files to ./dist/style folder
gulp.task('copy-css', function () {
 return gulp.src([
        './node_modules/angular-material/angular-material.min.css',
        './src/assets/style/*.css'
    ])
  .pipe(gulp.dest('./dist/style'))
  .on('error', gutil.log);
});

// ------------minify all js files---------------------------------------------------
// This task will minify all js files from ./dist/js folder
gulp.task('minify-js', function () {
 return gulp.src('./dist/js/*.js')
  .pipe(minify({
   ext: {
    src: '.debug.js',
    min: '.min.js'
   },
  }))
  .pipe(gulp.dest('./dist/js'))
  .on('error', gutil.log);
});

// ------------minify all css files--------------------------------------------------
// This task will minify css files form ./dist/style folder
gulp.task('minify-css', function () {
 return gulp.src('./dist/style/*.css')
  .pipe(cssmin())
  .pipe(gulp.dest('./dist/style'))
  .on('error', gutil.log);
});

// ------------rename all css files with .min-----------------------------------------
// This task will add .min as extention to all css files in ./dist folder
gulp.task('rename-css', function () {
 return gulp.src([
        './dist/style/*.css',
        '!./dist/style/*.min.css'
    ])
  .pipe(rename(function (path) {
   path.basename += ".min";
  }))
  .pipe(gulp.dest('./dist/style'))
  .on('error', gutil.log);
});

// ------------rename all js files with .min------------------------------------------
// This task will add .min and .debug as extention to js files in ./dist folder
gulp.task('rename-js', function () {
 return gulp.src([
        './dist/js/*.js',
        '!./dist/js/*.min.js'
    ])
  .pipe(rename(function (path) {
   path.basename += ".debug";
  }))
  .pipe(gulp.dest('./dist/js'))
  .on('error', gutil.log);
});

// ------------clean extra junk files from dist--------------------------------------
// This task will remove extra junk files from test build
gulp.task('clean-junk-prod', function () {
 return gulp.src([
        './dist/js/*.js',
        './dist/style/*.css',
        '!./dist/js/*.min.js',
        './dist/js/*.debug.js',
        '!./dist/style/*.min.css'
    ])
  .pipe(clean())
  .on('error', gutil.log);
});

// ------------clean extra junk files from dist----------------------------------------
// This task will remove extra junk js and css files from production build
gulp.task('clean-junk-test', function () {
 return gulp.src([
        './dist/js/*.js',
        './dist/style/*.css',
        './dist/js/*.min.js',
        '!./dist/js/*.debug.js',
        '!./dist/style/*.min.css'
    ])
  .pipe(clean())
  .on('error', gutil.log);
});

// ------------image optimization------------------------------------------------------
// This task will optimize all images in app
gulp.task('image-opt', function () {
 return gulp.src('./dist/img/*.*')
  .pipe(imagemin({
   progressive: true,
   svgoPlugins: [{
    removeViewBox: false
   }],
   use: [pngquant()]
  }))
  .pipe(gulp.dest('./dist/img'))
  .on('error', gutil.log);
});

// ------------convert templates to js file---------------------------------------------
// This task will convert all template html to js files and concat them all in template.js file
gulp.task('partials', function () {
 return gulp.src("./src/**/*.template.html")
  .pipe(minifyHtml({
   empty: true,
   spare: true,
   quotes: true
  }))
  .pipe(ngHtml2Js({
   moduleName: "templates",
   prefix: "/"
  }))
  .pipe(concat("partials.js"))
  .pipe(gulp.dest("./dist/js"))
  .on('error', gutil.log);
});

// ------------build index.html for test------------------------------------------------
// This task will inject js and css files for test build in index.html page
gulp.task('index-test', function () {
 var target = gulp.src('./dist/index.html');
 // It's not necessary to read the files (will speed up things), we're only after their paths:
 var sources = gulp.src([
        './dist/js/angular.debug.js',
        './dist/js/angular-material.debug.js',
        './dist/js/app.debug.js',
        './dist/js/partials.debug.js',
        './dist/style/angular-material.min.css',
        './dist/style/style.min.css'
    ], {
  read: false
 }, {
  relative: true
 });

 return target.pipe(inject(sources))
  .pipe(gulp.dest('./dist'))
  .on('error', gutil.log);
});

// ------------build index.html for prod---------------------------------------------------
// This task will inject js and css files for production build in index.html page
gulp.task('index-prod', function () {
 var target = gulp.src('./dist/index.html');
 // It's not necessary to read the files (will speed up things), we're only after their paths:
 var sources = gulp.src([
        './dist/js/angular.min.js',
        './dist/js/angular-material.min.js',
        './dist/js/app.min.js',
        './dist/js/partials.min.js',
        './dist/style/angular-material.min.css',
        './dist/style/style.min.css'
    ], {
  read: false
 }, {
  relative: true
 });

 return target.pipe(inject(sources))
  .pipe(gulp.dest('./dist'))
  .on('error', gutil.log);
});

Friday, 1 April 2016

Gulp JS....gulpfile.js example


var gulp = require('gulp');
var clean = require('gulp-clean');
var minify = require('gulp-minify');
var cssmin = require('gulp-cssmin');
var rename = require("gulp-rename");
var concat = require('gulp-concat');
var imageop = require('gulp-image-optimization');
var ngHtml2Js = require("gulp-ng-html2js");
var minifyHtml = require("gulp-minify-html");

// default task
gulp.task('default', ['build']);

// build task
gulp.task('build', [
    'clean', // clean the build
    'copy-html', // copy index.html to /dist folder
    'copy-assets', // copy all assets to /dist folder
    'copy-js', // copy all js files to /dist folder
    'concat-js', // concat all application js to app.js file
    'copy-css', // copy all css to
    'minify-js', // minify all js files in /dist/js folder
    'minify-css', // minify all css files in /dist/style folder
    'rename-css', // rename css files with .min prefix
    'clean-junk', // remove other junk files
    'image-opt', // image optimization
    'partials' // create html to js for all .template.html files
]);

// clean dist folder
gulp.task('clean', function () {
    return gulp.src('./dist')
        .pipe(clean());
});

// copy html to dist folder
gulp.task('copy-html', ['clean'], function () {
    return gulp.src('./src/index.html')
        .pipe(gulp.dest('./dist'));
});

// copy assets to dist folder
gulp.task('copy-assets', ['clean'], function () {
    return gulp.src(['./src/assets/**/*.*', '!./src/assets/**/*.css'])
        .pipe(gulp.dest('./dist'));
});

// copy all js files to dist folder after minification
gulp.task('copy-js', ['clean'], function () {
    return gulp.src(['./node_modules/angular/angular.js',
              './node_modules/angular-material/angular-material.js'])
        .pipe(gulp.dest('./dist/js'));
});

// list all application js files
var appJS = [
    './src/common/global.js',  
    './src/common/constants.js',
    './src/app/app.module.js',  
    './src/app/app.config.js',
    './src/app/app.route.js',
    './src/app/app.run.js',
    './src/app/app.controller.js'
];

// concat all application js files
gulp.task('concat-js', ['clean'], function () {
    return gulp.src(appJS)
        .pipe(concat('app.js'))
        .pipe(gulp.dest('./dist/js'));
});

// copy all css files to dist folder
gulp.task('copy-css', ['clean'], function () {
    return gulp.src(['./node_modules/angular-material/angular-material.min.css', './src/assets/style/*.css'])
        .pipe(gulp.dest('./dist/style'));
});

// minify all js files
gulp.task('minify-js', ['clean', 'copy-js', 'concat-js', 'partials'], function () {
    return gulp.src('./dist/js/*.js')
        .pipe(minify({
            ext: {
                src: '.debug.js',
                min: '.min.js'
            },
        }))
        .pipe(gulp.dest('./dist/js'));
});

// minify all css files
gulp.task('minify-css', ['clean', 'copy-css'], function () {
    return gulp.src('./dist/style/*.css')
        .pipe(cssmin())
        .pipe(gulp.dest('./dist/style'));
});

// rename all css files with .min
gulp.task('rename-css', ['clean', 'minify-css'], function () {
    return gulp.src(['./dist/style/*.css', '!./dist/style/*.min.css'])
        .pipe(rename(function (path) {
            path.basename += ".min";
        }))
        .pipe(gulp.dest('./dist/style'));
});

// rename all js files with .min
gulp.task('rename-js', ['clean', 'minify-js', 'concat-js'], function () {
    return gulp.src(['./dist/js/*.js', '!./dist/js/*.min.js'])
        .pipe(rename(function (path) {
            path.basename += ".min";
        }))
        .pipe(gulp.dest('./dist/js'));
});

// clean extra junk files from dist
gulp.task('clean-junk', ['clean', 'minify-css', 'minify-js'], function () {
    return gulp.src(['./dist/js/*.js', './dist/style/*.css', '!./dist/js/*.min.js','!./dist/js/*.debug.js' ,'!./dist/style/*.min.css'])
        .pipe(clean());
});

// image optimization
gulp.task('image-opt', ['copy-assets'], function () {
    return gulp.src('./dist/img/*.*')
        .pipe(imageop({
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest('./dist/img'));
});

// convert templates to js file
gulp.task('partials', ['clean'], function () {
    return gulp.src("./src/**/*.template.html")
        .pipe(minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(ngHtml2Js({
            moduleName: "templates",
            prefix: "/"
        }))
        .pipe(concat("partials.js"))
        .pipe(gulp.dest("./dist/js"));
});

Kendo multiselect with kendo tree view combine 2

<!--Created by Nilav Patel (nilavpatel1992@gmail.com, nilavpatel.blogspot.com)-->
<html>

<head>
    <title>Kendo Multi select and tree view combine control</title>
    <link href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.common.min.css" rel="stylesheet" />
    <link href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.default.min.css" rel="stylesheet" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://cdn.kendostatic.com/2015.1.429/js/kendo.all.min.js"></script>
    <style>
        .my-selected-state {
            background-color: lightskyblue;
            color: white
        }
     
        body {
            font-family: sans-serif
        }
     
        #treeview {
            display: none;
        }
     
        #multiselectTree {
            width: 400px;
            border: 2px solid lightskyblue
        }
     
        #multiselectTree .k-delete {
            /*display: none;/*
                /*by default kendo tree view is hidden*/
        }
     
        #treeview {
            background-color: aliceblue;
        }
     
        #multiselect-list {
            display: none !important;
        }
    </style>
</head>

<body>

    <!--Kendo multiselect tree view start-->
    <div id="multiselectTree">
        <!--Kendo multiselect start-->
        <div id="lblSelectTree">
            <select id="multiselect" multiple="multiple" placeholder="select leagal topics">
                <option value="" disabled selected>Select your option</option>
            </select>
        </div>
        <!--Kendo multiselect end-->
        <!--kendo tree view start-->
        <div id="treeview">
            <div id='mytree'>
            </div>
        </div>
        <!--Kendo tree view end-->
    </div>
    <!--Kendo multiselect tree view end-->

</body>

<script>
    // Global variable for selected values
    var selectedVlaues = [];
    var multiSelect;
    var treeView;
    var dataSourceForTreeView = [{
        text: "Item 1",
        id: "Item 1",
        items: [{
            id: "Item 1.1",
            text: "Item 1.1"
        }, {
            id: "Item 1.2",
            text: "Item 1.2"
        }, {
            id: "Item 1.3",
            text: "Item 1.3"
        }]
    }, {
        text: "Item 2",
        id: "Item 2",
        items: [{
            id: "Item 2.1",
            text: "Item 2.1"
        }, {
            id: "Item 2.2",
            text: "Item 2.2"
        }, {
            id: "Item 2.3",
            text: "Item 2.3"
        }]
    }, {
        id: "Item 3",
        text: "Item 3"
    }];

    function createMultiSelect() {

        // Create kedno multiselect
        multiSelect = $("#multiselect").kendoMultiSelect({
            optionLabel: "Select Legal Topics...",
            dataTextField: "text",
            dataValueField: "value",
            animation: false,
            change: function(event) {

                debugger;
             
                var array1 = multiSelect.value();
                var array2 = multiSelect.dataSource.data();
     

                $.grep(array2, function(el) {
                    if ($.inArray(el.value, array1) == -1) {
                        var bar = treeView.findByText(el.value);
                        treeView.dataItem(bar).set("checked", false);
                    }
                });


            }
        }).data("kendoMultiSelect");

        // Kendo multiselect in read only mode
        // multiSelect.readonly();


    }

    function createTreeView() {

        // Create Tree view control
        treeView = $('#mytree').kendoTreeView({
            dataSource: {
                data: dataSourceForTreeView
            },
            checkboxes: {
                checkChildren: false
            },
            check: onCheck,
            select: function(e) {
                debugger;
                var bar = treeView.findByText(e.node.innerText.split("\n")[0]);
                var node = treeView.dataItem(bar);
                if (node.dirty && node.checked) {
                    node.set("checked", false);
                } else {
                    node.set("checked", true);
                }
                             
                onCheck();
                             
            },
            change:function(){
                treeView.select().find(".k-state-selected").removeClass("k-state-selected");
            }

        }).data("kendoTreeView");

     
        $('#mytree ').data('kendoTreeView').expand(".k-item");

    }

    // function that gathers IDs of checked nodes
    function checkedNodeIds(nodes, checkedNodes) {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].checked) {

                if (nodes[i].parent().parent()) {
                    checkedNodes.push({
                        text: nodes[i].parent().parent().id + " > " + nodes[i].id,
                        value: nodes[i].id                      
                    });
                } else {
                    checkedNodes.push({
                        text: nodes[i].id,
                        value: nodes[i].id
                    });
                }
            }

            if (nodes[i].hasChildren) {
                checkedNodeIds(nodes[i].children.view(), checkedNodes);
            }
        }
    }

    // show checked node IDs on datasource change
    function onCheck() {

        var checkedNodes = [];
        checkedNodeIds(treeView.dataSource.view(), checkedNodes);

        multiSelect.dataSource.data(checkedNodes);
        multiSelect.value(checkedNodes);

    }

    $(document).ready(function() {

        createTreeView()

        createMultiSelect()

        // Show Treeview on click of multiselect
        $("#lblSelectTree").click(function(e) {
            $("#treeview").show();
        })

        // Hide tree view on click of outside control
        $('body').click(function(evt) {
            if ($(evt.target).parents('#multiselectTree').length == 0) {
                $("#treeview").hide();
            }
        });
    });
</script>

</html>

Parent-Child class declaration and initialization

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