Sample Code to consume UNData API using JavaScript

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

http://data.un.org/Host.aspx?Content=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
xmlHttp.open("POST", "http://data.un.org/WS/NSIEstatV20Service.asmx", 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", "http://ec.europa.eu/eurostat/sri/service/2.0/extended/GetCompactData");

var soapRequest = "<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->xml version='1.0' encoding='utf-8'?>"+
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
"<soap:Body>"+
"<GetCompactData xmlns='http://ec.europa.eu/eurostat/sri/service/2.0/extended'>"+
"<Query>"+
"<message:QueryMessage xsi:schemaLocation='http://ec.europa.eu/eurostat/sri/service/2.0/SDMXMessage.xsd http://ec.europa.eu/eurostat/sri/service/2.0/%20SDMXMessage.xsd' xmlns:generic='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic' xmlns:message='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message' xmlns:query='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"+
"<message:Header>"+
"<message:ID>onh14833545733929527</message:ID>"+
"<message:Test>false</message:Test>"+
"<message:Prepared>2017-01-01</message:Prepared>"+
"<message:Sender id='online-help' />"+
"</message:Header>"+
"<message:Query>"+
"<query:DataWhere>"+
"<query:And>"+
"<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>"+
"<query:Time>"+
"<query:StartTime>2014-01-02</query:StartTime>"+
"<query:EndTime>2017-01-02</query:EndTime>"+
"</query:Time>"+
"<query:Dataflow>DF_UNDATA_WPP</query:Dataflow>"+
"</query:And>"+
"</query:DataWhere>"+
"</message:Query>"+
"</message:QueryMessage>"+
"</Query>"+
"</GetCompactData>"+
"</soap:Body>" +
"</soap:Envelope>";

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

Output


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body><GetCompactDataResponse
xmlns="http://ec.europa.eu/eurostat/sri/service/2.0/extended">
<GetCompactDataResult>
<CompactData
xmlns:ns1="urn:sdmx:org.sdmx.infomodel.datastructure.DataStructure
=UNSD:DSD_WPP_UNDATA(1.0):ObsLevelDim:TIME_PERIOD"
xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message"
xmlns:common="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xml="http://www.w3.org/XML/1998/namespace"><Header>
<ID>DF_UNDATA_WPP</ID><Test>false</Test><Prepared>2017-01-06T08:25:46
</Prepared>
<Sender id="1B0">
<Name xml:lang="en">United Nations Statistics Division</Name>
<Contact><Email>statistics@un.org</Email></Contact></Sender>
<KeyFamilyRef>DSD_WPP_UNDATA</KeyFamilyRef><KeyFamilyAgency>UNSD
</KeyFamilyAgency><DataSetAgency>UNSD</DataSetAgency>
<DataSetID>DF_UNDATA_WPP_1B0_2017-01-06T082546</DataSetID>
<DataSetAction>Information</DataSetAction>
<Extracted>2017-01-06T08:25:46</Extracted>
<Source xml:lang="en">
United Nations Population Division World Population Prospects</Source>
</Header>
<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="http://esa.un.org/unpd/wpp/index.htm"><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#

Hi,

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

http://data.un.org/Host.aspx?Content=API

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

http://data.un.org/SdmxBrowser/start

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

http://data.un.org/WS/NSIEstatV20Service.asmx

Below is the sample C# Code


string queryMsg = @"<message:QueryMessage
xsi:schemaLocation='http://ec.europa.eu/eurostat/sri/service/2.0/SDMXMessage.xsd
http://ec.europa.eu/eurostat/sri/service/2.0/%20SDMXMessage.xsd'
xmlns:generic='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic'
xmlns:message='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message'
xmlns:query='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
<message:Header>
<message:ID>onh14833545733929527</message:ID>
<message:Test>false</message:Test>
<message:Prepared>2017-01-01</message:Prepared>
<message:Sender id='online-help'/>
</message:Header>
<message:Query>
<query:DataWhere>
<query:And>
<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>
<query:Time>
<query:StartTime>2014-01-02</query:StartTime>
<query:EndTime>2017-01-02</query:EndTime>
</query:Time>
<query:Dataflow>DF_UNDATA_WPP</query:Dataflow>
</query:And>
</query:DataWhere>
</message:Query>
</message:QueryMessage>";
NSIEstatV20Service service = new NSIEstatV20Service();
System.Xml.XmlDocument queryMessageDocument = new XmlDocument();
queryMessageDocument.LoadXml(queryMsg);
System.Xml.XmlNode queryMessage = queryMessageDocument.DocumentElement;
var result = service.GetCompactData(queryMessage);
MessageBox.Show(result.InnerXml);

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.

Hi,

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


<bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647">
<readerQuotas maxDepth="32"
maxArrayLength="2147483647"
maxStringContentLength="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>


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

Configure a WCF Service for Windows Authentication

Hi,

Sharing a simple example on how to enable Windows Authentication for a WCF Service using basicHttpBinding.

We will take an example of the OOB WCF Service that gets created when we create a new WCF Service Application.

Add the following configuration in web.config


<system.serviceModel>
<services>
<service name="WcfService2.Service1">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="myBinding" contract="WcfService2.IService1"/>
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="myBinding" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>

&nbsp;

And enable Windows Authentication in IIS

 

Hope it helps ..

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

Hi,

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

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

// get the next number from sequence
 autoNumber = Constants.PrefixReferralOfferNumber +
 AddPadding(
 referralOffer.GetNextNumber(Constants.EntityNameReferralOffer),
 Constants.PrefixReferralOfferNumberLength);
 }
