# All posts by Sunil Singhal

A human being whose dreams are tied to a Horse that will never tire

# Infix to Prefix Conversion

### 3. Convert Infix Expression to Prefix Expression

Problem:

Given an infix expression, output the expression in Prefix (Polish Notation) form.

For e.g.

Solution:

This implementation is done using C#.NET.

ALGORITHM:

This algorithm maintains two stacks. 1st stack for all operators and 2nd stack to store the operands.

1)  Validate the Infix Expression for correctness

a) ‘(‘ and ‘)’ are in pairs

b) Operator is in between 2 operands (Binary operators are considered only)

2)  If Infix Expression is Valid then

a)  Push ‘(‘ to Operator Stack and Append ‘)’ to Infix Expression

b)  Scan each character in the Infix expression

i)  If scanned character is ‘(‘

Then

Push it to Operator Stack

ii)  Else If scanned character is ‘)’

Then

(a)  Repeat the below steps until ‘(‘ is popped out from Operator Stack

(b)  Pop from Operator Stack into OPERATOR

(c)  If OPERATOR  != ‘(‘

(i)  Pop twice from Operand Stack into OPERAND2 and OPERAND1

(ii)  Push “OPERATOR OPERAND1 OPERAND2” in Operand Stack

iii)  Else If scanned character is an Operator

Then

(a) Repeat the below steps until Operator having low precedence than  Scanned character is popped out from Operator Stack

(b) Pop from Operator Stack into OPERATOR

(c)  If OPERATOR  has Higher or Equal Precedence than scanned character

(i)  Pop twice from Operand Stack into OPERAND2 and OPERAND1

(ii)  Push “OPERATOR OPERAND1 OPERAND2” in Operand Stack

(d) Otherwise,

(i) Push the last Popped operator back in Operator Stack

(ii) Push the scanned character in Operator Stack

iv) Otherwise, Scanned character is an operand. Thus, Push it in Operand Stack

c) Pop from Operand Stack which is the final expression and return;

```public void ConvertInfixToPrefix(string infixExpression)
{
try
{
ValidateInfixExpression(ref infixExpression);
}
catch (Exception ex)
{
Console.WriteLine(“Invalid infix expression. Error Details:{0}”, ex.Message);
return null;
}

Stack operatorStack = new Stack();
Stack operandStack = new Stack();

operatorStack.Push(‘(‘);
infixExpression += ‘)’;

foreach (char ch in infixExpression)
{
if (ch == ‘(‘)
{
operatorStack.Push(ch);
}
else if (ch == ‘)’)
{
// Pop from operator Stack until ‘(‘ is encountered
char poppedOperator = operatorStack.Pop();
while (poppedOperator != ‘(‘)
{
operandStack.Push(PrefixExpressionBuilder(operandStack, poppedOperator));
poppedOperator = operatorStack.Pop();
}
}
else if (IsOperator(ch))
{
// Pop all operators from Operator Stack which have same or higher precedence
char poppedOperator = operatorStack.Pop();
bool sameOrHighPrecedence = CheckSameOrHighPrecedence(poppedOperator, ch);
while (sameOrHighPrecedence)
{
operandStack.Push(PrefixExpressionBuilder(operandStack, poppedOperator));
poppedOperator = operatorStack.Pop();
sameOrHighPrecedence = CheckSameOrHighPrecedence(poppedOperator, ch);
}

operatorStack.Push(poppedOperator);
operatorStack.Push(ch);

}
else
{
operandStack.Push(ch.ToString());
}
}
return operandStack.Pop();
}

/// Validates the infix expression for correctness
///
/// Infix expression to be validated
/// True if expression is valid
private static void ValidateInfixExpression(ref string expression)
{
expression = expression.Replace(” “, string.Empty);
// Rule 1: ‘(‘ and ‘)’ pair
// Rule 2: Every two operands must have one operator in between
}

/// Checks if character is a listed operator or not
///
/// Charaxter to be tested
/// False if not otherwise True
private static bool IsOperator(char character)
{
if ((character == ‘+’) || (character == ‘-‘) || (character == ‘*’) || (character == ‘/’))
{
return true;
}
return false;
}

/// Checks if popped operator has same or higher precedence than Current operator
///
/// Popped operator
/// Current operator in the expression
/// True if equal or higher precedence
private static bool CheckSameOrHighPrecedence(char elementToTest, char checkAgainst)
{
bool flag = false;
switch (elementToTest)
{
case ‘/’:
case  ‘*’:
flag = true;
break;
case ‘+’:
case ‘-‘:
if ((checkAgainst == ‘+’) || (checkAgainst == ‘-‘))
{
flag = true;
}
break;
default: // for any other popped element
flag = false;
break;
}
return flag;
}

private static string PrefixExpressionBuilder(Stack operandStack, char operatorChar)
{
string operand2 = operandStack.Pop();
string operand1 = operandStack.Pop();
string infixExpression = string.Format(“{0}{1}{2}”, operatorChar, operand1, operand2);

return infixExpression;
}
```

