Using context.Database.Log

In my recent project there was a requirement to develop a logging system each query performed by Entity framework should be logged with time stamp. It was all in the air when we started addressing performance tuning.
A good and common way to find out what’s going on behind the scenes is to use SQL Server profiler to trace all calls to the database. That way, you can see what SQL statements are being executed, how often, and how much time they take.
Logging all database operations can be achieved by assigning the DbContext.Database.Log property with an action that takes a string as a parameter.
When the Log property is set the following activities are logged −

  1. SQL for all different kinds of commands e.g. Queries, including inserts, updates, and 2. deletes generated as part of Save Changes
    3. Parameters
    4. Whether or not the command is being executed asynchronously
    5.. A time stamp indicating when the command started executing
    6. The command completed successfully or failed
    7. Some indication of the result value
    8. The approximate amount of time it took to execute the command

The DbContext.Database.Log property can be set to a delegate for any method that takes a string. Most commonly it is used with any TextWriter by setting it to the “Write” method of that TextWriter. All SQL generated by the current context will be logged to that writer. For example, the following code will log SQL to the console as well as log file:

public partial class MyDBCoreContext : DbContext
{
    static MyDBCoreContext()
    {
        Database.SetInitializer<MyDBCoreContext>(null);
    }

    public MyDBCoreContext(String connectionString)
        : base(connectionString)
    {
        this.Database.CommandTimeout = 240;
        this.Database.Log = DatabaseEfLogger;
    }

    public void DatabaseEfLogger(string sql)
    {
        Debug.Write(sql);
        var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        logger.Debug(sql);
    }
}

AngularJS in MVC with WEBAPI

These days, AngularJS and ASP.NET MVC is getting focus on web development world.In this post we will learn how to combine the best of both worlds and use the goodness of AngularJS in ASP.NET MVC by demonstrating how to use AngularJS in an ASP.NET MVC application. This sample application will help to understand how AngularJS can integrate on MVC UI frame work and call a web API to populate the data.
Controller
A controller is the JavaScript constructor function which contains data and business logic. The controller and the view talk to each other using the $scope object. Scope is nothing but binding. It binds a logical view model to physical model.
Service
A service is the function by which an instance gets created once per application life cycle. Anything shared across the controller should be part of the service. A service can be created in many different ways. The most popular way is by using the service method or the factory method.
Modules
Modules are the functions which contain other functions like a service or a controller. There should be at least one module per Angular app.
This Application has three sections. Before you copy this code please make sure you have created a ASP.NET MVC application ready:
1. Create ASP.NET Web Application using MVC template.
2. Add AngulrJs libraries to the application (This sample use web reference)
3. Create a WEBAPI get method to punch out JSON object.
Create a App.JS file under scripts and copy this code:

var CountryApp = angular.module('CountryApp', []);
CountryApp.controller('CountryController', function ($scope, CountryService) {
    getCountries();
    function getCountries() {
        CountryService.getCountries()
            .success(function (data) {
                $scope.countries = data;
            })
            .error(function (error) {
                $scope.status = 'Unable to load country data: ' + error.message;
            });
    }
});

CountryApp.factory('CountryService', ['$http', function ($http) {
    var CountryService = {};
    CountryService.getCountries = function () {
        return $http.get('/Api/Home');
    };
    return CountryService;
}]);

Copy this code in API controller

        public List<Country> Get()
        {
            return new List<Country>()
            {
                new Country() {Name = "USA",Region = "NA",ID =  1 },
                new Country() {Name = "India",Region = "Asia", ID = 2 }
            };
        }

Index.chtml page will looks like below

<!DOCTYPE html>
    <html >
    <head>
        <title ng-bind="models.helloAngular"></title>
    </head>
    <body>
<div ng-app="CountryApp" class="container">
<div ng-controller="CountryController">
<table class="table">
<tr ng-repeat="r in countries | filter : searchCountry">
<td>{{r.ID}}</td>
<td>{{r.Name}}</td>
<td>
                            {{r.Region}}</td>
</tr>
</table>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
        <script src="~/Scripts/Controllers/App.js"></script>
     </body>
    </html>

Model class

    public class Country
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Region { get; set; }
    }

Folder stracture should be:
Capture.PNG

JavaScript closure explained

Closures are a way to let a function have persistent, private variables – that is, variables that only one function knows about, where it can keep track of info from previous times.It is an inner function that has access to outer function variables and parameters in addition to its own variables in its scope. In simple words, it is a function inside another function. These functions could be named functions or Anonymous.
Here is a sample closure:
Think about a scenario where we need to keep track of the mouse click happened in a session on a page:

<script type="text/javascript">
    var incrementClickCount = (function () {
        var clickCount = 0;
        return function () {
            return ++clickCount;
        }
    })()
</script>
<input type="button" value="Click Me" onclick="alert(incrementClickCount());" />