Sample Code to consume UNData API using JavaScript

Sharing a sample code that can be used to consume UNData API

The below code fetches the population data for country India.

Sample Code

var xmlHttp;
// creatng the xmlHttp object
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
// Calling the web service using post and true means asynchronous call"POST", "", false);

// Setting the request header to let the web service find the soap request we would be sending
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

xmlHttp.setRequestHeader("SOAPAction", "");

var soapRequest = "<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->xml version='1.0' encoding='utf-8'?>"+
"<soap:Envelope xmlns:soap='' xmlns:xsi='' xmlns:xsd=''>"+
"<GetCompactData xmlns=''>"+
"<message:QueryMessage xsi:schemaLocation='' xmlns:generic='' xmlns:message='' xmlns:query='' xmlns:xsi=''>"+
"<message:Sender id='online-help' />"+
"<query:Dimension id='INDICATOR'>SP_POP_TOTL</query:Dimension>"+
"<query:Dimension id='AGE'>_T</query:Dimension>"+
"<query:Dimension id='SEX'>_T</query:Dimension>"+
"<query:Dimension id='LOCATION'>_T</query:Dimension>" +
"<query:Dimension id='REF_AREA'>DEU</query:Dimension>" +
"<query:Dimension id='SCENARIO'>H</query:Dimension>"+
"</soap:Body>" +

var xmlDoc = jQuery.parseXML(xmlHttp.responseText);
var popValue = xmlDoc.getElementsByTagName('ns1:Obs')['0'].attributes['OBS_VALUE'].nodeValue;
alert("Total Population " + popValue);


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap=""
<Sender id="1B0">
<Name xml:lang="en">United Nations Statistics Division</Name>
<Source xml:lang="en">
United Nations Population Division World Population Prospects</Source>
<ns1:DataSet DATASET_NAME="World Population Prospects"
DATASET_SOURCE="United Nations Population Division"
DATASET_DESC="The United Nations World Population Prospects contains estimates and projections for every country in the world, including estimates and projections of demographic indicators such as birth rates, deaths rates, infant mortality rates and life expectancy." UNDATA_LASTUPDATE="20 Aug 2013" UNDATA_NEXTUPDATE="2015 release" METADATA=""><ns1:Series AGE="_T" FREQ="A" INDICATOR="SP_POP_TOTL" LOCATION="_T" SEX="_T" REF_AREA="DEU" SCENARIO="H"><ns1:Obs TIME_PERIOD="2015" OBS_VALUE="83178.615" UNIT="NUMBER" UNIT_MULT="3" TIME_SPAN="2015" /></ns1:Series></ns1:DataSet></CompactData></GetCompactDataResult></GetCompactDataResponse></soap:Body></soap:Envelope>

Hope it helps.

Sample code to consume UNData API in C#


Recently we were working on an application that had to fetch country specific details. For this we used the UNData API.

We can make use of SDMX Browser in helping us to write a query

Create a console app\windows application and add web reference to the following web service

Below is the sample C# Code

string queryMsg = @"<message:QueryMessage
<message:Sender id='online-help'/>
<query:Dimension id='INDICATOR'>SP_POP_TOTL</query:Dimension>
<query:Dimension id='AGE'>_T</query:Dimension>
<query:Dimension id='SEX'>_T</query:Dimension>
<query:Dimension id='LOCATION'>_T</query:Dimension>
<query:Dimension id='REF_AREA'>IND</query:Dimension>
NSIEstatV20Service service = new NSIEstatV20Service();
System.Xml.XmlDocument queryMessageDocument = new XmlDocument();
System.Xml.XmlNode queryMessage = queryMessageDocument.DocumentElement;
var result = service.GetCompactData(queryMessage);

The output

The query here basically returns the Total population of India

Hope it helps..

Solved: The remote server returned an error: (413) Request Entity Too Large in WCF Service.


Recently created a WCF Service to be used for file upload.

Was getting the below error for large file

Setting the binding in the following manner fixed the issue

<binding maxReceivedMessageSize="2147483647"
<readerQuotas maxDepth="32"

Hope it helps..

Missing Windows Authentication Provider in IIS 8 in Windows 8 or Windows 8.1

Was hosting a WCF Service in IIS on my machine.

Realized that Windows Authentication option was missing.

To add it, go to

Control Panel à Program Features à Turn Windows Features On and Off

Enable Windows Authentication.

Hope it helps

Calling a Windows Authenticated WCF Service in a Plugin in CRM


Suppose we need to call the service created here in our plugin

As plugin don’t have configuration file, we need to specify binding information in Code.

The sample code to call the WCF Service by passing Network Credentials

private static void CallWCFService()
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

// Specify the endpointAddress
EndpointAddress endpointAddress = new EndpointAddress(new Uri("http://servername:port/Service1.svc"));

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(binding, endpointAddress);
if (client.ChannelFactory.Credentials != null)
client.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password", "domain");
if (client.ClientCredentials != null)
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;