# Is Binary Tree a Binary Search Tree?

### 2. Is tree BinarySearchTree?

Problem:

Given a binary tree, determine if it is a Binary Search Tree (BST) or not?

Definition:

What is BST?

BST is a binary tree in which value of root is always greater than the value of every node on it’s left and is less than or equal to the value of every node on it’s right.

Solution:

This implementation is done using C#.NET.
``` class BinaryTree { public BinaryTreeNode Root { get; set; }```

``` public bool IsBinarySearchTree() { Console.WriteLine("Checking if Tree is BST or not:"); if (this.Root != null) { int value = 0; return this.Check(this.Root, ref value); } return true; } private bool Check(BinaryTreeNode currentNode, ref int lastNodeValue) { bool isTreeBST = false, leftTreePresent, rightTreePrsent ; leftTreePresent = currentNode.LeftTree == null ? false : true; rightTreePrsent = currentNode.RightTree == null ? false : true; if (leftTreePresent) { isTreeBST = this.Check(currentNode.LeftTree, ref lastNodeValue); } else { isTreeBST = true; } if (isTreeBST && currentNode.Info > lastNodeValue) { Console.WriteLine("Processing Node With Value:{0}", currentNode.Info); lastNodeValue = currentNode.Info; isTreeBST = true; } else { isTreeBST = false; } if (isTreeBST && rightTreePrsent) { isTreeBST = this.Check(currentNode.RightTree, ref lastNodeValue); } return isTreeBST; } } ```

```class BinaryTreeNode { public BinaryTreeNode LeftTree { get; set; } public BinaryTreeNode RightTree { get; set; } public int Info { get; set; } } ```

Problem with the above code is that if a tree has Duplicate Values, it will fail.

The approach could be then to pass the Range in terms of Minimum and the Maximum Value of a particular node. Since we are traversing down from Root and knowing the min and max value of a root, we can appropriately limit the range and pass on to Left and Right Trees.

``` private bool Check(BinaryTreeNode node, int min, int max) { if (node == null) return true;```

``` ```

```if (node.Info max) return false; else { return this.Check(node.LeftTree, min, node.Info) && this.Check(node.RightTree, node.Info + 1, max); } } ```

# SpiralTraversalOfMatrix

### 1. Spiral Traversal of a 2D matrix

Problem:

Given a 2D matrix, traverse all it’s elements in a spiral form.
Referring the below matrix as an input (Red line shows a spiral traversal),

output should be: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Solution:

This implementation is done using C#.NET. Rectangular Matrix is declared using int[,] syntax.

```public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList();

int rowStart = 0, rowEnd = matrix.length - 1, colStart = 0, colEnd = matrix[0].length - 1;

while (rowStart <= rowEnd && colStart <= colEnd) {
for(int i = colStart; i <= colEnd; i++) {
}
rowStart++;

if (rowStart > rowEnd) {
break;
}
for (int i = rowStart; i <= rowEnd; i++) {
}
colEnd--;

if (colStart > colEnd) {
break;
}
for (int i = colEnd; i >= colStart; i--) {
}
rowEnd--;

for (int i = rowEnd; i >= rowStart; i-- ) {
}
colStart++;
}
return res;
}
```

