ASP.NET Core 2.2, IIS and app_offline.htm Issue and Deployment Process

Recently we have migrated our .NET project at SpeQue POS having Web Api and MVC to unified ASP.NET Core. The biggest setback was the deployment process for .NET Core. As we all know ASP.NET Core runs on it own web server Kestrel . The challenge was,  In case ASP.NET deployment we can use the XCopy very easily without being worried about restarting the IIS or taking our website down.

In case ASP.NET Core it is not possible because the enter point dll or exe files are in used while Kestrel server is running.  IIS is used as reverse proxy which hosted our ASP.NET Core application (Kestrel webserver) In Process.

As we can see per the official document of ASP.NET Core 2.2 , Host on Windows with IIS under the section “Locked deployment files” there is a solution provided is the PowerShell automated script to drop app_offline.htm page which will shutdown the App pool and gracefully shut down the Kestrel webserver as well.

$pathToApp = 'PATH_TO_APP'
# Stop the AppPool
New-Item -Path $pathToApp app_offline.htm
# Provide script commands here to deploy the app
# Restart the AppPool
Remove-Item -Path $pathToApp app_offline.htm

But when we tried the script, something unexpected happened.
After dropping the app_offline.htm, App pool did not stopped right away and files were still locked. IIS and Kestrel started taking lot of time before it gracefully shutdown. The major side effect was our complete IIS
and other Application pool also stopped responding for next 10 minutes.
They started working only when we restarted the web server. The reason what we had figured it was that WAS which stopped responding.
After looking for other solution we have used the following PowerShell script which stops the App pool and wait till we get the confirmation that App pool is stopped and then we dropped the files for replacement

$pathToApp = 'F:\prod_web_core'
$appPoolName = 'ProdCoreAppPool'
# Stop the AppPool "Stopping Prod App Pool " + $appPoolName
Stop-WebAppPool -Name $appPoolName
while ((Get-WebAppPoolState -Name $appPoolName).Value -ne "Stopped")
{ "Waiting 1 second for site to stop..." Start-Sleep -s 1 }
# Provide script commands here to deploy the app
"Started copy the files from temp folder to the web folder"
Copy-Item "F:\prod_web_core_temp\*" -Destination $pathToApp -Recurse -Force
"Copied all the files"
# Restart the AppPool
"Bringing the site up"
Start-WebAppPool -Name $appPoolName
"Removing files from temp folder"
Remove-Item -Path "F:\prod_web_core_temp\*" -Recurse

So in above script first we issue the command to stop the App pool and then a loop which checks after each second if the status of the App pool is stopped. Once it is confirmed we copy the files from our temp location to the web folder and then restart the app pool.

On an average it does take 15-16 seconds that means our web application goes down for the same amount of time when we do the deployment which is really bad in compare to ASP.NET website under IIS which may be hardly goes down even we do copy the deployment file. We hope in future ASP.NET Core team will come up where deployment can be done with no downtime.

Real Time Notification with MongoDB Change Stream in C#

