Thursday, December 14, 2017

C# - How to merge paths with slashes in all subsequent params

To combine file paths with slashes will take care by below code

public static string MergePath(params string[] stringPaths)

            for (int i = 0; i < stringPaths.Length; i++)
                //To skip trim on first path
                if (i != 0)
                    stringPaths[i] = stringPaths[i].Trim().TrimStart(Path.DirectorySeparatorChar).TrimEnd(Path.DirectorySeparatorChar);

            return Path.Combine(stringPaths);


var stringtest = Extensions.MergePath(@"c:\path\", @"\dir\file.txt");
var stringtest2 = Extensions.MergePath(@"c:\path\",@"\test\adsf\", @"\dir\file.txt");
var stringtest3 = Extensions.MergePath(@"c:\path", @"test\adsf", @"dir\file.txt");


Monday, July 10, 2017

IIS - Application warmup

How to warm up IIS application especially when using Entity framework

Follow below steps to enable your website always respond quickly,

- Check "Application Initialization" feature enabled in windows features turn or off

- Start Mode of Application pool set as "Always Running" in AppPool Advanced Settings
- Preload of Website should be set as "true" in Website advanced settings
- Add Application Initialization script in web.config of your application as below, You can specify valid URL which can initialize all items such as SQL DB, EF etc.,

  <applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
      <add initializationPage="/YourUrl/YourMethodAnything" />

Following these steps will solve your idle timeout application responding slow issue.

Tuesday, March 7, 2017

JavaScript - Simple Export to excel

To export excel in JavaScript without any server side techiques, we can use following steps

Used blob file saver for download

Step 1: Create Html Content with required styles as below

var tableHtml = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
        tableHtml += '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets>';
        tableHtml += '<x:ExcelWorksheet><x:Name>PlanFundLineup</x:Name>';
        tableHtml += '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
        tableHtml += '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
  tableHtml += "<div><table  border='1'>" +
        tableHtml += "<thead>" +
        tableHtml += "<tr><th>" +
        tableHtml += "Header Text" +
        tableHtml += "</th></tr>" +
 tableHtml += "</thead>" +
               "<tbody>" +
        tableHtml += "<tr><td>" +
        tableHtml += "Content Text" +
        tableHtml += "</td></tr>" +
               "</tbody>" +
        tableHtml += '</body></html>';

Step 2: Download this html content using blob

var blob = new Blob([tableHtml], { type: "application/;charset=utf-8" })
window.saveAs(blob, "excelname.xls");

Wednesday, November 23, 2016

HTTP Call - Differentiate Request and Response with some id

On most cases, user expect last requested service call results to be displayed in UI when multiple service call are made (For Ex: Search textbox to search something will make multiple calls).

We can achieve this with HTTP headers, Let us see the implementation,

First on MVC side we can check custom header present in request or not and then return that header back to response

public class SomeCustomFilter : ActionFilterAttribute
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            if (actionExecutedContext.Request.Headers.Contains("Custom-Request-Id"))
                string HttpRequestID = actionExecutedContext.Request.Headers.GetValues("Custom-Request-Id ").FirstOrDefault();
                actionExecutedContext.Response.Headers.Add("Custom-Request-Id ", HttpRequestID);



Register this filter in global.asax

GlobalConfiguration.Configuration.Filters.Add(new SomeCustomFilter());

Now we are ready at service side, to get request header and return the same value as response header

Next send some header and receive at client side, lets take AngularJS $http for sample

var customRequestId = 0;

    function SomeMethod(url, data) {
        //Increase that request id on each service call, to make it unique
        customRequestId += ;
        var customHeaders = {‘
            Custom - Request - Id’: customRequestId

        method: 'POST',
        url: url,
        headers: customHeaders,
        data: data
            function(data) {
                //check if response and request are matches with latest service call
                var currentRequestId = parseInt(data.headers("Custom-Request-Id"));
                if (customRequestId === currentRequestId) {
                    //your logic goes here…

            function(errorData, status, headers, config) {});

Thats it, now your service call is get latest values to display in UI.

Wednesday, November 9, 2016

AngularJS - JavaScript - Client Side error logging

Usually for ServerSide logging we can use many error logging tools (For ex: elmah, log4net etc.,) to log errors into database and email. But for client side JavaScript framework we should include some extra code or some tools available (for ex: JSNLog etc.,). Here am going to explain how custom we do that,

First create JavaScript file "errorlog.js" and copy paste below code,

var errorLoggingServerURL = "Error/Log";

function logErrorToServer(ex, stack) {
    if (ex == null) return;

    if (stack == null && ex.stack != null) stack = ex.stack;

    // format output
    var out = ex.message != null ? + ": " + ex.message : "JavaScript Exception";
    if (stack != null) out += "\n  at " + stack.toString();

    // send error message
        type: 'POST',
        url: errorLoggingServerURL,
        data: { message: escape(out) }


Function.prototype.trace = function () {
    var trace = [];
    var current = this;
    while (current) {
        current = current.caller;
    return trace;

Function.prototype.signature = function () {
    var signature = {
        name: this.getName(),
        params: [],
        toString: function () {
            var params = this.params.length > 0 ?
                "'" + this.params.join("', '") + "'" : "";
            return + "(" + params + ")"
    if (this.arguments) {
        for (var x = 0; x < this.arguments.length; x++)
    return signature;

Function.prototype.getName = function () {
    if (
    var definition = this.toString().split("\n")[0];
    var exp = /^function ([^\s(]+).+/;
    if (exp.test(definition))
        return definition.split("\n")[0].replace(exp, "$1") || "anonymous";
    return "anonymous";

window.onerror = function (msg, url, line) {
    if (arguments != null && arguments.callee != null && arguments.callee.trace)
        logErrorToServer(msg, arguments.callee.trace());


In AngularJS, we can have custom logging as follows,

To override AngularJS default logging and to write custom logging use as below,

 app.factory('$exceptionHandler', function () {
        return function (exception, cause) {
            //Javascript Error log will catch this

Or to use both angularJS default logging and custom logging use as below

//Exception log decorator
 $provide.decorator('$exceptionHandler', ['$delegate', function ($delegate) {
    return function (exception, cause) {
     $delegate(exception, cause);

In Server Side, we can receive the Ajax call and use any logging tool to log error, For ex, here am using Elmah to log error, it uses MVC action controller and using logging as custom class named JavaScriptException

public class ErrorController : Controller
public void Log(string message)
                .Raise(new JavaScriptException(HttpUtility.UrlDecode(message)));