This article describes a way to create the Scheduled tasks in a system pro-grammatically for Windows Vista, Windows 7 etc Operating Systems using C#.NET language. Windows operating systems, though, already provide a User Interface to see a complete list, to add, to update or to delete a Scheduled Task under it. This UI can be seen by launching a Computer Management by issuing a command compmgmt.msc on a command prompt.

System Requirements
Windows Vista or Windows 7 or higher versions Operating systems

Development Environment

• Development IDE – Visual Studio [or simple Notepad]

How to Implement?
To begin with, we need an underlying library, can be COM library or unmanaged C(++) library or managed wrapper which talks to the system to get things done.
Aaannnnnnnn.
Don’t worry.
Here is the trick.
If you dare to 🙂 browse to C:\Windows\syswow64, you will notice the presence of Taskschd.dll assembly. This is what we need to proceed with.

Steps:

1. Create a new Project using Visual Studio

The last step resulted in an Interop assembly generation and referenced in the project. You can check this by selecting a referenced assembly and viewing it’s properties.

Now, we’ll make use of Types defined/exported in the interop assembly to achieve:
– View the list of all Scheduled Tasks

Be it any CRUD operation, we’ll make use of ITaskService type which connects to an actual store and exposes the operations. We’ll instantiate the TaskService and call the Connect method before any valid operation.

Before detailing out the steps, another important aspect is to understand the layout or a structure, the tasks are organized.

Scheduled Tasks are organized in a hierarchical fashion. They are always stored in a folder. The very first folder is termed Root Folder with a path @”\” or “\\”. Each folder can have sub folders under it. View the above picture to understand or open “Scheduled Tasks” on your system.

The following sections detail out “How to ?” part for each operation.

How to retrieve the list of all Scheduled Tasks?

`ITaskService taskService = new TaskScheduler();`
2. Call Connect() on previously created taskService object.
`taskService.Connect();`
3. Get a reference to Root Folder.
`ITaskFolder rootFolder = taskService.GetFolder(@"\");`
Remember, path to Root Folder is “\”.
4. Make a call to GetTasks() on a folder.
`IRegisteredTaskCollection tasks = rootFolder.GetTasks(0); // 0 or 1: 1 will include all hidden tasks as well`
Note: Here, you will get those tasks only which are created in root folder. Since this root folder can have sub folders under it, you have to recursively call GetTasks() for each sub-folder.

```private void Load()
{
}

{
{

{
}
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
}
```

How to delete a Scheduled Task?
By default, each task’s Location property contains the Name of that particular task as well as it’s containing folder. So if we have an access to Task Location only, we can find out it’s name and it’s containing folder through some string manipulation.
Steps to delete a task when it’s full location is provided as input:

• Find out the name of Task and it’s containing folder through string manipulation. [You may want to Validate the input:task Location]
• Instantiate a task service and connect
• Get the containing folder reference through below code:
`ITaskFolder containingFolder = taskService.GetFolder(folderPath);`
`containingFolder.DeleteTask(taskName, 0);`

This is how a complete function may Look like:

```public bool DeleteTask(string taskPath)
{

if (string.IsNullOrWhiteSpace(folderPath))
{
folderPath = “\\”;
}

try
{

}
catch(FileNotFoundException exception)
{
}

return true;
}
```

How to create\update a Scheduled task?
Creating a Scheduled task is not as easy as other operations. Before i detail out the steps here, i am pinpointing few things which are expected by COM and it’s behavior, to get our new task registered successfully in the system.

• Name of a new Task to be created can be empty while doing registration. If this is the case, system will generate a GUID and assign this as a name of a task
• The ExecutionTimeLimit, IdleDuration parameters under ITaskDefinition [see “Possible error and exceptions” section below] should be in a particular format. If this is not the case, new task won’t be registered
• Atleast one action should be specified when registering a new task
• If a task with the same name under the same folder exists, it will be updated if you register a task with a flag: “CreateOrUpdate” has a value of ‘6’. It is the 3rd argument passed in a call to RegisterTaskDefinition()

Now, let’s see how can we achieve this programmatically using C#.NET.
The below code will create\update a task under a Root Folder “\”. You may choose to create under a sub-folder.

