Logging the Http Response body in Application Insights


I can able to log the request message body in Application Insights using a method mentioned in this link https://stackoverflow.com/a/42772603/1094140 but I can’t able to log in the response message body. I am interested in logging the response message body as well. I am already logging the Post, Put, Delete Request message body.

When I tried to access the response body in the TelemetryInitializer I keep getting an exception with an error message saying that “stream was not readable. When I researched more I found that AzureInitializer is running as part of HttpModule(ApplicationInsightsWebTracking) so by the time it gets control response object is disposed of.

My idea is to record the response using a delegate handler since the response object is not disposed at the stage of the message handler. The message handler is part of the Web API life cycle i.e. similar to the HTTP module but confined to Web API Life cycle. When I developed and tested this idea, fortunately, It worked I recorded the response in the request message using message handler and retrieved it at the AzureInitializer (HTTP module whose execution happens later than the message handler i.e ASP.NET Web API Life cycle order). Here is the sample code.

public class AzureRequestResponseInitializer : ITelemetryInitializer
    public void Initialize(ITelemetry telemetry)
        var requestTelemetry = telemetry as RequestTelemetry;
        if (requestTelemetry != null && HttpContext.Current != null && HttpContext.Current.Request != null)
            if ((HttpContext.Current.Request.HttpMethod == HttpMethod.Post.ToString() 
                 || HttpContext.Current.Request.HttpMethod == HttpMethod.Put.ToString()) &&
                using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
                    HttpContext.Current.Request.InputStream.Position = 0;
                    string requestBody = reader.ReadToEnd();
                    if (requestTelemetry.Properties.Keys.Contains("requestbody"))
                        requestTelemetry.Properties["requestbody"] = requestBody;
                        requestTelemetry.Properties.Add("requestbody", requestBody);
            else if (HttpContext.Current.Request.HttpMethod == HttpMethod.Get.ToString() 
                     && HttpContext.Current.Response.ContentType.Contains("application/json"))
                var netHttpRequestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
                if (netHttpRequestMessage.Properties.Keys.Contains("responsejson"))
                    var responseJson = netHttpRequestMessage.Properties["responsejson"].ToString();
                    if (requestTelemetry.Properties.Keys.Contains("responsebody"))
                        requestTelemetry.Properties["responsebody"] = responseJson;
                        requestTelemetry.Properties.Add("responsebody", responseJson);

config.MessageHandlers.Add(new LoggingHandler());
public class LoggingHandler : DelegatingHandler
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        return base.SendAsync(request, cancellationToken).ContinueWith(task =>
            var response = task.Result;
            return response;

    private void StoreResponse(HttpResponseMessage response)
        var request = response.RequestMessage;

        (response.Content ?? new StringContent("")).ReadAsStringAsync().ContinueWith(x =>
            var ctx = request.Properties["MS_HttpContext"] as HttpContextWrapper;

            if (request.Properties.ContainsKey("responseJson"))
                request.Properties["responsejson"] = x.Result;
                request.Properties.Add("responsejson", x.Result);
Posted in Web Development | Tagged , , , , | 3 Comments

Kendo Grid No Records message

I wish kendo grid has an option to say whether we want to display ‘No Records Found’ message in the grid if there are no records to display.

When I goggled about it I found the following stack-overflow link which gave a solution for an grid .


I extended(actually hacked) it further to make it general so that it can be used across web application and below is the demo


Here is what I did

Grabbed all the kendo grids in a page by using $(‘.k-grid’) then looped through each kendo grid attaching an databound event handler. Event handler does the job of checking grid’s row count if it is zero then it insert a row in the grid. I got the event handler code from the stack-overflow and tweaked it to suit my needs.

The downside of this hack is that we need to have this script at the bottom of the page i.e. after all scripts or have it executed in the windows.settimeout like the above jsfiddle demo.

Here is the code

$(function() {
	function displayNoRecordsFound() {
		var grid = this;
		// Get the number of Columns in the grid
		var dataSource = grid.dataSource;
		var gridElement = grid.element;
		var colCount = gridElement.find('.k-grid-header colgroup > col').length;

		// If there are no results place an indicator row
		if (dataSource._view.length == 0) {
			gridElement.find('.k-grid-content tbody')
				.append('<tr class="kendo-data-row"><td colspan="' + colCount + '" style="text-align:center"><b>No Records Found</b></td></tr>');

		// Get visible row count
		var rowCount = gridElement.find('.k-grid-content tbody tr').length;

		// If the row count is less that the page size add in the number of missing rows
		if (rowCount < dataSource._take) {
			var addRows = dataSource._take - rowCount;
			for (var i = 0; i < addRows; i++) {
				gridElement.find('.k-grid-content tbody').append('<tr class="kendo-data-row"><td>&nbsp;</td></tr>');
	window.setTimeout(function() {
			$('.k-grid').each(function(e) {
			var grid = $(this).data('kendoGrid');
			grid.bind('dataBound', displayNoRecordsFound);
Posted in Uncategorized | Leave a comment

Kendo Custom Global Validator

Kendo provides the option for custom validation but when you want to do the custom validation across many pages or many sites or corporate wide we need to repeat the code multiple times.

I structured the custom code in a way that can be used via globally i.e. Define the custom code once in a separate file and just use the corresponding attribute to do the custom validation

Here is the example html

<input data-role=”datepicker” data-bind=”value: selectedDate” data-isValidDate data-isValidDateMsg=”Please enter valid date”>

Here data-isValidDate is the custom validation attribute and it is defined in a separate JavaScript file. Once it is defined and referred in a page we can start using the attribute.  So here we separated the custom validation code from the html so it can be managed better and can be used globally across pages, sites and corporate wide.

Here is the demo


Here is the code in the JavaScript file

kendo.ui.validator.rules.isValidDate = function (input, params) {

//ignore all other input that doesnt have this attribute
//case insensitive
if (!(input.is(‘[data-isValidDate]’) || input.is(‘[data-isvaliddate]’))) return true;

var retVal = false;

var kendoDatePicker = input.data(“kendoDatePicker”);
if (kendoDatePicker) {
var d = kendo.parseDate(kendoDatePicker.value(), [“yyyy/MM/dd HH:mm”, “MM/dd/yyyy HH:mm”, “MMM dd, yyyy h:mm tt”, “yyyy/MM/dd”, “MM/dd/yyyy”, “MMM dd, yyyy”]);
retVal = d instanceof Date;
if (retVal) input.closest(‘.k-datepicker’).removeClass(“red-box”);
else input.closest(‘.k-datepicker’).addClass(“red-box”);

return retVal;

// enabling user to pass the custom validation message.
kendo.ui.validator.messages.isValidDate = function (input) {
return typeof input.data(“isValidDateMsg”) === “undefined” ? typeof input.data(“isvaliddatemsg”) === “undefined” ? “Invalid Date” : input.data(“isvaliddatemsg”) : input.data(“isValidDateMsg”);

Posted in Uncategorized | 1 Comment

Kendo Extension to alert user when kendo grid has dirty data with in Kendo Window

One of the use case I recently encountered is to alert an user when he tries to close an kendo window and that kendo window has some dirty data in it’s kendo grid( user has edited the data in the kendo grid which is sitting on the kendo window).

I posted the working example @


There are two extensions I have created

1. One is kendo.data.DataSource.prototype.isDirty which will let you know whether the datasource is dirty (whether user has altered data)

How to use it : just call dataSource.isDirty() which will return a Boolean indicating the status.

2. Second extension is kendo.ui.Window.prototype.enableConfirmChangesForGrid  while will alert the user about the dirty changes

How to use it: call kendowindo.enableConfirmChangesForGrid(modalGrid) – pass the kendo grid instance which is sitting on the kendo window to the method.

You can refer http://jsfiddle.net/chandarmk/4ymkqL8L/ for working demo

Posted in Uncategorized | Leave a comment

OutputCache Handler to display .NET Internal’s outputcache values

We don’t have an out of box feature to show the internal values of the output cache. I developed an HttpHandler which will show the values of the internal output cache. There are many values inside the internal output cache right now we I am only dealing with the usercontrol output cache and outputcache values(mvc style) and ignoring the rest. Please feel free to extend this project.

Handler along with the demo project is under following GitHub. The demo project would display the values of UserControl Cache (Webform) and OutputCache which are internal to the .NET Framework


Posted in Uncategorized | Leave a comment

How ASP.NET MVC prevents Cross-site scripting(XSS) attack

This blog post is to explain Cross-site scripting with little more detail and how ASP.NET MVC prevents it to an extent.

Cross-site scripting attack is the act of injecting their own code (typically JavaScript but there are types of codes can be injected) into a website. The implication ranges from inconvenience to fatal damage.

An example for Inconvenience would be running a website which allows user to post a comment and user deliberately posts a comment which contains JavaScript with code to alert ‘I just did XSS attach successfully’ 1000 times in a loop.

An example for fatal damage would be running a bank website which allows user to post a comment and user deliberately post a comment which contains JavaScript with code to make request(note that this request carries the baking website cookie information since the code is running on banking website page) to the suspicious site. The suspicious site could then steal your banking website cookie information and other valuable information. There is some browser safeguard mechanism (Same origin policy) to stop this from happening and of course there are some workarounds and vulnerabilities from the server that attacker can leverage.

Simple way to avoid this attack is to encode the HTML code i.e. make that as NON HTML code for the browser. Beginning from ASP.NET MVC2 view engines encoded the string so that any html code inside the string will be made as non html code e.g. <div> will become &lt;div&gt; and <script> will become &lt;script&gt; so user doesn’t get a chance to inject their own HTML code.

Syntax for HTML encoding

1. <%: model.something %> syntax in WebForms

2.  It is automatic in Razor i.e. @model.something will auto encode automatically no
need to do anything to encode.

3. MVC3 HTML Helper methods return the encoded string automatically. e.g. Html.Label will return the encoded string

If you don’t need to encode use the following syntax

1. <%= %> syntax on webforms

2. HTML.Raw syntax on Razor

3. Return MvcHtmlString from the code to stop MVC from encoding it.

One can also stop accepting content that contains HTML code on the server side (ASP.NET configuration to stop accepting that content) but there are requirements where we need to accept those content and display in safe manner and above would be useful for those cases.

Posted in Uncategorized | Leave a comment

Data Graph IPhone App Description


IOS SDK was yet to give an api that will give the usage of cellular data from a given date or any date for that matter. We need to harvest data and process it to get the picture of cellular/Wi-Fi data usage from a reference data(usually billing start date). This app has got lot of back end processing to give that information to the user.

I started data tracking applications when my data usage bumps unusually I was curious to know when I am consuming lot of data. The other apps gives information about the data usage in a nice UI but they didn’t give me a usage history over time so I decided to develop this app to address that problem to an extent. This app tries to show the usage of the data over time in Graph format which is one of the uniqueness of this app. It captures the data usage whenever user opens the app or whenever there is a significant change in the user location.

This app also let you dynamically change the reference data/billing date unlike other apps. Most apps allows you to set a billing date but if you want to change the date in the middle you will lose some data usage information or need to wait until next billing cycle before it actually shows useful information.

This app is yet to be compatible with IOS 7.0 I will be upgrading it soon.

 Below is the description about the Data Graph App in the App Store.


Data Graph shows the usage of the valuable Cellular data (3G/4G/LTE/Edge/Gprs) and Wi-Fi data. One of the unique feature of the app is that it will show the usage of cellular data in graph format (up to max of past 3 days) so that user can have an idea when he is consuming more data i.e.  Tracking data over time.

The following are the usages of the app.

1. Shows the Cellular data usage for the current billing period with progress bar. It also lists other useful information about the cellular data usage.

2. Shows the recently used cellular data locations (past 3 days) in the Map whenever there is a significant change in the user location.

3. Shows the Wi-Fi data usage for the current billing period with progress bar and other useful information about the Wi-Fi data usage.

4. Shows the recent data usage in Graph format (Usage will get captured whenever user opens the app or whenever there is a significant change in the user location along with the location)

5. Enables user to configure the cellular billing period dynamically.


The app doesn’t collect any personal information and also doesn’t upload/send the data collected to any third party service and the data doesn’t even cross the App and its phone. It just stays on the device and older data would be purged by the app.

Here is the screenshot about the App description from iTunes.


Posted in Uncategorized | 3 Comments