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>

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);
});

Parent-Child class declaration and initialization

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