Steps to create a task under Root Folder:

1. Instantiate a task service and connect
`ITaskService taskService = new TaskScheduler();`
``` ITaskDefinition taskDefinition = taskService.NewTask(0); ```
3. Configure a new Task – all desirable properties like – Name, Description, Triggers, Actions, Author etc.
``` taskDefinition.RegistrationInfo.Description = "task Description Goes Here"; taskDefinition.RegistrationInfo.Author = "task Author domainName\userName goes here";```taskDefinition.Settings.Enabled = “true or false”;
{
TimeSpan timespan = TimeSpan.FromMinutes(“No of minutes goes here”);// this is the format needed by COM
}

if (“You want to allow the task to execute only when system is idle for so many minutes”)
{

TimeSpan timespan = TimeSpan.FromMinutes(“Number of Minutes Goes Here”);

// this is the format needed by COM
}

4. Configure triggers, if any
``` ITriggerCollection triggers = taskDefinition.Triggers; ITrigger trigger = triggers.Create("type of Trigger goes here"); // _TASK_TRIGGER_TYPE2 enumeration trigger.Enabled = "true or false"; trigger.StartBoundary = DateTime.Now.ToString(Constants.DateTimeFormatExpectedByCOM);```if (“You want this trigger to expire after sometime”)
{
trigger.EndBoundary = DateTime.Now.EndTime.ToString(Constants.DateTimeFormatExpectedByCOM);
}
5. Configure Actions [atleast one]
``` IActionCollection actions = taskDefinition.Actions; _TASK_ACTION_TYPE actionType = "type of action you want goes here"; IAction action = actions.Create(actionType);```switch (actionType)
{
IExecAction execAction = action as IExecAction;execAction.Path = “Path to Program To Run goes here”;
execAction.Arguments = “Optional Arguments goes here when starting the above executable”;
IEmailAction mailAction = action as IEmailAction;

mailAction.From = “Sender email address goes here”;
mailAction.Server = “SMTPServer address goes here”;
mailAction.Subject = “email Subject goes here” ;
mailAction.Body = “email MessageBody goes here”;

break;

IShowMessageAction showAction = action as IShowMessageAction;

showAction.Title = “Display Title goes here”;
showAction.MessageBody = “Display Message goes here”;
break;
}

6. Till this point, we have configured task settings, triggers, actions, conditions. Now we need to register this task definition under some folder, RootFolder – “\”, here
``` // creating this task in the root Folder // Create SubFolder under RootFolder, if you require ITaskFolder rootFolder = taskService.GetFolder(@"\");```// ‘6’ as argument means this task can be created or updated [“CreateOrUpdate” flag]
// if Name id empty or null, System will create a task with name as GUID

That’s all we need to do. If luck goes with you:), you won’t get errors [not like me]. Just kidding.
If you get a new error, contact me. I’ll try to find a cause and suggest you a resolution.

Possible errors and exceptions

• Error Code :-2147216616,
System.Runtime.InteropServices.COMException (0x80041318): (8,44):StartBoundary:26-01-2012 08:28:31

Cause: “ExecutionTimeLimit”/ “IdleDuration” are expected in some format by COM and not just simple ToString() conversion
Resolution: Use System.Xml.XmlConvert.ToString(). [Spent lot of time to get to this]

• System.Runtime.InteropServices.COMException (0x80041319): (38,4):Actions:

Cause: This means tat atleast one action should be specified when registering a task definition for a new task.
Simply put, a task should define atleast one action
Resolution: Specify atleast one action – be it : To send an email or To execute a task or To display a message

• System.Runtime.InteropServices.InvalidComObjectException was caught
Message=COM object that has been separated from its underlying RCW cannot be used.
Source=mscorlib
StackTrace:

Cause:
You are trying to work on the Released TaskScheduler COM object
Resolution:

• Error Code: -2147221163. Interface not registered while creating a task.

Yet to identify the real cause and resolution. [Noticed this when i share the same TaskScheduler instance and use it from diferent win forms]

References

# Playaround with an address of object reference variable