Mongodb 3.6 introduced many new features including Change Stream (https://docs.mongodb.com/manual/changeStreams/) . Change stream help us to listen to the collection change as they happen in real time. This is really useful feature to develop real time notification for any application.

In SpeQue POS the product that our company developed had the similar requirement and we were doing the polling to check like every 10 seconds if their is any change has occurred or not in the collection. In our project we have a collection where the document is inserted from different sources and we have one service looking for this change and sending the notification.

We had achieved this by adding Timestamp key with each document and our polling service used to store the last polling time and make the next query with condition where Timestamp is less than the current time and Status is “Pending (2)” . So our document look like this

{
“_id” : ObjectId(“5bc9896250a10312807ef51b”),
“Detail” : “One order arrived at Table 6”,
“TS” : ISODate(“2018-10-19T07:36:02.360Z”),
“S” : 2
}

and our query will look like this

function BsonDocument GetOneDocumentToProcess(){
var filter = Builders.Filter;
var options = new FindOneAndUpdateOptions()
{
ReturnDocument = ReturnDocument.Before
};
var searchQuery = filter.And(filter.Lte("TS", currentTime), filter.Eq("S", (int)PrintQueueStatus.Pending));
MongoDatabase.Instance.GetCollection("PrintQueue").FindOneAndUpdate(searchQuery,Builders.Update.Set("S", (int)PrintQueueStatus.Completed).Set("CTS",DateTime.Now),options);}

The poll query uses the findAndModify method (https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/) which atomically update the document and return the document as well.

This solution works fine but the issue here is,  how do we decide at what frequency which we need to call this method. If we do it too frequently it will add too much overhead on DB and if we do it with delay it means we get the notification late.

function BsonDocument GetNotification(){
while(true)
{
Thread.Sleep(3000);
var doc = GetOneDocumentToProcess();
if(doc != null){ return doc; }
}
}

With the introduction of Change stream we made the change in our approach and starting a watch on the collection for any kind of insert

public void StartCollectionWatch(){
// We are just watching insert operation
var pipeline = new EmptyPipelineDefinition().Match("{ operationType: { $eq: 'insert' } }");
// start the watch on the collection
using (var printQueueStream = mongoDB.GetCollection("PrintQueue").Watch(pipeline).ToEnumerable().GetEnumerator())
{
// loop is required so that we are always connected and looking for next document
 while (true)
 {
  try
  {
// If we get the document, serialize to our model
  printQueueStream.MoveNext();
  var printQueueEntry = DeSerializePrintQueueKOTDocument(printQueueStream.Current.FullDocument);
// We are locking the collection before inserting the latest record to avoid multiple insert
  lock (_lockKOTEntry)
  {
   if (!_readyToBePickedKOTList.ContainsKey(printQueueEntry.RestaurantId))
   _readyToBePickedKOTList.Add(printQueueEntry.RestaurantId, new List());
  _readyToBePickedKOTList[printQueueEntry.RestaurantId].Add(printQueueEntry);
  }
 unHandledExceptionCounter = 0;
 }
 catch (Exception ex)
 {
// in case of some error we are incrementing the counter
unHandledExceptionCounter++;
 if (unHandledExceptionCounter == 1)
 {
  logger.Error($"Unhandled exception with the counter {unHandledExceptionCounter}.", ex);
 }
 else if (unHandledExceptionCounter > 10)
 {
  logger.Error($"Too many unhandled exception with the counter {unHandledExceptionCounter}. We will break the loop.", ex);
  break;
 }
}
}
}
}

Above method will always block on thread because the moment any insert operation will happen it will yield the document and just after we have processed the document we have to start watching again. So we have added a class level lookup list where this method keep on queuing the document and another method keep on polling it and return to the client. Now we might think, we are again polling but the advantage here is we are making database or network call to get the document, we are just polling locally in-memory collection which is way faster.

In the above method we are watching the collection by Watch method which takes  Pipeline as one of the parameter. Pipeline can be used to put different kind of filter to avoid un necessary document sent over to us and then application discard it. In our example we have made sure that we only need those document which is “inserted”.

I have added the while loop after we have created the Watch so that after each time we get one “inserted” document we again wait for the cursor to give another document.

The above approach is having one practical issue i.e. what happens if the Thread got aborted by the Application pool in that case we may miss the “inserted” document because Watch only watches from the time it has made the connection to the database server if not passed on “resume able” token of last time it was connected. It can solved by 2 approaches

  1. We can persists the “resume able” token in the database after each time it yield and read the database before starting the watch and pass on the “resume able” token
  2. In our system we also have the Status key which is marked done after it is processed, so before we start the Watch, we run the database query to pull all the document in the “Pending” status and then start the Watch.

As our application is hosted as ASP.NET MVC, we used our Global.asax Application_Start to start the above method on the separate thread.

protected void Application_Start(){
 new Thread(() => StartCollectionWatch()).Start();
}

Binary Search : learning by examples

Binary search , a very handy approach to solve the problem within the time limit as it has complexity of O(logN). Binary search is applied on the order set like sorted array. You must wonder why we need to have sorted array to apply the binary search while we are looking for a particular number ? Binary search can be applied on any set of data if following criteria is met and in coming blogs i will pick one by one many problems and solve it by applying the rule stated here. The nature of sorted may be misguiding sometime, so the underneath criteria is if am looking for an answer is there a way to know if i my point of search is currently above or below or at the same place where currently i am at. For example in the given array


{5 , 9 , 6 , 1 , 8} ( starting index is at 1 )

, if i am looking for 6 and i am at 2nd position (number 9) can i get the answer in O(1)  if I have to look below or above position of my current index (index 2) ? The answer is no but if i sort the array


{1 , 5 , 6 , 8 , 9}

, now i can answer this question in O(1) ( i hope you must have got why ? Because we can compare the value at the current index and the value i am looking for  ). This the power of binary search which allows the search area scope to become half till we find the number or we are in position to say it does not exits. To read more you can refer the top coder link here .

I am going to making it more easy to grasp with how i perceived the question and why I thought that it can be solved by binary search. In some question this decision is hidden in the question. I will put the question and my own solution from different coding platform like SPOJ , codechef , HackerRank, HackerEarth and codeforces.

See you all in the next blog post on the binary search  with  our first problem and solution 🙂

Real time Auto Complete using TRIE in C#

Its being very long time I have been using the auto complete feature available in jqueryUI and AJAX toolkit in ASP.NET.  I have been using the very native approach to get the possible words by making the call to the database and using the regular expression. The possible query to the database would look like this

SELECT Id , Name FROM tblName WHERE Name LIKE @prefix  + ‘%’;

The problem with this kind of approach is that we make many calls to the database which will be very costly.

In recent time I am learning different data structure and their practical application. In my recent encounter to TRIE data structure (read more) I have the chance to use it my of the project to use it as real time for the auto complete feature. There are many articles on the TRIE and its concept, I have tired to put all the information and my own use to make it work for the auto complete. I am using the ASP.NET MVC Controller to serve the list of the auto complete words , for the UI I am using the jQuery UI autocomplete plugin. I am using the basic concept of ASP.NET like caching etc. to make it more real time. I am not worried about the database as such but I will have method to get the data from the database which can be used for any kind of storage system.

TRIE kind of data structure is good for words because we fixed number of characters and they are less in number. For example take two words like TREAT and TRAITER. As you can see TR is common prefix for both the word,so rather than storing twice we can have a common storing container . So if we see tree by it will be T->R and then two different branch at this level for E and A.

Now it is time for some code. I am going to start with the TRIENode class which will represent the node of the TRIE tree. TRIENode will have following property

1) Children : List of all the possible letter as key and address for the next node.