Hope it helps ..



405 error – Method not allowed error while calling WCF service inside Plugin in CRM 2011.


Recenlty we wrote a plugin that was calling a WCF Rest Service. The plugin was registered on Pre Create of an entity. Here if we were creating the entity record through web interface, the plugin was running fine.

However if we had that plugin being triggered by another plugin (the other plugin was creating the entity record triggering this particular plugin) we were getting “405 – method not allowed” error.

As it turned out the WCF service was getting confused regarding the operation context when being called by another plugin.

Specifying the OperationContextScope fixed the issue.

Original Code

using (
 var webChannelFactory =
 new WebChannelFactory<IAutoNumber>(
 new Uri(dictionaryConfigSettings[Constants.AutoNumberServiceUrl])))
 IAutoNumber referralOffer = webChannelFactory.CreateChannel();

// get the next number from sequence
 autoNumber = Constants.PrefixReferralOfferNumber +

The modified code

using (
 var webChannelFactory =
 new WebChannelFactory<IAutoNumber>(
 new Uri(dictionaryConfigSettings[Constants.AutoNumberServiceUrl])))
 IAutoNumber referralOffer = webChannelFactory.CreateChannel();

using (new OperationContextScope((IContextChannel)referralOffer))
 // get the next number from sequence
 autoNumber = Constants.PrefixReferralOfferNumber +


The helpful post,guid,26d9b30e-c441-4776-9778-4dfdab58bd3d.aspx

Hope it helps.

The data contract type cannot be serialized in partial trust because the member is not public while using Serialization in the sandboxed plugin in CRM 2011


Was getting the below error while serializing the CRM Entity as mentioned here

Then gave it a try with a DataContract just to check if it works properly with it or not. It worked properly on the sandbox plugin.

Please check the below discussion for more details.


Calling WCF Rest Service from a Plugin in CRM 2011 (Online)

Let us take a simple rest service example here

It returns the string “You have asked for photos”.

Within the plugin class add references to following assemblies.

The sample code of the plugin

namespace TestPlugin
 public class Class1 : IPlugin
 public void Execute(IServiceProvider serviceProvider)
 IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

 if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

// using WebClient
 WebClient webClient1 = new WebClient();
 string data1 = webClient1.DownloadString("");

// using WebChannelFactory
 WebChannelFactory<IPhotos> factory = new WebChannelFactory<IPhotos>(new Uri(""));
 IPhotos proxy = factory.CreateChannel();
 string photos = proxy.GetPhotos();



 public interface IPhotos
 [WebGet(UriTemplate = "Photos")]
 string GetPhotos();

Register the plugin in Sandbox mode for CRM 2011 online.

Check this wonderful post for all the details

Hope it helps.

“Network Error” while calling WCF Service through JavaScript.


I was getting the following “Network Error” on calling WCF Service using XMLHttpRequest within an html page through JavaScript.

I was using IE 10 in a Windows 8 machine.

After some searching found out that this is a known issue.

Running the same in compatibility mode worked properly.

Hope it helps.

An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.

We were getting the above error while testing one of our WCF service. On syncing the clock of our client and server machine we were able to resolve the issue.

This helped us resolve the issue



Using JavaScript to consume a WCF service

Suppose this is our simple WCF service which takes the name as input and returns the resulting string with Hello appended to it.

namespace HelloWorldWCFService{
public interface IService1
string GetData(string name);

namespace HelloWorldWCFService{
public class Service1 : IService1 {
public string GetData(string name) {
return “Hello “ + name;

It uses BasicHttpBinding.

Now this would be our JavaScript function which can consume the above WCF service.

function MyRequest() {var xmlhttp = new XMLHttpRequest();‘POST’, http://localhost:64833/Service1.svc&#8217;, false);xmlhttp.setRequestHeader(‘SOAPAction’,;);

xmlhttp.setRequestHeader(‘Content-Type’, ‘text/xml’);
var data = ;

data += ‘<s:Envelope xmlns:s=””>&#8217;;data += ‘ <s:Body>’;

data += ‘ <GetData xmlns=””>&#8217;;

data += ‘ <name>Nishant</name>’;

data += ‘ </GetData>’;

data += ‘ </s:Body>’;

data += ‘</s:Envelope>’;xmlhttp.send(data);

alert(“status = “ + xmlhttp.status);alert(“status text = “ + xmlhttp.statusText);



Here for


We can get the value for SOAPAction from the wsdl of the WCF service. 

Open the http://localhost:64833/Service1.svc?wsdl

Search for soapAction there.

We would find soapAction value there.

<wsdl:operation name=”GetData“>  <soap:operation
soapAction=” style=”document” />

Hope it helps !