Well, rarely you will have to find an address of a variable in C#.NET. Though C#.NET allows use of pointers but anyone hardly use them. .NET base library and Compiler have done a beautiful job, abstracting the complex use of pointers, exposing ref, out keywords.

But what if you still want to playaround?
[I must warn you about this. Don’t dare to play with Pointers 🙂 Improper handling of pointers can even bring your application down]

Thankfully, there are constructs which do help in achieving what we want.

The above link is just to get a concept of Stack. What a stack is. It has nothing to do with Stack class provided in C#.NET.
``` static void GetAddress() { unsafe { int i = 5; object refer = new object(); // &i gets an address of variable 'i' and * operator gets the value Console.WriteLine("Address of i:{0},{1}" , (uint)&i, *(&i)); Console.WriteLine("Address of refer:{0},{1}", (uint)(&i - 1), *(&i - 1)); } } ```
Explanation
Here, i have defined two variables, named – i and refer . Both these variables sit on STACK, however the values stored by them are treated differently.
i stores the value directly [5 in our case as per statement], and
refer stores the address of an actual object allocated on a manged heap.
This is how Stack and Heap state would be after two initalizing statements.

So, if i have an access to an address of i and knowing that refer is on Stack just after i, decrementing 1 from i address [Pointer arithmetic], i’m now pointing to the refer which is the reference to the actual object (object()) sitting on heap.

You have a stack address and thus the value stored at that location. Using Pointer Arithmatic, do what you want WITH CARE.
MS should tag POINTERS with “HANDLE WITH UTMOST CARE” 🙂

# How to Reference or use same fully qualified class name from different assemblies

Two or more different assemblies can contain a type with a same name and same namespace.
What will happen if you reference those assemblies in your project?
Well, referencing won’t result into any error. 🙂
But.
How about making an object of that class?
This will fail. Compilation error will be generated because of ambiguity. Which type from which assembly should be used?
Compiler can’t make this decision on it’s own and rather i would say, it should not.
This should be done by a programmer/coder to clear his intentions to the compiler.
But How?

Solution

Let’s say, we have two assemblies:

• Assembly1
• Assembly2

Both assemblies define a type, say class having fully qualified name as SomeNameSpace.SomeClassName

We have a project where we refer the above two assemblies.
In order to instantiate an object of ProjectLibrary.Class defined in Assembly1, do:

1. Change the Aliases property of one of the references
2. Whenever any reference is added, Aliases is set to global. Change this to your desired name, say Assembly1
Though this can be done for both but doing it for one will automatically open doors for another assembly.

3. Write a code statement on the top of your file: extern alias Assembly1;
4. Lastly, change the object instantiation statement to
Assembly1::ProjectLibrary.Class obj = new Assembly1::ProjectLibrary.Class();
5. “::” is a Namespace Alias Qualifier in .Net.

That’s it.

# Customize or Override core.js file functions in Sharepoint

Core.js JScript file located @ 12 or 14 hive , depending upon the SharePoint version installed on a system, provides several in-built javascript functions. This is an out-of-box aka OOB sharepoint file.
[12/14 hive is @ %PROGRAMFILES%\Common Files\Microsoft Shared\Web Server Extensions\]

These functions are invoked internally by OOB visual webparts in sharepoint.

For e.g.,
Any Document library View page listing all items, hosted in a sharepoint site, references core.js file. Functions may get invoked when a user hovers any item name column or when an Add New Item link is clicked.

You may be thinking about the scenarios where you may need to customize a function defined in core.js file.

Where\Why?
There can be many. Yes. One of them which i faced is related to Browser compatibility.

• Add modal pop up opening as a full page
• On XP SP3 build’ IE7, a javascript error was thrown on clicking “Add New Item”. Due to this, an AddItem page was opening as a full page rather than a modal pop-up. This was not even reproducible on IE9 running into IE7 compatibilty and document mode.
The faulty function was: function UseDialogsForFormsPages(c){…}

You may face other problems but cause could be the same.

Note: However, my recommendation is NOT to OVERWRITE the core.js.

You may now be confused. Many questions may be coming into your mind – What is the purpose of this blog then?, How should i achieve if i ever need to?