2) IsCompleteWord : It will mark the completeness of the word and we will use to know if we can use till this node path as the complete word.

3) PrefixCount : It will hold the number of words can be formed, if we will use the word till this node as prefix.

4) Ids : It will contain the multiple Ids of the name , in case we have duplicate names , we need to store the multiple Ids.

5) ActualChar : It will contain the original case of the letter of the word.In case of Children key we will store the lower version of the letter as the key.

TRIENode class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TRIEAutoComplete.Models
{
    public class TRIENode
    {
        private SortedDictionary<string, TRIENode> _children;
        private bool _isCompleteWord;
        private int _prefixCount;
        private List<string> _ids;
        private string _actualChar;
        public string ActualChar
        {
            get
            {
                return _actualChar;
            }
            set
            {
                _actualChar = value;
            }
        }
        public List<string> Ids
        {
            get
            {
                return _ids;
            }
            set
            {
                _ids = value;
            }
        }
        public int PrefixCount
        {
            get
            {
                return _prefixCount;
            }
            set
            {
                _prefixCount = value;
            }
        }
        public SortedDictionary<string,TRIENode> Children
        {
            get
            {
                return _children;
            }
            set
            {
                _children = value;
            }
        }

        public bool IsCompleteWord
        {
            get
            {
                return _isCompleteWord;
            }
            set
            {
                _isCompleteWord = value;
            }
        }

        public TRIENode()
        {
            _children = new SortedDictionary<string, TRIENode>();
            _isCompleteWord = false;
            _prefixCount = 0;
            _actualChar = string.Empty;
            _ids = new List<string>();
        }
    }
}

TRIE.cs : It will be contain all the required methods. I have added an extra method RemoveWord , it will remove the associated Ids of the existing word and if there is no Ids left it will make the IsCompleteWord flag false.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TRIEAutoComplete.Models
{
    public class TRIE
    {
        public TRIENode CreateNode()
        {
            return new TRIENode();
        }

        public void AddWord(string word , TRIENode rootNode , string id)
        {
            int len = word.Length;
            if (len == 0)
            {
                rootNode.PrefixCount++;
                rootNode.IsCompleteWord = true;
                rootNode.Ids.Add(id);
                return;
            }
            for (int i = 0; i < len; i++)
            {
                string key = word.Substring(i, 1);
                string lowerVersionKey = key.ToLower();
                if(!rootNode.Children.ContainsKey(lowerVersionKey))
                {
                    rootNode.Children.Add(lowerVersionKey, new TRIENode());
                    rootNode.Children[lowerVersionKey].ActualChar = key;
                }
                rootNode.PrefixCount++;
                rootNode = rootNode.Children[lowerVersionKey];
            }
            rootNode.IsCompleteWord = true;
            rootNode.Ids.Add(id);

        }

        public void RemoveWord(string word, TRIENode rootNode, string id)
        {
            int len = word.Length;
            if (len == 0)
            {
                rootNode.PrefixCount--;
                if (rootNode.PrefixCount == 0)
                    rootNode.IsCompleteWord = false;
                rootNode.Ids.Remove(id);
                return;
            }
            for (int i = 0; i < len; i++)
            {
                string key = word.Substring(i, 1);
                string lowerVersionKey = key.ToLower();
                rootNode.PrefixCount--;
                rootNode = rootNode.Children[lowerVersionKey];
            }
            rootNode.Ids.Remove(id);
            if (rootNode.Ids.Count == 0)
                rootNode.IsCompleteWord = false;
        }

        public TRIENode GetMatchedNode(string prefix, TRIENode rootNode)
        {
            int len = prefix.Length;
            if (len > 0)
            {
                for (int i = 0; i < len; i++)
                {
                    string key = prefix.Substring(i, 1);
                    string lowerVersionKey = key.ToLower();
                    if (!rootNode.Children.ContainsKey(lowerVersionKey))
                        return null;
                    rootNode = rootNode.Children[lowerVersionKey];
                }
                return rootNode;
            }
            return null;
        }

        public void GetAutoCompleteList(TRIENode matchedNode, string completeWord, List<AutoCompleteResult> wordList)
        {
            foreach (var item in matchedNode.Children)
            {
                string tmpWord = completeWord + item.Value.ActualChar;
                if(item.Value.IsCompleteWord)
                {
                    AutoCompleteResult r = new AutoCompleteResult();
                    r.id = string.Join(",", item.Value.Ids);
                    r.label = tmpWord;
                    r.value = tmpWord;
                    wordList.Add(r);
                }
                GetAutoCompleteList(item.Value, tmpWord , wordList);
            }
        }
    }
}

AutoCompleteResult.cs : It will contain the result for the JSON structure for auto complete of the jqueryUI.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TRIEAutoComplete.Models
{
    public class AutoCompleteResult
    {
        public string id;
        public string label;
        public string value;
    }
}

AutoCompleteController.cs : MVC Controller containing all the possible actions . To make it more real time , I am caching the root node when I have loaded all the names from my database. Fetching the names again from the database is very costly affair. I have added couple of action method to use the Delete and Add of the names and cache it again. We can delete or add the names from the database in normal way and once we succeed we can delete or add from the word from the cache itself .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using TRIEAutoComplete.Models;

