Activation error occured while trying to get instance of type Database, key “” | EntLib


The title of this post may sound a bit strange for those who have not faced this problem but it may sound a Sweet Tune Music :) to those who want to resolve this nasty error in their application.

If you fall into the latter category, you can directly jump to the Solution section though everybody is definitely welcomed to read the entire post.

What is this about?
An error which occurs when using Enterprise Library Data Access Block in instantiating a Database using factory approach.
You may have followed the msdn article to setup DataAccessBlock with the correct code and the configuration in your application but always resulting into the error when you try to instantiate a database object.

Context
Typically, software solutions are multi-layered. One of them being a Data Access Layer, aka DAL, which interacts with the Data Store(s) and performs the CRUD operations on the data in the data store. In this layer, you can either opt for ADO.Net or Enterprise Library Data Access Block to connect to Data Store (database) besides other options.

Since, the post is talking about a specific error resulted in the EntLib, lets assume that we preferred to implement DAL using EntLib Data Access Block.

Problem / Error
Activation error occured while trying to get instance of type Database, key “”
This error occurs on the below code statement, the very first statement to perform the CRUD operation into the DataStore.

Database dataStore = DatabaseFactory.CreateDatabase();

or,

Database dataStore = DatabaseFactory.CreateDatabase("someKey");

Cause
Enterprise library consists of number of classes in different namespaces and assemblies.
Two of them are:

  1. Microsoft.Practices.EnterpriseLibrary.Data
  2. Microsoft.Practices.EnterpriseLibrary.Common

The above code statement is present in the former assembly. After a series of function calls in the same assembly and the latter assembly, a function in the latter assembly tries to load the former assembly using the partial name.

Note: Loading of an assembly using Partial name
This is what leads to the error if the Enterprise libraries assemblies are GACed and not copied locally into the application directory.
Assembly with a partial name won’t be found in the GAC and then the search/probing of an assembly will continue to Local Application Directory or sub-directories with the same name or as per configuration.
Since assembly is not present anywhere else except GAC, assembly loading will fail and leading to this error.

You can see this in action by launching Fusion Log Viewer utility, which comes by default. Command is : “fuslogvw” in case yof could not locate the utility. Type the command in the Visual Studio Command Prompt.
You may need to customize the Log Viewer to log all binding to disks to view every log.

[You can opt to open this assembly into a Reflector or ILSpy and go through each code statement and function call post the above code statement to understand more.]

So, is there a solution or a workaround for the above problem?

Resolution
This problem is solvable. :)
Problem can be solved in many ways, you choose what suits you the best.

  1. You can deploy the enterprise library, “Microsoft.Practices.EnterpriseLibrary.Data” locally to the applcation bin directory. [This may lead to maintaining multiple copies of the same assembly]
  2. Another option is to have the below configuration in the application configuration file. This appears a bit clean approach but again the same configuration change has to be done at multiple places if they are using this library

    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <qualifyAssembly partialName="Microsoft.Practices.EnterpriseLibrary.Data" fullName="Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </assemblyBinding>
    </runtime>

    Thanks to Mr. Philippe for this 2nd solution posted @ CodePlex.
Posted in .NET | Tagged , , , , , | 4 Comments

DeterminantOfMatrix


4. Determinant of a 2D matrix

Problem:

Given a 2D matrix, Determine it’s Determinant.

Solution:

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

public static long EvaluateDeterminant(int[,] matrix)
{
long determinant = 0;

if (matrix == null || matrix.GetUpperBound(0) != matrix.GetUpperBound(1))
{
Console.WriteLine("Non-square matrix can't have a determinant");

return determinant;
}

int row_UB = matrix.GetUpperBound(0);

determinant = Determinant(matrix, row_UB + 1);

return determinant;
}

private static long Determinant(int[,] matrix, int size)
{
long determinant = 0;

if (size == 1) // 1x1 MAtrix
{
determinant = matrix[0, 0];
}
else if (size == 2) // 2x2 MAtrix
{
determinant = matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]; // can hash this multiplication
}
else
{
int multiplier = 1;

for (int i = 0; i < size; i++)
{
multiplier = (i % 2 == 0) ? 1 : -1;

determinant += multiplier * matrix[0, i] * Determinant(GetMinor(matrix, size, 0, i), size - 1);
}
}

