October 19, 2017

WCF Service - How to log custom messages using Trace.Write()

In this post I will explain how to write custom logging messages in WCF tracing. I found many articles showing how to enable tracing and can see the default messages when service gets invoked. A good post from MSDN I found is:


It works well and get enabled to view default messages for different WCF methods. But I was facing problem when tried to write custom messages within WCF service.

After searching I found following trick to work for me. This will allow you to write custom messages from coding.

This is how your write log message from C# code using Trace class.

Trace.WriteLine("Custom message goes here...")
// We need to call Flush() method to empty the output buffer for tracing.

Next step is to add a listener in the Listeners Collection to get the receive messages from trace output methods, you can do this adding following lines in your app.config or web.config file.

    <trace autoflush="false" indentsize="4">
        <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Test\WcfTracingExample.log" />
        <remove name="Default" />

I used the path C:\Test\WcfTracingExample.log for log file, you may want to change according to your environment, just make sure that you have write permissions enabled for this directory and file.

You can also use other methods from Trace class apart from Write():

System.Diagnostics.Trace.TraceError("TraceError: GetData");
System.Diagnostics.Trace.TraceInformation("TraceInformation: GetData");
System.Diagnostics.Trace.TraceWarning("TraceWarning: GetData");
System.Diagnostics.Trace.WriteLine("WriteLine: GetData");
// Then call the Flush() method to empty the buffer.

September 17, 2017

SQL Running-Total with reset option

I received this question from one of my colleague and found worth sharing with you. The scenario is that we need to display the running total for amount field which could be done in different ways, as discussed here. But the requirement slightly differs in this case, because we need to reset running-total field if it encounters any negative value.

Lets start with a simple example.

We have a table @tblItems with some dummy data as follows:

