Archive

Archive for the ‘Misc’ Category

Data Tables – Error – Non table node initialization

In one of my Dynamics portal’s requirements, I had to use Data Tables table control to bind the search results.

After referring helper files and configured the ‘Data Tables’ table control in my HTML, I encountered below error during the run:

Data Table - Error

Reason & Fix:

  • ‘Data Table’ table control requires a <table> place holder in the HTML page, which will get rendered with result set (i.e., json collection) in run time.

In your <script>:

var table = $(‘#customGrid‘).DataTable({
data: rows,
destroy: true,
columns: columns});

  • If you refer any control (i.e., Div/Span etc…) other than <table> you will get the error.

In your HTML <body>:

<table id=”customGrid” class=”display”></table>

  • I wrongly used <Div> control in my case and replaced with <Table> to fix the issue.

🙂

Categories: Misc Tags: ,

‘Duplicate record execution’ issue with System.Timer Elapsed event – Windows Service

We have a window service with System.Timer control ‘timerExecuteQuery’, which periodically polls the records from Data Base and process.

this.timerExecuteQuery= new System.Timers.Timer(3) { AutoReset = true };
this.timerExecuteQuery.Start();
this.timerExecuteQuery.Elapsed += this.TimerExecuteQuery_Elapsed;

Everything seems working fine until we noticed few records executing twice causing inconsistency.

The issue was random and unable to reproduce consistently.

Reason:

  • In our scenario, the culprit was System.Timer’s Elapsed event
  • Our timer’s duration is 3 seconds with ‘AutoReset=true’, so, every 3 seconds Elapsed event kick in and executes the logic.
  • In few scenarios, business logic in ‘Timer_Elapsed’ was taking more than 3 seconds causing the trigger of new Elapsed event before completion of old thread. Hence records got executed more than once randomly.

Fix:

  • We declared a global Boolean variable ‘executing’ and handled as below.
    • Set variable ‘executing=true’ before Business logic of ‘Timer_Elapsed’ event and set ‘executing=false’ after execution of Business logic.
    • Check the ‘executing’ variable value before the execution of business logic, if its True, return.

private bool executing = false;

protected void TimerExecuteQuery_Elapsed(object sender, System.Timers.ElapsedEventArgs e){

// ‘executing’ true denotes, previous elapsed event was not over
if (executing){
return;
}

executing = true;

// Business logic
executing = false;
}

🙂

“Bad Data” Error – During Web.Config file Decryption

February 15, 2016 Leave a comment

In one of my web application we are reading credentials from Web.config file’s Connection Strings section.

And we are encrypting the Connection Strings using aspnet_regiis.exe tool during deployments.

Below are the steps to Encrypt/Decryption of Config file using aspnet_regiis.exe tool

Encryption Command

  • Open Visual Studio Command Prompt and run below commands.

   Encrypt Connection Strings  > aspnet_regiis.exe -pef “connectionStrings” “<Path of folder containing web.config file>”

Encrypt App Settings  > aspnet_regiis.exe -pef “appSettings” “<Path of folder containing web.config file>”

  • Ex: If my web.config exists at wwwroot folder, below is the command to encrypt ‘connectionStrings’ section

     aspnet_regiis.exe -pef “connectionStrings” ” C:\inetpub\wwwroot\MyPublishedSite”

WebConfig - Path

WebConfig – Path

Encryption - config file

Encryption – config file

Decryption Command

   Decrypt Connection Strings > aspnet_regiis.exe -pdf “connectionStrings” “<Path of folder containing web.config file>”

Decrypt App Settings > aspnet_regiis.exe -pdf “appSettings” “<Path of folder containing web.config file>”

How to read the encrypted values in your code?

  • No need of any special statements in your code to the read the encrypted values.
  • Your “ConfigurationManager” will take care (i.e., ConfigurationManager.AppSettings[“mypassword”] will return the actual value even if its encrypted)

Key points about Encryption/Decryption

  • Encryption/Decryption is always specific to a machine.
  • So you cannot decrypt a file on Machine 2 which has been encrypted on Machine 1 and ‘aspnet_regiis’ tool throws “Bad Data” error, if you attempt.
Bad Data - Decrypting config file

Bad Data – Decrypting config file

Reason and Fix for the “Bad Data” error:

  • As mentioned earlier, Encryption/Decryption is always specific to a machine.
  • In my case, I tried to Decrypt a file which was encrypted in my Test server, from my Local machine which resulted a “Bad Data” error.
  • To fix the issue, I connected to “Test server” where the config file was originally encrypted, and decryption done successfully.

🙂

Categories: Misc Tags: , , ,

Post XML over HTTP and capture the response – C#

January 7, 2016 1 comment

Recently we got a requirement to post the data from ‘CRM Plug-in’ to an external API and capture response.

External API was built as XML over HTTP (i.e., Its not a SOAP based and no WSDL).

In this approach we post the Request XML to a URL and in return we will get the Response.

Refer below test client with Request and Response XML’s.

Request XML

XML over HTTP - Request XML

XML over HTTP – Request XML

Response XML

XML over HTTP - Response

XML over HTTP – Response

C# Code:

  • In XML over HTTP we will post the Request XML to a URL and get the Response.
  • So the below C# function accepts URL and RequestXML as Parameters and return the Response.

public static XmlDocument SubmitXmlRequest(string apiUrl, string reqXml){
XmlDocument xmlResponse = null;
HttpWebResponse httpWebResponse = null;
Stream requestStream = null;
Stream responseStream = null;

// Create HttpWebRequest for the API URL.
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);