return determinant;
}

/// <summary>
/// Gets the Minor of a Square Matrix
/// </summary>
/// <param name="matrix"></param>
/// <param name="size"></param>
/// <param name="rowIndex"></param>
/// <param name="colIndex"></param>
/// <returns></returns>
/// <remarks>
/// If function has to be Public, Certain checks on rowIndex, ColIndex should be made and size need not to be passed
/// </remarks>

private static int[,] GetMinor(int[,] matrix, int size, int rowIndex, int colIndex)
{
int minorSize = size - 1;
int[,] minor = new int[minorSize, minorSize];

for (int i = 0; i < rowIndex; i++)
{
for (int j = 0; j < colIndex; j++)
{
minor[i, j] = matrix[i, j];
}
}

for (int i = rowIndex + 1; i < size; i++)
{
for (int j = 0; j < colIndex; j++)
{
minor[i - 1, j] = matrix[i, j];
}
}

for (int i = 0; i < rowIndex; i++)
{
for (int j = colIndex + 1; j < size; j++)
{
minor[i, j - 1] = matrix[i, j];
}
}

for (int i = rowIndex + 1; i < size; i++)
{
for (int j = colIndex + 1; j < size; j++)
{
minor[i - 1, j - 1] = matrix[i, j];
}
}

return minor;
}

Posted in Algorithms | Tagged , , , , | Leave a comment

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<char> operatorStack = new Stack<char>();
Stack<string> operandStack = new Stack<string>();

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();

}

/// <summary>
/// Validates the infix expression for correctness
/// </summary>
/// <param name="expression">Infix expression to be validated</param>
/// <returns>True if expression is valid</returns>
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

}

/// <summary>
/// Checks if character is a listed operator or not
/// </summary>
/// <param name="character">Charaxter to be tested</param>
/// <returns>False if not otherwise True</returns>
private static bool IsOperator(char character)
{

if ((character == '+') || (character == '-') || (character == '*') || (character == '/'))
{
  return true;
}

return false;

}

/// <summary>
/// Checks if popped operator has same or higher precedence than Current operator
/// </summary>
/// <param name="elementToTest">Popped operator</param>
/// <param name="checkAgainst">Current operator in the expression</param>
/// <returns>True if equal or higher precedence</returns>
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<string> operandStack, char operatorChar)
{

string operand2 = operandStack.Pop();
string operand1 = operandStack.Pop();

string infixExpression = string.Format("{0}{1}{2}", operatorChar, operand1, operand2);

return infixExpression;

}

Posted in Algorithms | Tagged , , , , , , , , | 10 Comments

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 < min || node.Info > max)
return false;
else
{
return this.Check(node.LeftTree, min, node.Info) && this.Check(node.RightTree, node.Info + 1, max);
}
}

Posted in Algorithms | Tagged , , , , , , , , , , , , | Leave a comment

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 void DoSpiralTraversal(int[,] rectArray)
{
if(rectArray != null && rectArray.Length > 0)
{
Console.WriteLine("Doing Spiral Traversal on a 2D array:");

int noOfElementsTraversed = 0, row_LB = 0, row_UB = rectArray.GetUpperBound(0), col_LB = 0, col_UB = rectArray.GetUpperBound(1), iter;

while (noOfElementsTraversed < rectArray.Length)
{
// Move downwards
for (iter = row_LB; iter <= row_UB; iter++)
{
Console.Write(rectArray[iter,col_LB] + ” “);

noOfElementsTraversed++;
}

col_LB++;

// Move Left to Right
for (iter = col_LB; iter <= col_UB; iter++)
{
Console.Write(rectArray[row_UB, iter] + ” “);

noOfElementsTraversed++;
}

row_UB–;

// Move upwards
for (iter = row_UB; iter >= row_LB; iter–)
{
Console.Write(rectArray[iter, col_UB] + ” “);

noOfElementsTraversed++;
}

col_UB–;

// Move right to Left
for (iter = col_UB; iter >= col_LB; iter–)
{
Console.Write(rectArray[row_LB, iter] + ” “);

noOfElementsTraversed++;
}

row_LB++;
}
}
}