declare @tblItems table(
 ID int identity(1, 1),
 Amount decimal(12, 3),
 RunningTotal decimal(12, 3) default(0)

insert into @tblItems(Amount)

Now if you apply the technique Update with Local Variable, as discussed in the post mentioned earlier:

DECLARE @RunningTotal decimal(12, 3) = 0;

UPDATE @tblItems
SET @RunningTotal = RunningTotal = @RunningTotal + Amount
FROM @tblItems;

SELECT ID, Amount, RunningTotal
FROM @tblItems

You will get output like this:

But the problem is that we need Running Total value as 0 for ID = 3 which in this case is showing -30.

To reset running total value, we can simply add a case statement and return 0 if there is any negative value. So the script will become this:

UPDATE @tblItems
SET @RunningTotal = RunningTotal = case when Amount < 0 then 0 else (@RunningTotal + Amount) end
FROM @tblItems;

And the output will be:

August 13, 2017

HTML5 - Display Arrows for Array Items on Canvas

I received this question from one of my followers, How to Display Data on Canvas. I found this interesting and dedicated some time to work on this requirement. In this post I will explain how did I achieve drawing arrows among array items' positions before and after sorting. Lets start with the same example as posted in this question.

We have the following array along-with a sorting function:

 var selectionSort = function(arr) {
  var j,i;
  var smallest;
  for(j = 0; j < arr.length ; j++)
   smallest = j;
   for(i = j + 1; i < arr.length ; i++)
    if(arr[i] < arr[smallest])
    smallest = i;
  var temp;
  arr[temp] = arr[smallest];
  arr[smallest] = arr[j];
  arr[j] = arr[temp];
 return arr;

 var array = [6,5,4,3,2,1];
 array2 = selectionSort(array.slice()).slice();

At this point, we have two arrays, array is the original unsorted array and array2 is the final sorted one. And we want to display both arrays on screen with drawing arrows to show the possible movement of items in positions inside the array.

Let first setup our UI to have canvas containers where we want to display array, here is the HTML I used for this example:


  <div id="myocontainer" style="width:70%;margin-left:100px;">
   <div style="width:300px;float: left;">
    <h2>Origianl Array</h2>
    <h4 style="float:left; margin-left:50px;margin-top:5px;"><u>Index</u></h4>
    <h4 style="float:left; margin-left:40px;margin-top:5px;"><u>Value</u></h4>
    <canvas id="cnvTable1" width="100%" height="100%"></canvas>
   <div style="width:300px;float:left; margin-left:300px;">
    <h2>Sorted Array</h2>
    <h4 style="float:left; margin-left:50px;margin-top:5px;"><u>Index</u></h4>
    <h4 style="float:left; margin-left:40px;margin-top:5px;"><u>Value</u></h4>
    <canvas id="cnvTable2"></canvas>

To make things simpler I created a class ArrayItem to represent array items by maintaining their index, value and with two helper functions getPosX, getPosY. getPosX, getPosY respectively describes the position of items being drawn on canvas for that particular item. Here is the code for this class:

 function ArrayItem(indx, val) {
   this.index = indx;
   this.value = val;
   this.getPosX = function() {
  return 50;
   this.getPosY = function() {
  return this.index * 50;

Since we are drawing objects on screen, in order to have better display on screen I have hard-coded values for positionX and relative value for positionY.

Next part is to create temp array of ArrayItem objects for both array and array2.

 var array1Items = [];
 $.each(array, function( index, value ) {
  array1Items.push(new ArrayItem(index, value));
 var array2Items = [];
 $.each(array2, function( index, value ) {
  array2Items.push(new ArrayItem(index, value));

Now comes the tricky part how to display array items on canvas. I write this printArray() function to display items on canvas.

 function printArray(arr1, canvasID, offsetX, offsetY)
  var c = document.getElementById(canvasID);
  var ctx = c.getContext("2d");
  c.width  = 800;
  c.height = 1000;

  ctx.font="30px Georgia";
  var tempX = 50;
  var tempY = 50;
  $.each(arr1, function( index, value ) {
   tempX = value.getPosX() + offsetX;
   tempY = value.getPosY() + offsetY;
   ctx.fillText(index, tempX, tempY);
   ctx.fillText(value.value, tempX + 70, tempY);

It takes following parameters:

  • arr1: the array we need to print
  • canvasID: container, where we have to print array items
  • offsetX: offset of X position, or left margin from the container.
  • offsetY: offset of Y position, or top margin from the container.

Using this function we can print our arrays:

 printArray(array1Items, "cnvTable1", 10, 50);
 printArray(array2Items, "cnvTable2", 10, 50);

Now comes the final part how to draw arrows showing possible movement among array items before and after sorting process. I have used this jQuery plugin Curved Arrow to draw arrows, you can download this js file and add reference to this along-with jQuery.

 $.each(array1Items, function( index, value ) {
  offsetX = 140;
  offsetY = 170;
  var newArrayItem = getArrayItemAfterSort(value.value);
  if(newArrayItem != undefined)
   console.log(index  + " - " + value.value + " - " + newArrayItem.index);
    p0x: value.getPosX() + offsetX,
    p0y: value.getPosY() + offsetY,
    p1x: value.getPosX() + offsetX,
    p1y: value.getPosY() + offsetY,
    p2x: newArrayItem.getPosX() + 570 + offsetX,
    p2y: newArrayItem.getPosY() + offsetY,
    lineWidth: 3,
 function getArrayItemAfterSort(valueToFind)
  var arrayItem = undefined;
  for (i = 0; i < array2Items.length; i++) {
   if(array2Items[i].value == valueToFind)
    arrayItem = array2Items[i];
  return arrayItem;

We are done with drawing arrows for array items. Lets try running this code and with the array items used in this example, you will see output similar to this:

Slightly changing the sequence of array items, i.e. var array = [6,4,1,5,2,3]; , you will see output like this:

August 6, 2017

MS SQL Server - Calculate Running Total

In this post we will see different ways to calculate running total using T-SQL. I am using Microsoft SQL SERVER 2008 R2. Let first setup a target table we want to calculate running values. Create a new table (say @tblItems) with the following script.

 declare @tblItems table(
  ID int identity(1, 1),
  Amount decimal(12, 3),
  RunningTotal decimal(12, 3) default(0)

Populate @tblItems table with some dummy records.

 insert into @tblItems(Amount)


This is the first way we are calculating running total using INNER JOIN.

 SELECT t1.ID, t1.Amount, RunningTotal = SUM(t2.Amount)
 FROM @tblItems AS t1
 INNER JOIN @tblItems AS t2
   ON t1.ID >= t2.ID
 GROUP BY t1.ID, t1.Amount

But this technique is not recommended for large tables, because as the table gets larger, each incremental row requires reading n-1 rows in the table. This may lead to failures, timeouts, or low performance.

Update with Local Variable:

 DECLARE @RunningTotal decimal(12, 3) = 0;

 UPDATE @tblItems
 SET @RunningTotal = RunningTotal = @RunningTotal + Amount
 FROM @tblItems;

 SELECT ID, Amount, RunningTotal
 FROM @tblItems

This method is more efficient than the above, but since the behavior is not properly documented, there are no guarantees about order.

Nested / Sub-Query

 SELECT ID, Amount,
  (SELECT SUM(amount) 
   FROM @tblItems t2 WHERE t2.ID <= t1.ID
  as RunningTotal 
 FROM @tblItems as t1

This method performs similar to self join technique, as the table gets larger, this may lead to failures, timeouts, or low performance.

OVER Clause (For SQL Server 2012 or above)

New window functions introduced in SQL Server 2012 make this task a lot easier.

 SELECT ID, Amount, 
   SUM(Amount) OVER (ORDER BY ID) as RunningTotal 
 FROM @tblItems 

It performs better than all of the above techniques.

July 26, 2017

AngularJS - ng-change is not working for input type file

In this post I will share the code how to detect the change event for HTML file input. We are supporting an old application written with AngularJS, and encountered this problem. If you are using default ng-change attribute, it will not work in AngularJS because of no binding support for file input control. I will show you I solved this problem in my case. I made a custom directive to listen for file input changes which enables us to invoke the custom event handler function. Lets start coding this solution:

Here is the custom directive fileOnChange definition:

 myApp.directive('fileOnChange', function () {
  return {
   restrict: 'A',
   link: function (scope, element, attrs) {
    var onChangeHandler = scope.$eval(attrs.fileOnChange);
    element.bind('change', onChangeHandler);

Here is the HTML for file input showing how to bind this directive to listen for file changes.

 <input type="file" file-on-change="onFileChange"> </input>

Now the final part of this task, write the handler function to do the actual work required on file change. Within the target controller, I write this handler function, in this example it is only showing the selected file name in alert box.

 $scope.onFileChange = function (event) {
  var filename = event.target.files[0].name;
  alert('File name: ' + filename);