namespace TRIEAutoComplete.Controllers
{
    public class AutoCompleteController : Controller
    {
        TRIE trieDS = new TRIE();
        TRIENode rootNode = new TRIENode();
        //
        // GET: /AutoComplete/
        public ActionResult Index()
        {
            rootNode = trieDS.CreateNode();
            trieDS.AddWord("Name One", rootNode, "1");
            trieDS.AddWord("Name Two", rootNode, "2");
            trieDS.AddWord("Name One", rootNode, "4");
            HttpContext.Cache["rootNode"] = rootNode;
            return View();
        }

        public JsonResult AutoCompleteList(string term)
        {
            List<AutoCompleteResult> result = new List<AutoCompleteResult>();
            if (HttpContext.Cache["rootNode"] != null)
                rootNode = (TRIENode)HttpContext.Cache["rootNode"];
            TRIENode matchedNode = trieDS.GetMatchedNode(term, rootNode);
            trieDS.GetAutoCompleteList(matchedNode, term, result);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public void AddWord(string word, string id)
        {
            if (HttpContext.Cache["rootNode"] != null)
                rootNode = (TRIENode)HttpContext.Cache["rootNode"];
            trieDS.AddWord(word, rootNode, id);
            rootNode = (TRIENode)HttpContext.Cache["rootNode"];
        }

        public void RemoveWord(string word , string id)
        {
            if (HttpContext.Cache["rootNode"] != null)
                rootNode = (TRIENode)HttpContext.Cache["rootNode"];
            trieDS.RemoveWord(word, rootNode, id);
            HttpContext.Cache["rootNode"] = rootNode;
        }

    }
}
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>AutoComplete : Example</title>
    <script src="../../Scripts/jquery-1.8.2.min.js"></script>
    <script src="../../Scripts/jquery-ui-1.8.24.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#txtName").autocomplete({
                source: '/AutoComplete/AutoCompleteList',
                minlength: 2,
                select: function (event, ui) {
                }
            });
        });
    </script>
</head>
<body>
    <div>
        <input type="text" name="txtName" id="txtName" />
        <input type="hidden" name="hydId" id="hydId" />
    </div>
</body>
</html>

I am using the select method in the jquery UI autocomplete to get the Id or Ids of the selected option and I will send the same to get the list of the possible names and extra detail from the database. In the database you can easily index the Id and get the list much faster. Currently I have applied the same in my one of the project. Please do share or correct me in case I have missed something .

Convert your hindi message text in hex : php way

Very recently i have a requirement to send the SMS in hindi to my customer. The mobile vendor need it to be converted in the HEX encoding before sending them through the http POST. It was easy to do in C# but i need to spent some time do the same in PHP. The inbuild function dechex was not sufficent. I have got the code from here : http://tech.groups.yahoo.com/group/php-objects/message/8555 (all credit should go here) , but the function was not encoding the number and english letter in the HEX. So i have made some changes to make it work. Now this function can be used to hex all unicode chareter.In my case hindi mixed with english or numbers.

function utf8_to_unicode($str) {
        $unicode = array();
        $values = array();
        $lookingFor = 1;
        for ($i = 0; $i < strlen($str); $i++) {
            $thisValue = ord($str[$i]);
            if ($thisValue < 128) {
                $number = dechex($thisValue);
                $unicode[] = (strlen($number) == 1) ? '%u000' . $number : "%u00" . $number;
            } else {
                if (count($values) == 0)
                    $lookingFor = ( $thisValue < 224 ) ? 2 : 3;
                $values[] = $thisValue;
                if (count($values) == $lookingFor) {
                    $number = ( $lookingFor == 3 ) ?
                            ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ) :
                            ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64
                            );
                    $number = dechex($number);
                    $unicode[] =
                            (strlen($number) == 3) ? "%u0" . $number : "%u" . $number;
                    $values = array();
                    $lookingFor = 1;
                } // if
            } // if
        }
        return implode("", $unicode);
    }
$hexMessage = str_replace('%u', '',utf8_to_unicode($_message));

findAndModify in mongoDB , a practical example

Its been almost more than a year that I am working on mongoDB with C# as well as PHP. Recently I have encounter a very different requirement. I would start with my mongoDB collection schema , which will be give us better picture of my requirement.I have two collection
1) Student collection : Where I keep all the information about the student profile like Name , Date of Birth etc. At the same time to take more advantage of document approach and lack of joins, I have sub document , which contains all the payments made by the student over period of time. So structure can look like this.

{
"_id" : STUDENTID, "Name" : "myName" , 
"Payments" : 
 [
  { "Id" : PAYMENTID1, "AmountPaid" : 34000 , "PaymentDate" : '1/03/2013' , PaymentType : "Admission" } , 
  { "Id" : PAYMENTID2, "AmountPaid" : 4000 , "PaymentDate" : '1/03/2013' , PaymentType : "Installment"  }
 ]
}

2) Report collection : This collection is used from reporting prospective , which store the quick view data of daily payments and used by admin to see the daily collection. Collection schema may look like this :

{"Id" : "01_Mar_2013" , 
"AdmissionPayments" : 
[
{"Name" : "myName" , "PaymentId" : PAYMENTID1, "Amount" : 34000}
] , 
"InstallmentPayment" : 
[
{"Name" : "myName" , "PaymentId" : PAYMENTID2, "Amount" : 4000
}
]

All looked good , easily and fast I can show the daily report snapshot to the admin , by querying on the Id, but still we have not used our findAndModify, now we are going to use it.
Just assume you need to delete the student entry , then obviously we will delete the payments history also from the report collection, so what I have to do ? First I have to get the student document and update it with “Active” : False .
So this has become two call to mongoDB.
1) To get the detail of student
2) Update the Active status and save.