Posted in Algorithms | Tagged , , , | Leave a comment

Task Scheduler in C#.Net


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]
  • Task Scheduler COM Library

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
  2. Right Click on project and click Add Reference.Select “TaskScheduler TypeLibrary”

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
– To pro-grammatically add a Scheduled Task
– To delete a task

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?

  1. Instantiate TaskService object.
    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()
    {
    ITaskService taskService = new TaskScheduler();
    taskService.Connect();List<IRegisteredTask> tasks = new List<IRegisteredTask>();

    // “\\” or @”\” is the RootFolder
    this.GetData(taskService.GetFolder(@”\”), tasks);

    this.view.ScheduledTasks = tasks;
    }

    private void GetData(ITaskFolder folder, List tasks)
    {
    foreach (IRegisteredTask task in folder.GetTasks(1)) // get all tasks including those which are hidden, otherwise 0
    {
    tasks.Add(task);

    System.Runtime.InteropServices.Marshal.ReleaseComObject(task); // release COM object

    foreach (ITaskFolder subFolder in folder.GetFolders(1))
    {
    this.GetData(subFolder, tasks);
    }
    }
    System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
    }

How to delete a Scheduled Task?
We need some task details like task name, task container i.e. folder in which this task exists in order to delete it.
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.
For e.g., “\\SampleTaskFolder\\SampleTask” means that the task named SampleTask is stored in a folder SampleTaskFolder which is further in RootFolder(“\\”).
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);
  • Call DeleteTask() with a task name
    containingFolder.DeleteTask(taskName, 0);

This is how a complete function may Look like:

public bool DeleteTask(string taskPath)
{
ITaskService taskService = new TaskScheduler();
taskService.Connect();ValidateTaskPath(taskPath);

int lastIndex = taskPath.LastIndexOf(“\\”);

string folderPath = taskPath.Substring(0, lastIndex);

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

string taskName = taskPath.Substring(lastIndex + 1);

try
{
ITaskFolder containingFolder = taskService.GetFolder(folderPath);

containingFolder.DeleteTask(taskName, 0);
}
catch(FileNotFoundException exception)
{
throw new InvalidTaskPath(“Task Path is invalid”, 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();
    2. Create a new task using task Service object. This requires calling “taskService.NewTask(0)”

      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”;
      taskDefinition.Settings.Hidden = “true or false”;
      taskDefinition.Settings.Compatibility = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;if (“You want to set the execution time limit for Task Actions”)
      {
      TimeSpan timespan = TimeSpan.FromMinutes(“No of minutes goes here”);

      // this is the format needed by COM
      taskDefinition.Settings.ExecutionTimeLimit = XmlConvert.ToString(timespan);
      }

      if (“You want to allow the task to execute only when system is idle for so many minutes”)
      {
      taskDefinition.Settings.RunOnlyIfIdle = “true or false”;

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

      // this is the format needed by COM
      taskDefinition.Settings.IdleSettings.IdleDuration = XmlConvert.ToString(timespan);
      }

    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)
      {
      case _TASK_ACTION_TYPE.TASK_ACTION_EXEC:
      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”;
      break;

      case _TASK_ACTION_TYPE.TASK_ACTION_SEND_EMAIL:
      IEmailAction mailAction = action as IEmailAction;

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

      break;

      case _TASK_ACTION_TYPE.TASK_ACTION_SHOW_MESSAGE:
      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
      rootFolder.RegisterTaskDefinition(task.Name, definition, 6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);

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:
    at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis, IntPtr pThread)
    at TaskScheduler.ITaskService.get_Connected()InnerException:

Cause:
You are trying to work on the Released TaskScheduler COM object
Resolution:
Create a new object of TaskScheduler , connect and carry on with your task operation

  • 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


Posted in .NET, Technical | Tagged , , , , , | 18 Comments

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” :)

Posted in .NET, Common Technical Problems, Technical | Tagged , , , , , , , , , | 4 Comments

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.

Posted in Common Technical Problems | Tagged , , , , , , , , , | Leave a comment

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

Posted in Javascript, Sharepoint, Technical | Tagged , , , , , , , , , | Leave a comment

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

Posted in Sharepoint, Technical | Tagged , , , , , , , , , , | Leave a comment