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.

Advertisements

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..

Customizing Default IE Test Page for ASP.NET web service

Hi,

When we create ASP.NET web service from visual studio and run the web service a test page opens up in which we can test our web service.

We can easily customize that web service test page. The name of the page is DefaultWsdlHelpGenerator.aspx we can found it in the following directory

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\ for ASP.NET 2.0.

Open the page in Visual Studio

First and foremost we would find the following things that could be configured

// set this to true if you want to see a POST test form instead of a GET test form
bool showPost = true;

// set this to true if you want to see the raw XML as outputted from the XmlWriter (useful for debugging)
bool dontFilterXml = false;

// set this higher or lower to adjust the depth into your object graph of the sample messages
int maxObjectGraphDepth = 4;

// set this higher or lower to adjust the number of array items in sample messages
int maxArraySize = 2;

// set this to true to see debug output in sample messages
bool debug = false;

To customize the UI good information is provided over here

Customizing Web Service Test Page’s UI Design

By Default the web service can be tested using Http Get (default) and Http Post, but if we want to test using the SOAP we can make use of the information provided in the following link

Testing Web Service with SOAP

Bye

Consuming an Asp.NET web service using SOAP protocol from JavaScript

There are many ways we can consume a web service
The three common protocols for accessing a .NET web service are
HTTP GET, HTTP POST and SOAP.
The trasport protocol used for them is HTTP. However a web sercie can work on any other internet protocol like SMTP, FTP, Jabber, and TCP.

For HTTP GET and HTTP POST method you can refer to these posts
https://nishantrana.wordpress.com/2007/10/22/calling-aspnet-web-service-from-javascript-ajax-passing-parameter/
https://nishantrana.wordpress.com/2007/10/22/calling-aspnet-web-service-from-javascript-ajax-passing-parameter-post/
The proxy class generated by Visual studio for us using the wsdl itself uses the SOAP.
Let’s take an example of calling the simple web service using SOAP through java script.
Say this is our sample web service

[WebService(Namespace = “http://myNamespace/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(String name) {
return “Hello “+name;
}

}

The javascript code that we can use to call this web service using SOAP request would be this
<script type=”text/javascript”>
var xmlHttp;
function SoapCall()
{
// creatng the xmlHttp object
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
// Calling the web service using post and true means asynchronous call
xmlHttp.open(“post”, “http://localhost/WebSite/WebSite4/Service.asmx&#8221;, true);
// Setting the request header to let the web service identify the soap request we would be sending
xmlHttp.setRequestHeader(“Content-Type”,”text/xml; charset=utf-8″);
// http://myNamespace/HelloWorld – name of the webmethod
//[WebService(Namespace = “http://myNamespace/&#8221;)] which we had applied to our web service class
xmlHttp.setRequestHeader(“SOAPAction”,”http://myNamespace/HelloWorld&#8221;);
xmlHttp.onreadystatechange=doUpdate;
// setting the soap request body
var soapRequest=”<?xml version=’1.0′ encoding=’utf-8′?>” +
“<soap:Envelope xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance'”+
” xmlns:xsd=’http://www.w3.org/2001/XMLSchema&#8217; xmlns:soap=’http://schemas.xmlsoap.org/soap/envelope/’>”+
“<soap:Body>”+
“<HelloWorld xmlns=’http://myNamespace/’>”+
“<name>Nishant Rana</name> “+
“</HelloWorld>”+
” </soap:Body>”+
“</soap:Envelope>”;


xmlHttp.send(soapRequest);
return false;


}

function doUpdate()
{
debugger;
if(xmlHttp.readyState==4)
{
var responseXMLResult=xmlHttp.responseXML;
var result = responseXMLResult.lastChild.nodeTypedValue;
alert(result);
}
}
</script>

We will receive the following Soap Response
<?xml version=”1.0″ encoding=”utf-8″?>
<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<soap:Body>
<HelloWorldResponse xmlns=”http://myNamespace/”&gt;
<HelloWorldResult>Hello Nishant Rana</HelloWorldResult>
</HelloWorldResponse>
</soap:Body>
</soap:Envelope>

We can create our SOAP request by making use of the test page of our Web Service which we can open in IE.

Or else we can use Fiddler tool. (http://www.fiddlertool.com/fiddler/)

Bye..

Url Behaviour – Asp.NET web service

When adding a webreference to a webservice in visual studio we can set the Url Behaviour property inside visual studio.

In visual studio 2003 by default it is set to static and in visual studio 2005 it is set default to dynamic.

Static means the url is set in the code within the generated proxy class Reference.cs.

Normally this file doesn’t show up in visual studio. Using Show All Files option in visual studio displays this file.

This is what would be there in generated proxy class for Url Behaviour Static

public CrmService() {

this.Url = http://d-3324:5555/mscrmservices/2006/crmservice.asmx&#8221;;

And in case of Dynamic we will find a corresponding entry for the url in our application config file.

<applicationSettings>

<WindowsFormsApplication1.Properties.Settings>

<setting name=WindowsFormsApplication1_CrmSdk_CrmService serializeAs=String>

<value>http://d-3324:5555/mscrmservices/2006/crmservice.asmx</value>

</setting>

</WindowsFormsApplication1.Properties.Settings>

</applicationSettings>

And inside our proxy class

public CrmService() {

this.Url = global::WindowsFormsApplication1.Properties.Settings.Default.WindowsFormsApplication1_CrmSdk_CrmService;

Bye

There was an error downloading ‘http://localhost/…./Service.asmx’. The request failed with HTTP status 503: Service Unavailable.

I was receiving this error when I was trying to add web reference to the webservice which was deployed in our server from inside our Visual Studio.

 

But putting the same url in the IE, everything seemed to work fine. So there was no issue of IIS not running.

 

Later I realized that the issue was because of the a software that I was using Ultrasurf (UltraSurf is the flagship software product from UltraReach Internet Corp. for Internet anti-censorship. It enables users inside countries with heavy Internet censorship to visit any public web sites in the world safely and freely.)

 

But even after closing the UltraSurf the problem persisted. I restarted the system, cleared my system using CCleaner but wasn’t able to solve the problem.

 

Finally this is something I tried and it worked for me

 

I went to Tools Internet Options Connections (tab) LAN Settings for IE

 

In the LAN settings dialog box, checkbox Bypass Proxy Server for local addresses was checked so I unchecked it than clicked OK two times to close both the dialog boxes.

 

Then again went to Tools Internet OptionsConnections (tab) LAN Settings

And in the LAN setting dialog box again checked it.

 

This way I was able to resolve the issue of not being able to add web reference to web services from inside Visual Studio.