Why we need to pull the student document ? , because we need to loop through the payments made by student and then we have to go and update the report collection by making these payments “Active” : False .

Now with findAndModify command we can do this one in one step. Below working code will show how.

//Remember you need  PHP mongoDB driver 1.3.0 and greater , otherwise use other syntax i.e. using command.
//Check here : http://php.net/manual/en/mongocollection.findandmodify.php
$retval = $studentCollection->findAndModify(
     array("_id" => $studentId), // searchQuery
     array('$set' => array('Active' => false, "Reason" => "Duplicate entry" "DeleteDate" => new MongoDate())), // UpdateQuery
     array("Payments" => 1), // What columns will be sent back from database , I only need the Payments data.
     array(
        "new" => false // Give the document before the update status, it is fine for me.
    )
);
if($retVal) // If we have some return value
{
  foreach($retVal['Payments'] as $payment)
  {
      $paymentId = $payment['Id'];
      //Continue with the  next set of work like deleting the data from ReportCollection
  }
}

Above code not only update the status of the student document but at the same time returned us Payment history and all in on go.
I hope my approach will help you to grasp it better.

Techgig : Strange Sequences solution

Today I am picking the problem I am not sure if I know the best way to do it. I have used the tree data structure in solving the problem.

Problem : read here http://www.techgig.com/codecontest/problem/Strange-Sequences-30

Solution : I am going to use tree data structure to solve the problem . The reason behind using tree data structure is, we have multiple option at each point ( {-2 , 0 , 3} condition). In the tree approach we have to stop getting more nodes if we either reached total summation limit or no next number is satisfying the condition of {-2 , 0 , 3}. First I will generate the tree and later I will traverse to print it. I will start my tree parent node from the number 1 till the number given as input. For each number I will try to generate the tree nodes satisfying both the condition and start printing.

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Text;
public class CandidateCode
{
    public static string sum_value(int input1)
    {
        StringBuilder sb = new StringBuilder();
        string output1 = string.Empty;
        if (input1 > 0 && input1 <= 10)
        {
            int globalCounter = 0;
            for (int z = 1; z <= input1; z++)
            {
                List<string> solutions = new List<string>();
                Graph<string> N = new Graph<string>();
                var startingNode = new GraphNode<string>(globalCounter.ToString());
                N.AddNode(startingNode);
                //We have used stack to reach end of each list faster.
                Stack<GraphNode<string>> stack = new Stack<GraphNode<string>>();
                stack.Push(startingNode);
                List<string> visitedNode = new List<string>();
                //NOTE ! : Rather than using three dictionary we can create a class and add these three as property
                Dictionary<string, string> outputString = new Dictionary<string, string>();// It will store the string we need to output something like {1,1,1} {2,1}
                Dictionary<string, int> totalSum = new Dictionary<string, int>(); //It will contain the total summation at the level
                Dictionary<string, int> nodeValues = new Dictionary<string, int>(); //It will contain the node value it self.
                outputString[globalCounter.ToString()] = z.ToString();
                totalSum[globalCounter.ToString()] = z;
                nodeValues[globalCounter.ToString()] = z;
                globalCounter++;
                while (stack.Count > 0)
                {
                    var item = stack.Pop();
                    if (visitedNode.Contains(item.Value))
                    {
                        continue;
                    }
                    var possibleVal = Possible(nodeValues[item.Value]);
                    for (int i = 0; i < possibleVal.Length; i++)
                    {
                        if (possibleVal[i] <= 0 || (possibleVal[i] + totalSum[item.Value] > input1))
                            continue; // Condition are not met , we have end of this tree nodes.
                        if (possibleVal[i] + totalSum[item.Value] != input1)
                        {
                            int rnd = globalCounter; // Just to give the uniqueId to each node. Nothing useful else wise.
                            var addedNode = new GraphNode<string>(rnd.ToString());
                            item.NeighBours.Add(addedNode);
                            outputString[rnd.ToString()] = outputString[item.Value] + "," + possibleVal[i];
                            totalSum[rnd.ToString()] = totalSum[item.Value] + possibleVal[i];
                            nodeValues[rnd.ToString()] = possibleVal[i];
                            stack.Push(addedNode);
                            globalCounter++;
                        }
                        else
                        {
                            //We have got exact matching summation. So one sequence is done. 
                            solutions.Add("{" + outputString[item.Value] + "," + possibleVal[i] + "}");
                        }

                    }
                    visitedNode.Add(item.Value);
                }
                //To get the output in lexicographic order 
                for (int k = solutions.Count - 1; k >= 0; k--)
                {
                    sb.Append(solutions[k]);
                }
            }
            sb.Append("{");
            sb.Append(input1);
            sb.Append("}");


            output1 = sb.ToString();
        }
        else
        {
            output1 = "-999"; // We have sometest cases for this also 🙂 
        }
        return output1;
    }

