Create Responsive + Bootstrap + SignalR + ASP.NET MVC c# + AngularJS Real time dashboard

Hi all. Let’s create responsive dashboard using
– AngularJS
– Bootstrap
– SignalR
– Highcharts

This sample project based on tons of resources on internet.I have listed few of them below. You can download this project on GitHub (https://github.com/uwudamith/Dashboard). Feel free to download and modify the dashboard project.
Entire prototype has developed using SignalR services. Server will push data into the client without refreshing the browser. That is the beauty of Real Time applications. All charts are based on Highcharts. Layout based on Bootstrap css, so it is responsive by default.

Runtime

ServerPerformance

customer

Charts

SiganalR hub proxy factory

var signalRHubProxy = function ($rootScope, signalRServer) {
    
    function signalRHubProxyFactory(serverUrl, hubName, startOptions) {
        var connection = $.hubConnection(signalRServer);
        var proxy = connection.createHubProxy(hubName);
        connection.start(startOptions).done(function () { });

        return {
            on: function (eventName, callback) {
                proxy.on(eventName, function (result) {
                    $rootScope.$apply(function () {
                        if (callback) {
                            callback(result);
                        }
                    });
                });
            },
            off: function (eventName, callback) {
                proxy.off(eventName, function (result) {
                    $rootScope.$apply(function () {
                        if (callback) {
                            callback(result);
                        }
                    });
                });
            },
            invoke: function (methodName, callback) {
                proxy.invoke(methodName)
                    .done(function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
            },
            connection: connection
        };
    };

    return signalRHubProxyFactory;
};

Calling the factory from angular controller

var serverPerformanceController = function ($scope, signalRHubProxy) {

    $scope.RamCpu = {
        RamUsage: '0',
        CpuUsage: '0',
        Total:'0'
    };

    var clientPushHubProxy = signalRHubProxy(
       signalRHubProxy.defaultServer, 'MyHub',
           { logging: true });

    clientPushHubProxy.on('serverPerformanceDetails', function (data) {
        $scope.RamCpu = data;
        var x = clientPushHubProxy.connection.id;
    });
};

Injecting service into chart controller

// Declare angular application
var dashboardApp = angular.module('dashboardApp', ['ui.bootstrap', 'highcharts-ng']);

// Service declaration
dashboardApp.service('chartdataService', ['$rootScope', '$http', chartdataService]);

// Factory declaration
dashboardApp.factory('signalRHubProxy', ['$rootScope', signalRHubProxy]);

// Controllers declaration
dashboardApp.controller('chartController', ['$scope', '$log', '$timeout', '$interval', 'chartdataService', 'signalRHubProxy', chartController]);

Binding data into html pages

<div class="row" ng-controller="serverPerformanceController">
    <div class="col-md-3">
        <div class="panel panel-warning text-center">
            <div class="panel-body">
                <h1 class="text-info">{{RamCpu.RamUsage}} MB</h1>
            </div>
            <div class="panel-footer panel-info">Available RAM</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="panel panel-warning text-center">
            <div class="panel-body">
                <h1 class="text-info">{{RamCpu.CpuUsage}} %</h1>
            </div>
            <div class="panel-footer panel-info">Total RAM</div>
        </div>
    </div>
</div>

Background timer application

public class BackgroundServerTimeTimer : IRegisteredObject
    {
        private readonly Timer _timer;
        private readonly Timer _timer1;
        private readonly IHubContext _hubContext;

        public BackgroundServerTimeTimer()
        {
            HostingEnvironment.RegisterObject(this);
            _hubContext = GlobalHost.ConnectionManager.GetHubContext();
            _timer = new Timer(OnTimerElapsed, null,TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
            _timer1 = new Timer(OnTimerElapsed1, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
        }

        private void OnTimerElapsed(object sender)
        {
            _hubContext.Clients.All.monthlyRainFall(DashboardData.GetChartDataForDashboard());
            _hubContext.Clients.All.customerInformations(DashboardData.GetCustomerInformations());
        }
        private void OnTimerElapsed1(object sender)
        {
            var server = new ServerPerformanceUtility();

           _hubContext.Clients.All.serverPerformanceDetails(server.GetServerPerformance());

        }

        public void Stop(bool immediate)
        {
            _timer.Dispose();
            _timer1.Dispose();
            HostingEnvironment.UnregisterObject(this);
        }
    }

Develop high quality software using NDepend

I just tried this tool and it looks pretty powerful, I still have to dig further in it.It has lots of features like

  • Code Rule and Code Query over LINQ (CQLinq)
  • Trend Monitoring
  • Harness Test Coverage Data
  • Code Quality, 82 Code Metrics
  • Explore Existing Architecture
  • Detect Dependency Cycles
  • Compare Builds and Code Diff
  • Compare Builds and Code Diff
  • Complexity and Diagrams
  • Continuous Integration Reporting
  • Warnings on Build Process Health
  • NDepend.API and Power Tools
  • Real-World Proof

If you are really interested to increase the quality of your product, you better to try this tool. NDepend offers a wide range of features to let the user analyze a code base.
It is often described as a Swiss Army Knife for .NET developers.

http://www.ndepend.com/Default.aspx

 

How to find method execution time in c#

In some time i wanted to measure method or the loop execution time in c#. I found that using c# Stopwatch class we can measure it. Here i have provided a simple example. Measuring code execution time can be used to optimize the code.

Here is the utility class which contain methods of calculating.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Elapsed_Time
{
    /// <summary>
    /// Source URL: http://stackoverflow.com/questions/2329079/how-do-you-convert-stopwatch-ticks-to-nanoseconds-milliseconds-and-seconds
    /// </summary>
    public static class Utility
    {
        public static long ElapsedNanoSeconds(this Stopwatch watch)
        {
            return watch.ElapsedTicks * 1000000000 / Stopwatch.Frequency;
        }
        public static long ElapsedMicroSeconds(this Stopwatch watch)
        {
            return watch.ElapsedTicks * 1000000 / Stopwatch.Frequency;
        }
        public static long ElapsedMiliseconds(this Stopwatch watch)
        {
            return watch.Elapsed.Milliseconds;
        }
        public static long ElapsedSeconds(this Stopwatch watch)
        {
            return watch.Elapsed.Seconds;
        }
        public static long ElapsedMinutes(this Stopwatch watch)
        {
            return watch.Elapsed.Minutes;
        }
        public static long ElapsedHours(this Stopwatch watch)
        {
            return watch.Elapsed.Hours;
        }
    }
}

and i have added another simple class which contain my looping methods and this class looks like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Elapsed_Time
{
    public class Common
    {
        public void runWithForLoop(List<int> values)
        {
            for (int i = 0; i < values.Capacity; i++)
            {

            }
        }
        public void runWithForEachLoop(List<int> values)
        {
            foreach (int i in values)
            {

            }
        }
    }
}

and my main class is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace Elapsed_Time
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch objStopWatch = new Stopwatch();
            Common c = new Common();
            List<int> values = new List<int>();

            for (int i = 0; i < 1000; i++)
            {
                values.Add(i);
            }

            objStopWatch.Start();
            c.runWithForLoop(values);
            objStopWatch.Stop();
            Console.WriteLine("Time elapsed for loop \n{0}\tHours \n{1}\tMinutes \n{2}\tSeconds \n{3}\tMiliseconds \n{4}\tMicroseconds \n{5}\tNanoseconds", Utility.ElapsedHours(objStopWatch), Utility.ElapsedMinutes(objStopWatch), Utility.ElapsedSeconds(objStopWatch), Utility.ElapsedMiliseconds(objStopWatch), Utility.ElapsedMicroSeconds(objStopWatch), Utility.ElapsedNanoSeconds(objStopWatch));

            objStopWatch.Restart();
            Console.WriteLine();
            objStopWatch.Start();
            c.runWithForEachLoop(values);
            objStopWatch.Stop();

            Console.WriteLine("Time elapsed foreach loop \n{0}\tHours \n{1}\tMinutes \n{2}\tSeconds \n{3}\tMiliseconds \n{4}\tMicroseconds \n{5}\tNanoseconds", Utility.ElapsedHours(objStopWatch), Utility.ElapsedMinutes(objStopWatch), Utility.ElapsedSeconds(objStopWatch), Utility.ElapsedMiliseconds(objStopWatch), Utility.ElapsedMicroSeconds(objStopWatch), Utility.ElapsedNanoSeconds(objStopWatch));

        }

    }
}

and the final output is

method_execution_time_32

how to set focus on textbox after post back in asp.net

I had this issue when i manually Post Back our application while searching and filtering a data in a Grid View  So i searched on the internet and finally i completed it with combination of several examples. These codes did not invented by me. But i combined these examples into one working example and all credits should goes to original developers or bloggers and stackoverflow website. This is how i Post Back the page while typing in a text box in asp.net with c# in our application.

asp.net code similar to below.

<asp:TextBox runat="server" ID="txtAutoSearch" AutoPostBack="True" 
  ontextchanged="txtAutoSearch_TextChanged" CssClass="content"
  ClientIDMode="Static" OnKeyUp="onTextBoxChanging(this);">
</asp:TextBox>

and the onTextBoxChanging(this) method similar to

<script type="text/javascript">

    var tbPostBackTimeout = null;

    function onTextBoxChanging(sender) {
        clearTimeout(tbPostBackTimeout);

        tbPostBackTimeout = setTimeout(function () {
          afterTimeout()
         }, 1000);
    }

    function afterTimeout() {
        __doPostBack('<%=txtAutoSearch.UniqueID %>', "onkeyup");

    }

</script>

here txtAutoSearch is the text box which cause the postback and on the asp.net c# section we can call java script function to focus end of txtAutoSearch text box.In the Page_Load section we can call this piece of code

if (Request.Params["__EVENTTARGET"] == txtAutoSearch.UniqueID && Request.Params["__EVENTARGUMENT"] == "onkeyup")
                {
                    focusToTextBox();
                }

and finally focusToTextBox() method similar to

private void focusToTextBox()
        {
            string str = "var input = $('#txtAutoSearch');";
            str += "var len = input.val().length;";
            str += "input[0].focus();";
            str += "input[0].setSelectionRange(len, len);";

            ScriptManager.RegisterStartupScript(Page, this.GetType(), "id", str, true);
        }