Advertisements

Archive

Archive for the ‘Misc’ Category

DataTable – Destory() method not removing all the rows

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

DataTable

I used below snippet to bind the results.

var table = $(‘#customGrid‘).DataTable({
data: rows,
destroy: true,
columns: columns,
oLanguage: {
sLengthMenu: ‘Show _MENU_ items’,
sInfo: ” <b>Showing _START_ – _END_ of _TOTAL_ items</b>”,
sInfoEmpty: ‘ <b>Showing 0 – 0 of 0 items</b>’,
sEmptyTable: “No data to display”
},
‘columnDefs’: [
]
});

In the above snippet

  • #customGrid – Is ID of a HTML <Table> object which we use for DataTable.
    • <table id=”customGrid” class=”display”></table>
  • rows – JSon collection

Problem statement:

I am using ‘DataTable’ in one of my custom HTML Search pages

  • I was binding the Search results to the DataTable up on Search button click and have to clear the previous results when no match results found.
  • I was calling destroy() function to clear off the rows from previous Search.

if ($.fn.DataTable.isDataTable(“#customGrid”)) {
$(“#customGrid”).DataTable().destroy();
}

  • However, destroy() its not removing all the rows.

Reason and Fix:

  • destroy() remove all defined events and properties of DataTable object.
  • Its not clearing the <table> object rows (This may have fixed or changed in latest versions)
  •  So, to clear the rows, you must call empty() function of <table> object.
  • Below is the final code

if ($.fn.DataTable.isDataTable(“#customGrid”)) {
     // Destroy ‘DataTable’ object
$(“#customGrid”).DataTable().destroy();
    // Remove the <table> rows
    $(“#customGrid”).empty();
}

🙂

Advertisements
Categories: Misc Tags: ,

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;

}

🙂