    public static int[] Possible(int number)
    {
        return new int[] { number - 2, number, number + 3 };
    }
}

    public class Node<T>
    {
        private T data;
        private NodeList<T> neighbours = null;
        public Node()
        {
        }
        public Node(T data)
            : this(data, null) { }

        public Node(T data, NodeList<T> neighbours)
        {
            this.data = data;
            this.neighbours = neighbours;
        }

        public T Value
        {
            get
            {
                return this.data;
            }
            set
            {
                this.data = value;
            }
        }

        protected NodeList<T> NeighBours
        {
            get
            {
                return this.neighbours;
            }
            set
            {
                this.neighbours = value;
            }
        }
    }
    public class NodeList<T> : Collection<Node<T>>
    {
        public NodeList() : base() { }
        public NodeList(int initalSize)
        {
            for (int i = 0; i < initalSize; i++)
            {
                base.Items.Add(default(Node<T>));
            }
        }
    }
    public class GraphNode<T> : Node<T>, IComparable<GraphNode<T>>
    {
        private List<int> costs;
        public int Priority;
        public GraphNode() : base() { }
        public GraphNode(T value) : base(value) { }
        public GraphNode(T value, NodeList<T> neighbours) : base(value, neighbours) { }
        new public NodeList<T> NeighBours
        {
            get
            {
                if (base.NeighBours == null)
                    base.NeighBours = new NodeList<T>();
                return base.NeighBours;
            }
        }
        public List<int> Costs
        {
            get
            {
                if (costs == null)
                    costs = new List<int>();
                return costs;
            }
        }
        public int CompareTo(GraphNode<T> other)
        {
            if (this.Priority > other.Priority)
                return 1;
            return 0;
        }
    }
    public class Graph<T>
    {
        private NodeList<T> nodeSet;
        public Graph() : this(null) { }
        public Graph(NodeList<T> NodeSet)
        {
            if (NodeSet == null)
                this.nodeSet = new NodeList<T>();
            else
                this.nodeSet = NodeSet;
        }
        public void AddNode(GraphNode<T> node)
        {
            nodeSet.Add(node);
        }
        public void AddDirectedEdge(GraphNode<T> from, GraphNode<T> to, int weight)
        {
            from.NeighBours.Add(to);
            from.Costs.Add(weight);
        }
        public void AddUnDirectedEdge(GraphNode<T> from, GraphNode<T> to, int weight)
        {
            from.NeighBours.Add(to);
            from.Costs.Add(weight);
            to.NeighBours.Add(from);
            to.Costs.Add(weight);
        }
        public void RemoveUnDirectedEdge(GraphNode<T> from, GraphNode<T> to)
        {
            from.NeighBours.Remove(to);
            to.NeighBours.Remove(from);
        }
        public NodeList<T> Nodes
        {
            get
            {
                return this.nodeSet;
            }
        }
    }

Last time my solution has reached in 99 but when I tried now it only reached in 88 (Note it is passing all the test cases , but I think performance is not that much good compare to best one.). I know this is not the best approach and there can be better way of doing it, but It was good learning for me :). Please share if you have better way of doing it.

Techgig : Toll Tax Solution

With this blog , I will be using Graph and Priority Queue kind of data structure. I will not go much in detail about about these two but I will definitly guide and post the links which will help you to grasp them very easily as I did. I will suggest to visit these links before further reading if you are not aware of both the data structure. I am adding the part of the code I am going to use in solving the techgig problem.

Priority Queue : Wiki : http://en.wikipedia.org/wiki/Priority_queue . Code and implementation in C# : http://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx

Graph data structure in C# : http://msdn.microsoft.com/en-us/library/aa289152(v=vs.71).aspx

Problem : read here : http://www.techgig.com/codecontest/problem/Toll-Tax-34 .
Solution : The problem is direct and one of the good example to show the working code of Kruskal’s Algorithm for finding the shortest possible path in positive weighted graph. Graph structure can be used where ever you may have multiple choice or path need to be chosen . You need to check all the possible points before you can decide what will be the minimum cost. We have one assumption while creating the graph, that the edges are undirected , it means toll tax of going from A – B will be same as B – A. This assumption does not mean that you can not use the same logic for directed cases. The challenge in the problem is to create all the nodes and the related toll tax amount to move from one node to another.

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;