<pre>

The modified code

</pre>
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 +
 AddPadding(
 referralOffer.GetNextNumber(Constants.EntityNameReferralOffer),
 Constants.PrefixReferralOfferNumberLength);
 }

}
<pre>

The helpful post

http://www.rgoarchitects.com/nblog/CommentView,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

Hi,

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.

http://social.microsoft.com/Forums/en-US/d0332c9c-3cef-4b34-8c11-2b263369e21f/serializing-entity-in-sandbox-doesnt-work

Bye.

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

Let us take a simple rest service example here

http://www.rockycherry.net/services/Photos/photos.svc/photos

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("http://www.rockycherry.net/services/Photos/photos.svc/photos");

// using WebChannelFactory
 WebChannelFactory<IPhotos> factory = new WebChannelFactory<IPhotos>(new Uri("http://www.rockycherry.net/services/Photos/photos.svc"));
 IPhotos proxy = factory.CreateChannel();
 string photos = proxy.GetPhotos();

 }

 }
 }

[ServiceContract]
 public interface IPhotos
 {
 [WebGet(UriTemplate = "Photos")]
 [OperationContract]
 string GetPhotos();
 }
}


Register the plugin in Sandbox mode for CRM 2011 online.

Check this wonderful post for all the details

http://rockycherry.net/blog/?p=179

Hope it helps.

Integrating CRM 2011 and SharePoint 2013 using BCS (WCF Service – CRUD Operation)

Create a new WCF Service Application in Visual Studio with .NET Framework version as 4.0 (since we will be using CRM 2011’s assembly that are in version 4.0).

Please go through this MSDN article first to get a clear understanding on the BCS Service

http://msdn.microsoft.com/en-us/library/office/ff953200(v=office.14).aspx

Define the Service Contract and the Date Contract in the following manner. Here we would be performing CRUD operation on Date of Birth and Last Name field of the Contact Entity.

Add references to the following assemblies

Microsoft.BusinessData can be found at

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI on the SharePoint Server.


[ServiceContract]
 public interface IService1
 {
 [OperationContract]
 IEnumerable<ContactEntity> ReadList();

[OperationContract]
 ContactEntity ReadItem(Guid contactId);

[OperationContract]
 ContactEntity Create(ContactEntity newContact);

[OperationContract]
 void Update(ContactEntity contact);

[OperationContract]
 void Delete(Guid contactId);
 }

 [DataContract]
 public class ContactEntity
 {
 [DataMember]
 public Guid ContactId { get; set; }

[DataMember]
 public DateTime? DateOfBirth { get; set; }

[DataMember]
 public string LastName { get; set; }
 }


Implement the Service Contract