try{
// Set HttpWebRequest properties
var bytes = System.Text.Encoding.ASCII.GetBytes(reqXml);
httpWebRequest.Method = “POST”;
httpWebRequest.ContentLength = bytes.Length;
httpWebRequest.ContentType = “text/xml; encoding=’utf-8′”;

//Get Stream object
requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();

// Post the Request.
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

// If the submission is success, Status Code would be OK
if (httpWebResponse.StatusCode == HttpStatusCode.OK){
// Read response
responseStream = httpWebResponse.GetResponseStream();

if (responseStream != null){
var objXmlReader = new XmlTextReader(responseStream);

// Convert Response stream to XML
var xmldoc = new XmlDocument();
xmldoc.Load(objXmlReader);
xmlResponse = xmldoc;
objXmlReader.Close();
}
}

// Close Response
httpWebResponse.Close();
}
catch (WebException webException)
{
throw new Exception(webException.Message);
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
finally
{
// Release connections
if (requestStream != null){
requestStream.Close();
}

if (responseStream != null){
responseStream.Close();
}

if (httpWebResponse != null){
httpWebResponse.Close();
}
}

// Return API Response
return xmlResponse;
}

Capture and Read the Response

XmlDocument response = SubmitXmlRequest(uri, xmlString);

Console.WriteLine(“Inner Text – ” + response.InnerText);

Console.WriteLine(“Inner XML – ” + response.InnerXml);

🙂

Categories: Misc Tags: ,

Boot failure reboot and select proper boot device – Error connecting to VM – Hyper V

November 14, 2015 1 comment

I was getting below ‘Boot failure error’, while connecting to one of my VM with Windows Server 2012 OS, from Hyper V.

Hyper V Boot Issue

Hyper V Boot Issue

Reason & Fix

  • There could be many reasons for this problem. In my case below steps solved the issue.
  • I initially chosen ‘Generation 1’ while configuring VM.
  • Re-configuring the VM by opting ‘Generation 2’ solved my issue.

 

Hyper V - Generation options

Hyper V – Generation options

Refer article on how to decide between Generation 1 and Generation 2.

🙂

Categories: Misc Tags: , ,

Duplicate record execution with System.Timer Elapsed event

We have a windows service with System.Timer control which periodically polls the records from Data Base and processes in its Elapsed event as below.

protected void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)        {

// Business logic goes here

}

Everything seems working fine until we noticed few records executing twice causing inconsistency.

The issue was random and unable to reproduce consistently.

Reason

  • Culprit was System.Timer’s Elapsed event
  • Assume the timer’s duration is 3 seconds, so every seconds Elapsed event kick in and executes the business logic. What happens if previous elapsed event would not complete before next Elapsed event ticks in.
  • This is exactly what happened in our case and caused duplicate execution of records.

Fix

  • We restricted overlap of Elapsed event using a Static variable as below

        protected static bool isInExecution = false;

protected void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)        {

if (isInExecution) return;

isInExecution = true;

// Business logic goes here

isInExecution = false;

}

🙂

Unable to get property ‘integer’ of undefined or null reference – Error jqGrid

October 25, 2014 Leave a comment

We got a requirement to display XML data in table format in HTML file. We opted jqGrid for binding xml and display the XML content.

$(“#grid”).jqGrid({ datatype: ‘xmlstring’, datastr: responseXml, xmlReader: { repeatitems: false, root: xmlRoot, row: xmlRow }

I was getting this exception when I was binding XML to the jqGrid Fix :

  • By referring “grid.locale-en.js” file in my HTML file solved the issue.(i.e., <script src=”../grid.locale.en.js”></script>)

Note : grid.locale-en.js is helper file which comes when you download jqGrid.

🙂

Exclude namespaces from XML using Jscript

In one of my requirement I had to parse XML and find node values.

 My XML looks as below

<NS1:Envelope xmlns:NS1=http://schemas.xmlsoap.org/soap/envelope/>

<QueryBalanceResult>

<NS1:AvailableCredit>17400</NS1:AvailableCredit>

</QueryBalanceResult>

</NS1:Envelope>

Since the XML has got namespaces I need to exclude namespaces before I find the node. 

Below is the logic to exclude namespaces

var xmlWithNamespaces={Your xml with namespaces};

var xmlWithNoNamespaces= xmlWithNamespaces.replace(/<(\/?)([^:>\s]*:)?([^>]+)>/g, “<$1$3>”);

🙂

 

 

Categories: Misc Tags: , , ,

Stack overflow error while disposing object – C#

September 27, 2014 Leave a comment

I have a class “ABC” which implements “IDisposable” interface and having below Dispose method.

Public Class ABC : IDisposable {

public void Dispose()       {

this.Dispose(true);

}

}

When I run the application I was getting “Stack Overflow” error because the Dispose() method getting called recursively and went in to an infinite loop.

Fix :

  • Prevent the Dispose() recursive call by using flag and the logic is as below

 private bool disposed = false;

public void Dispose() {

this.Dispose(true);

GC.SuppressFinalize(this);

}

protected virtual void Dispose(bool disposing) {

if (this.disposed) {

return;

}

this.disposed = true;

}

🙂

Categories: Misc Tags: , ,

Make your WCF service’s Operation/Method Fire and Forget

September 10, 2014 Leave a comment

There are cases when an operation has no returned values and the client does not care about the success or failure of the invocation.

To support this sort of fire-and-forget invocation, WCF offers one-way operations.

It’s simple to implement. We just need to add “IsOneWay” property to ‘true’ to the [OperationContract] property.

[ServiceContract]

interface IWCFContract

{

[OperationContract(IsOneWay = true)]

void HelloWorld()

}

Note : The Operation Contract must have a “void” return type without any outgoing parameters.

Refer this article for more.

🙂

Categories: Misc Tags: , ,