public class UserMainCode
{
    //Assume following return types while writing the code for this question. 
    public static int output1;
    public static void Minimum_TollTax(string input1, int input2, string input3, string input4)
    {
        string[] cites = input1.TrimStart('{').TrimEnd('}').Split(',');
        //First city will be origin and second city will be destination
        string[] originandDestinationCity = input4.TrimStart('{').TrimEnd('}').Split(',');
        input3 = input3.TrimStart('{').TrimEnd('}');
        int totalCites = cites.Length;
        Graph<string> cities = new Graph<string>();
        Dictionary<string, int> costTable = new Dictionary<string, int>(totalCites);
        Dictionary<string, int> cityMapping = new Dictionary<string, int>();//This will be used to map the index of the city with city Id.
        PriorityQueue<GraphNode<string>> q = new PriorityQueue<GraphNode<string>>();
        for (int i = 0; i < totalCites; i++)
        {
            GraphNode<string> graphNode = new GraphNode<string>(cites[i]);
            costTable[cites[i]] = cites[i] == originandDestinationCity[0] ? 0 : Int32.MaxValue; // Start with cost table
            cities.AddNode(graphNode);
            cityMapping.Add(cites[i], i);
            if (cites[i] == originandDestinationCity[0])
            {
                graphNode.Priority = 0; // Setting up the Priority low will be picked first when we Dequeue
                q.Enqueue(graphNode);
            }
        }
        int startIndex = 0;
        bool startofTestData = false;
        List<string> edgeCity = new List<string>();
        //Code to read the data and create the graph edge and it cost.
        for (int j = 0; j < input3.Length; j++)
        {
            if (input3[j] == '(')
            {
                startIndex = j;
                startofTestData = true;
                edgeCity.Clear();

            }
            else if (input3[j] == ',')
            {
                if (startofTestData)
                {
                    edgeCity.Add(input3.Substring(startIndex + 1, (j - startIndex - 1)));
                    startIndex = j;
                }
            }
            else if (input3[j] == ')')
            {
                startofTestData = false;
                int d = int.Parse(input3.Substring(startIndex + 1, (j - startIndex - 1)));
                //We have UnDirected Edge because we have same cost either going from A - B or B - A .
                cities.AddUnDirectedEdge((GraphNode<string>)cities.Nodes[cityMapping[edgeCity[0]]], (GraphNode<string>)cities.Nodes[cityMapping[edgeCity[1]]], d);
                edgeCity.Clear();
                startIndex = j;
            }

        }
        List<string> processedNodes = new List<string>();
        //Kruskal's Algorithm implementation
        while (q.Count() > 0)
        {
            GraphNode<string> c = q.Dequeue();
            if (!processedNodes.Contains(c.Value))
            {
                processedNodes.Add(c.Value);
                for (int i = 0; i < c.NeighBours.Count; i++)
                {
                    string n = c.NeighBours[i].Value;
                    int v = c.Costs[i];
                    if (costTable[n] > v + costTable[c.Value])
                    {
                        costTable[n] = v + costTable[c.Value];
                        ((GraphNode<string>)c.NeighBours[i]).Priority = v + costTable[c.Value];
                        q.Enqueue((GraphNode<string>)c.NeighBours[i]);
                    }
                }
            }

        }
        output1 = costTable[originandDestinationCity[1]];
    }

}
public class PriorityQueue<T> where T : IComparable<T>
{
    private List<T> data;

    public PriorityQueue()
    {
        this.data = new List<T>();
    }

    public void Enqueue(T item)
    {
        data.Add(item);
        int ci = data.Count - 1; // child index; start at end
        while (ci > 0)
        {
            int pi = (ci - 1) / 2; // parent index
            if (data[ci].CompareTo(data[pi]) >= 0) break; // child item is larger than (or equal) parent so we're done
            T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp;
            ci = pi;
        }
    }

    public T Dequeue()
    {
        // assumes pq is not empty; up to calling code
        int li = data.Count - 1; // last index (before removal)
        T frontItem = data[0];   // fetch the front
        data[0] = data[li];
        data.RemoveAt(li);

        --li; // last index (after removal)
        int pi = 0; // parent index. start at front of pq
        while (true)
        {
            int ci = pi * 2 + 1; // left child index of parent
            if (ci > li) break;  // no children so done
            int rc = ci + 1;     // right child
            if (rc <= li && data[rc].CompareTo(data[ci]) < 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
                ci = rc;
            if (data[pi].CompareTo(data[ci]) <= 0) break; // parent is smaller than (or equal to) smallest child so done
            T tmp = data[pi]; data[pi] = data[ci]; data[ci] = tmp; // swap parent and child
            pi = ci;
        }
        return frontItem;
    }

    public T Peek()
    {
        T frontItem = data[0];
        return frontItem;
    }

    public int Count()
    {
        return data.Count;
    }

    public override string ToString()
    {
        string s = "";
        for (int i = 0; i < data.Count; ++i)
            s += data[i].ToString() + " ";
        s += "count = " + data.Count;
        return s;
    }
}
public class Node<T>
{
    private T data;
    private NodeList<T> neighbours = null;
    public Node()
    {
    }
    public Node(T data)
        : this(data, null) { }

    public Node(T data, NodeList<T> neighbours)
    {
        this.data = data;
        this.neighbours = neighbours;
    }

    public T Value
    {
        get
        {
            return this.data;
        }
        set
        {
            this.data = value;
        }
    }