public class Service1 : IService1
 {
 private readonly IOrganizationService _orgService = GetOrganizationService();

public ContactEntity ReadItem(Guid contactId)
 {
 try
 {
 var cols = new ColumnSet(new[] {"lastname", "birthdate"});
 ContactEntity contactRecord = null;
 Entity entity = _orgService.Retrieve("contact", contactId, cols);
 if (entity != null)
 {
 contactRecord = new ContactEntity();
 contactRecord.ContactId = contactId;
 if (entity.Contains("lastname"))
 {
 contactRecord.LastName = entity.Attributes["lastname"].ToString();
 }
 if (entity.Contains("birthdate"))
 {
 contactRecord.DateOfBirth = (DateTime) entity.Attributes["birthdate"];
 }
 }

return contactRecord;
 }
 catch (InvalidOperationException)
 {
 throw new ObjectNotFoundException(
 "Unable to read data for the conatct with ID = " +
 contactId.ToString() +
 ". The contact no longer exists.");
 }
 catch (Exception generalException)
 {
 throw new RuntimeException(
 "There was a problem reading contact data.",
 generalException);
 }
 }

public IEnumerable<ContactEntity> ReadList()
 {
 try
 {
 var queryExpression = new QueryExpression("contact");
 var conditionExpression = new ConditionExpression("statuscode", ConditionOperator.Equal, 1);
 queryExpression.ColumnSet = new ColumnSet(new[] {"contactid", "lastname", "birthdate"});
 queryExpression.Criteria.AddCondition(conditionExpression);

EntityCollection contactCollection = _orgService.RetrieveMultiple(queryExpression);
 var lstContactType = new List<ContactEntity>();
 ContactEntity contactRecord;
 foreach (Entity entity in contactCollection.Entities)
 {
 contactRecord = new ContactEntity();
 contactRecord.ContactId = new Guid(entity.Attributes["contactid"].ToString());
 if (entity.Contains("lastname"))
 {
 contactRecord.LastName = entity.Attributes["lastname"].ToString();
 }
 if (entity.Contains("birthdate"))
 {
 contactRecord.DateOfBirth = (DateTime) entity.Attributes["birthdate"];
 }

lstContactType.Add(contactRecord);
 }

return lstContactType;
 }
 catch (Exception generalException)
 {
 throw new RuntimeException(
 "There was a problem reading contact data.",
 generalException);
 }
 }

public ContactEntity Create(ContactEntity newContact)
 {
 try
 {
 var returnContact = new ContactEntity();
 returnContact.ContactId = Guid.NewGuid();
 returnContact.DateOfBirth = newContact.DateOfBirth;
 returnContact.LastName = newContact.LastName;

var contactRecord = new Entity();
 contactRecord.LogicalName = "contact";
 contactRecord.Attributes["lastname"] = returnContact.LastName;
 contactRecord.Attributes["contactid"] = returnContact.ContactId;
 contactRecord.Attributes["birthdate"] = returnContact.DateOfBirth;
 newContact.ContactId = _orgService.Create(contactRecord);

return returnContact;
 }
 catch (Exception generalException)
 {
 throw new RuntimeException(
 "There was a problem creating a new contact.",
 generalException);
 }
 }


 public void Update(ContactEntity updateContact)
 {
 try
 {
 var contactRecord = new Entity();
 contactRecord.LogicalName = "contact";
 contactRecord.Attributes["lastname"] = updateContact.LastName;
 contactRecord.Attributes["contactid"] = updateContact.ContactId;
 contactRecord.Attributes["birthdate"] = updateContact.DateOfBirth;

_orgService.Update(contactRecord);
 }
 catch (InvalidOperationException)
 {
 throw new ObjectNotFoundException(
 "Unable to update the contact with ID = " +
 updateContact.ContactId.ToString() +
 ". The contact no longer exists.");
 }
 catch (Exception generalException)
 {
 throw new RuntimeException(
 "There was a problem updating the lawyer with ID = " +
 updateContact.ContactId.ToString() + ".", generalException);
 }
 }

public void Delete(Guid contactId)
 {
 try
 {
 _orgService.Delete("contact", contactId);
 }
 catch (InvalidOperationException)
 {
 throw new ObjectNotFoundException(
 "Unable to delete the contact with ID = " +
 contactId.ToString() +
 ". The contact no longer exists.");
 }
 catch (Exception generalException)
 {
 throw new RuntimeException(
 "There was a problem lawyer the customer with ID = " +
 contactId.ToString() + ".", generalException);
 }
 }

public static IOrganizationService GetOrganizationService()
 {
 var organizationUri = new Uri("http://crmserver/orgname/XRMServices/2011/Organization.svc");
 Uri homeRealmUri = null;
 var credentials = new ClientCredentials();
 credentials.Windows.ClientCredential = new NetworkCredential("username", "password", "domain");
 var orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
 IOrganizationService _service = orgProxy;
 return _service;
 }

 

Host the Service in the IIS.

Open SharePoint Designer 2013 and connect to the site where we want to create an external content type based on our WCF Service.

Create a new External Content Type

Specify name for the content type and click on the link for defining operations

Click on Add Connection and specify WCF Service as the connection type

Specify the url of the WCF service

For each of the Web Methods, specify the corresponding operation.

For each of the operations define ContactId as Identifier

Once defined, select Create Lists and Form button

Open the SharePoint site and open the list created

Corresponding contact records in CRM

Hope it helps.

“Network Error” while calling WCF Service through JavaScript.

Hi,

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.

http://bugs.jquery.com/ticket/12790

Running the same in compatibility mode worked properly.

Hope it helps.