Well, i recommended not to overwrite core.js. The reason being that this is OOB file and may get modified in the next version of sharepoint.
What you should do is provide a method override. Another javascript function which has a same prototype but a body definition as per your requirements.
Continue reading Customize or Override core.js file functions in Sharepoint

# Setting Custom Permission Levels in Sharepoint Programmatically

Before going into How part, lets first understand What is a Permission Level (known as Site Groups prior to WSS 3.0) in Sharepoint? Why do we need it?

What is a Permission Level?
It is a group or set of permissions\actions. By action, i mean that what a particular user is allowed to do in an application.
These permissions can then be assigned to a user or a group of users to allow\restrict certain actions based upon his role in the application.

Why?
Security. Making application secure, defining roles and responsibilities of it’s users.
Obviously, every application has users [otherwise why would it exist?]. Each user has it’s own set of roles and responsibilities. As per those responsibilities, he can perform tasks or take actions which are laid down for him.

Have you ever seen a Software Developer doing a job of CA, Finance Head? Surely, it is not meant for a poor developer.
This is where Permission Levels are needed. These permission levels segregate permissions, clearly demarcating or creating a boundary for users what they are supposed to do and what they are not.
Continue reading Setting Custom Permission Levels in Sharepoint Programmatically

# XSLTListViewWebpart in Sharepoint 2010 Uncovered

Successor and much more powerful webpart than Dataform or ListViewWebpart provided in Sharepoint 2010, yes, that’s true.

As mentioned in msdn, it handles view rendering for lists which can be document libraries as well as announcements. As the name suggests, it uses a XSLT i.e transforms for Html rendering. Xml data obtained as per Query and XmlDefinition, explained later, is converted into html using Xslt. It, by default, applies styles [ViewStyles] as provided by Sharepoint.

It provides an option to enable column filtering, sorting, Paging and AJAX as well. Yes, filtering, sorting, Paging can be done async, without whole page refresh using AJAX option.

What’s more? You can even define your own custom xsl defining styles, rendering and you have a data rendered the way you want. Custom xslt can override default templates and thus has a power to completely replace default XSLTs which is rarely needed.

For e.g. Dates to be shown in a particular format or you want to specify custom header names rather than display names defined in a list definition or a view.

Isn’t it powerful from what we had earlier?

Why am i writing this?

In my project, i had a requirement to show latest 5 documents with a More… button at the bottom in a page which had other data as well. It should support sorting, filtering but without paging. And most importantly, to show list data which exists in a different site collection.

Surely this is achievable by writing a custom visual web part and a backend code but how much time does this require? If you are following a layered approach and are following a well-defined architecture :), which you will be as a good coder, it can take a lot of time with a filtering, sorting support. And what if Client demands for Paging later. This usually happens in Agile methodology. Plus why to forget a testing?

This is where XsltListView webpart can be handy, inbuilt webpart, already test proven, just set few properties as per your requirements and you are good to go.

But…

What to set, when, why? If you want to use this webpart and you don’t have knowledge how to use it, I pray to God.

You have now 2 options:

• Either spend a lot of time yourself, exploring this XsltListViewWebpart, or
• Refer to this blog :). If not 100% , it will definitely save more than 75% of your efforts in fiddling around

How to use?

Following are the few properties which must be considered when using this webpart:

You can either make use of SharepoingDesigner (SPD) or your skill 🙂 to define XsltListViewWebPart definition declaratively.

# How to read or write excel file using ACE OLEDB data provider?

This article describes the way to read or write into the excel workbook(or a file, used interchangeably) pro-grammatically using C#.NET language and ACE Oledb data providers by Microsoft.
This covers the following topics:

• System Requirements
• Development Environment
• Versions of Excel files which can be read or written
• How to build a connection string?
• How to build a command string?
• Possible errors and exceptions

System Requirements
To read/write the excel worksheet using ACE oledb providers, MS office need not to be installed on a machine. An installable package containing ACE oledb providers can be installed from ACE OLEDB Installer Location
Go to this link to install the required version and also check the system requirements.
Note: You can install either 32 bits version or 64 bits version but not both. Also, if you have 64 bits office installed then you can’t install 32 bits ACE oledb and vice versa.
Check the requirements carefully on the page.