    protected NodeList<T> NeighBours
    {
        get
        {
            return this.neighbours;
        }
        set
        {
            this.neighbours = value;
        }
    }
}
public class NodeList<T> : Collection<Node<T>>
{
    public NodeList() : base() { }
    public NodeList(int initalSize)
    {
        for (int i = 0; i < initalSize; i++)
        {
            base.Items.Add(default(Node<T>));
        }
    }
}
public class GraphNode<T> : Node<T>, IComparable<GraphNode<T>>
    {
        private List<int> costs;
        public int Priority;
        public GraphNode() : base() { }
        public GraphNode(T value) : base(value) { }
        public GraphNode(T value, NodeList<T> neighbours) : base(value, neighbours) { }
        new public NodeList<T> NeighBours
        {
            get
            {
                if (base.NeighBours == null)
                    base.NeighBours = new NodeList<T>();
                return base.NeighBours;
            }
        }
        public List<int> Costs
        {
            get
            {
                if (costs == null)
                    costs = new List<int>();
                return costs;
            }
        }
        public int CompareTo(GraphNode<T> other)
        {
            if (this.Priority > other.Priority)
                return 1;
            return 0;
        }
    }
public class Graph<T>
    {
        private NodeList<T> nodeSet;
        public Graph() : this(null) { }
        public Graph(NodeList<T> NodeSet)
        {
            if (NodeSet == null)
                this.nodeSet = new NodeList<T>();
            else
                this.nodeSet = NodeSet;
        }
        public void AddNode(GraphNode<T> node)
        {
            nodeSet.Add(node);
        }
        public void AddDirectedEdge(GraphNode<T> from, GraphNode<T> to, int weight)
        {
            from.NeighBours.Add(to);
            from.Costs.Add(weight);
        }
        public void AddUnDirectedEdge(GraphNode<T> from, GraphNode<T> to, int weight)
        {
            from.NeighBours.Add(to);
            from.Costs.Add(weight);
            to.NeighBours.Add(from);
            to.Costs.Add(weight);
        }
        public void RemoveUnDirectedEdge(GraphNode<T> from, GraphNode<T> to)
        {
            from.NeighBours.Remove(to);
            to.NeighBours.Remove(from);
        }
        public NodeList<T> Nodes
        {
            get
            {
                return this.nodeSet;
            }
        }
    }

All the test cases had passed with the solution. Please let me know if you have more optimized solution.

Movie Review : Special Chabbis , movie you must watch

Special Chabbis is one of the finest movie you are going to watch ever. Specially when movie is based on some real incident , making it into the movie is not that much easy.

Superb Acting : All the characters of the movie , from small star to big star all have done performance of the lifetime. Manoj Bajpayee is superb out of all them but It does not mean that anybody else is below. Akshay Kumar has finally changed his super action hero image and had done some serious acting. Even though Jimmy Shergill has very few line to deliver but he had done a marvelous acting. I am not going to tell any thing about Anupam Kher because I do not need to write ( You must be knowing why !). I would go for 5 out of 5 for acting

Songs : Average and I think movie does not required any support. So overall 3 out of 5

Background Music : I want to mention the background music is much above the par of indian movies standard. You are going to enjoy , even my feet’s started moving. 5 out of 5.

Direction / Story : I would go for 5.1 out of 5 . Superb , mind blowing …… After the movie The Wednesday , Neeraj Pandey had proved that he knows his business better than anybody else in bollywood.

Overall I will go for 4 out of 5 and You must go and watch the movie as early as possible.

TECHGIG : IPL Team rankings Solution

Hello Friends , one more blog is rolling to solve easy level of Techgig problem. This problem is easy but will apply the basic fundamental logic which is used in commercial databases.

Problem : read here , http://www.techgig.com/codecontest/problem/IPL-Team-rankings-26

Solution : As problem has certain rules, we will analyze them first.
FIRST Rule : We have to find the occurrence of capital letter in the name. The position of occurrence is important because if the capital letter in 1st team name is at 2nd position and 3rd in 2nd team name then 1st team rank should appear first. Once we have tie for the position of capital letter we have to go for natural sort order of the alphabets.
SECOND Rule : In case we do not have any capital letter we have to sort based on the normal sorting of names.

The point here is to consider that we need to have weight for each rule. So what we can do is, as we know the ASCII value of CAPITAL letter is between 65 and 90. So we will try to assign some value to all the team such that we can sort in the last very easily. So we will multiply the position index of capital letter with 100.
You may be thinking why I have chosen 100 , I will explain,let us assume we have one team name with First Letter itself capital but the letter is Z , ASCII value of Z is 90 and I have second team name with position of capital letter is at 2nd and letter is A . With no multiplication factor 2nd Team position may appear first. Now with 100 multiplication factor the 1st team will get the value 100 * 0 + 90 = 90 (Max) and 2nd team will be 100 * 1 + 65 = 165 . So we have assign the values in such a manner that in case be easily sorted in the last.
In case we do not find any capital letter we need to push them in last but maintaining the order , I have chosen to give them very large value and just adding the ASCII value of the first character of word to have natural ordering.

What I believe when we have primary index and secondary Index in the database. They also maintain some gap of big number so that in no case secondary index value can pass over the primary index. Example SQL Query with ORDER BY on two columns. Enough of theory, time for code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class UserMainCodeOld
{
    //Assume following return types while writing the code for this question. 
    public static string[] output1;
    public static void GetTeamOrder(int input1, string[] input2)
    {
        List<string> teamNames = new List<string>(input1);
        output1 = new string[input1];
        Dictionary<int, string> rankingCollection = new Dictionary<int, string>();
        const int BIGNUMBER = (Int32.MaxValue - 123);
        for (int i = 0; i < input1; i++)
        {
            var team = input2[i];
            int charLength = team.Length;
            bool foundRank = false;
            for (int j = 0; j < charLength; j++)
            {
                if ((int)team[j] <= 90)
                {
                    int num = (j * 100) + (int)team[j];
                    rankingCollection.Add(num, team);
                    foundRank = true;
                    break;
                }
            }
            if (!foundRank) // When no capital letter in the name
            {
                int num = BIGNUMBER + (int)team[0];
                rankingCollection.Add(num, team);
            }
        }
        output1 = rankingCollection.OrderBy(x => x.Key).Select(x => x.Value).ToArray(); // Sort the result to output
    }
}

Code had passed on all the test cases with 99.99 points around. Please let me know if you have more optimized solution.