I want to consume ASMX service in my titanium project, for that I have used the Kitchen Sink Nook project and it works well for the currency convertor asmx webservice and it doesn't have the authentication header.
But I have authentication header for my client webservice, I have tested the below webservice in SOAP UI and it works perfect. But I don't get the solution for Titanium SOAP Call.
Calling_class.js
Titanium.include('suds.js');
var window = Ti.UI.createWindow({
title:"Web Service Test",
backgroundColor:"#FFF",
exitOnClose:true
});
var label = Ti.UI.createLabel({
top: 10,
left: 10,
width: 'auto',
height: 'auto',
text: 'Contacting currency rates web service...'
});
var bouton = Titanium.UI.createButton({
title:"Test",
bottom:20,
height:120,
width:135,
});
window.add(label);
var url = "http://192.168.15.45:8082/CrmAppointments.asmx";
var callparams = {
AppointmentNumber: 'APP-00000003-H042S5',
UserId: '4'
};
var suds = new SudsClient({
endpoint: url,
targetNamespace: 'http://tempuri.org'
});
bouton.addEventListener("click", function(e){
try {
suds.invoke('BookAppointmentFromWCF', callparams, function(xmlDoc) {
console.log('response : '+ this.responseText);
var results = xmlDoc.documentElement.getElementsByTagName('BookAppointmentFromWCF');
if (results && results.length>0) {
var result = results.item(0);
label.text = '1 Euro buys you ' + results.item(0).text + ' U.S. Dollars.';
} else {
label.text = 'Oops, could not determine result of SOAP call.';
}
});
} catch(e) {
Ti.API.error('Error: ' + e);
}
});
window.add(bouton);
window.open();
suds.js
/**
* Suds: A Lightweight JavaScript SOAP Client
* Copyright: 2009 Kevin Whinnery (http://www.kevinwhinnery.com)
* License: http://www.apache.org/licenses/LICENSE-2.0.html
* Source: http://github.com/kwhinnery/Suds
*/
function SudsClient(_options) {
function isBrowserEnvironment() {
try {
if (window && window.navigator) {
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
function isAppceleratorTitanium() {
try {
if (Titanium) {
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
//A generic extend function - thanks MooTools
function extend(original, extended) {
for (var key in (extended || {})) {
if (original.hasOwnProperty(key)) {
original[key] = extended[key];
}
}
return original;
}
//Check if an object is an array
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
//Grab an XMLHTTPRequest Object
function getXHR() {
var xhr;
if (isBrowserEnvironment()) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else if (isAppceleratorTitanium()) {
xhr = Titanium.Network.createHTTPClient();
}
return xhr;
}
//Parse a string and create an XML DOM object
function xmlDomFromString(_xml) {
var xmlDoc = null;
if (isBrowserEnvironment()) {
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(_xml,"text/xml");
}
else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(_xml);
}
}
else if (isAppceleratorTitanium()) {
xmlDoc = Titanium.XML.parseString(_xml);
}
return xmlDoc;
}
// Convert a JavaScript object to an XML string - takes either an
function convertToXml(_obj, namespacePrefix) {
var xml = '';
if (isArray(_obj)) {
for (var i = 0; i < _obj.length; i++) {
xml += convertToXml(_obj[i], namespacePrefix);
}
} else {
//For now assuming we either have an array or an object graph
for (var key in _obj) {
if (namespacePrefix && namespacePrefix.length) {
xml += '<' + namespacePrefix + ':' + key + '>';
} else {
xml += '<'+key+'>';
}
if (isArray(_obj[key]) || (typeof _obj[key] == 'object' && _obj[key] != null)) {
xml += convertToXml(_obj[key]);
}
else {
xml += _obj[key];
}
if (namespacePrefix && namespacePrefix.length) {
xml += '</' + namespacePrefix + ':' + key + '>';
} else {
xml += '</'+key+'>';
}
}
}
return xml;
}
// Client Configuration
var config = extend({
endpoint:'http://localhost',
targetNamespace: 'http://localhost',
envelopeBegin: '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:ns0="PLACEHOLDER" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><ns0:Authentication><ns0:Username>Infrab</ns0:Username><ns0:Password>ZxH35oCeXnA</ns0:Password></ns0:Authentication></soap:Header><soap:Body>',
envelopeEnd: '</soap:Body></soap:Envelope>'
},_options);
// Invoke a web service
this.invoke = function(_soapAction,_body,_callback) {
//Build request body
var body = _body;
//Allow straight string input for XML body - if not, build from object
if (typeof body !== 'string') {
body = '<ns0:'+_soapAction+'>';
body += convertToXml(_body, 'ns0');
body += '</ns0:'+_soapAction+'>';
}
var ebegin = config.envelopeBegin;
config.envelopeBegin = ebegin.replace('PLACEHOLDER', config.targetNamespace);
//Build Soapaction header - if no trailing slash in namespace, need to splice one in for soap action
var soapAction = '';
if (config.targetNamespace.lastIndexOf('/') != config.targetNamespace.length - 1) {
soapAction = config.targetNamespace+'/'+_soapAction;
}
else {
soapAction = config.targetNamespace+_soapAction;
}
//POST XML document to service endpoint
var xhr = getXHR();
xhr.onload = function() {
_callback.call(this, xmlDomFromString(this.responseText));
};
xhr.open('POST',config.endpoint);
xhr.setRequestHeader('Content-Type', 'text/xml');
xhr.setRequestHeader('SOAPAction', soapAction);
xhr.send(config.envelopeBegin+body+config.envelopeEnd);
console.log(config.envelopeBegin+body+config.envelopeEnd);
};
}
The main methods in this code is the var config = extend({ which is the client configuration for SOAP xml. When I execute I get this 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>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Server was unable to process request. ---> Object reference not set to an instance of an object.</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
I've checked SOAP UI for testing the webservice by removing the authentication header, and it gives me the same exact error like in Titanium.
My question is how would I can pass the Authentication header with username and password values?
Related
Following this Streaming CloudWatch Logs Data to Amazon Elasticsearch Service, it's working fine to stream cloud watch log to ELK having one log group and one Lambda function.
But now I want to change target lambda function for my other logs group, but I am not able to do that as there is no option in AWS console.
Any Help will be appreciated.
Thanks
I was streaming to ELK using the AWS console option which is Start Streaming to Amazon Elasticsearch Service, But I failed to change or choose different lambda function as there is only lambda function can be selected for any log group using this option.
So, I create new lambda function and set stream target to AWS lambda function,
Here is the code that all you need, Node version for lambda function is 4.* as it was some issue with the new version but the pulse point is it does not require any extra NPM packages.
// v1.1.2
var https = require('https');
var zlib = require('zlib');
var crypto = require('crypto');
var endpoint = 'search-my-test.us-west-2.es.amazonaws.com';
exports.handler = function(input, context) {
// decode input from base64
var zippedInput = new Buffer(input.awslogs.data, 'base64');
// decompress the input
zlib.gunzip(zippedInput, function(error, buffer) {
if (error) { context.fail(error); return; }
// parse the input from JSON
var awslogsData = JSON.parse(buffer.toString('utf8'));
// transform the input to Elasticsearch documents
var elasticsearchBulkData = transform(awslogsData);
// skip control messages
if (!elasticsearchBulkData) {
console.log('Received a control message');
context.succeed('Control message handled successfully');
return;
}
// post documents to the Amazon Elasticsearch Service
post(elasticsearchBulkData, function(error, success, statusCode, failedItems) {
console.log('Response: ' + JSON.stringify({
"statusCode": statusCode
}));
if (error) {
console.log('Error: ' + JSON.stringify(error, null, 2));
if (failedItems && failedItems.length > 0) {
console.log("Failed Items: " +
JSON.stringify(failedItems, null, 2));
}
context.fail(JSON.stringify(error));
} else {
console.log('Success: ' + JSON.stringify(success));
context.succeed('Success');
}
});
});
};
function transform(payload) {
if (payload.messageType === 'CONTROL_MESSAGE') {
return null;
}
var bulkRequestBody = '';
payload.logEvents.forEach(function(logEvent) {
var timestamp = new Date(1 * logEvent.timestamp);
// index name format: cwl-YYYY.MM.DD
var indexName = [
'prod-background-wo-' + timestamp.getUTCFullYear(), // year
('0' + (timestamp.getUTCMonth() + 1)).slice(-2), // month
('0' + timestamp.getUTCDate()).slice(-2) // day
].join('.');
var source = buildSource(logEvent.message, logEvent.extractedFields);
source['response_time'] = source["end"] - source["start"];
source['#id'] = logEvent.id;
source['#timestamp'] = new Date(1 * logEvent.timestamp).toISOString();
source['#message'] = logEvent.message;
source['#owner'] = payload.owner;
source['#log_group'] = payload.logGroup;
source['#log_stream'] = payload.logStream;
var action = { "index": {} };
action.index._index = indexName;
action.index._type = payload.logGroup;
action.index._id = logEvent.id;
bulkRequestBody += [
JSON.stringify(action),
JSON.stringify(source),
].join('\n') + '\n';
});
return bulkRequestBody;
}
function buildSource(message, extractedFields) {
if (extractedFields) {
var source = {};
for (var key in extractedFields) {
if (extractedFields.hasOwnProperty(key) && extractedFields[key]) {
var value = extractedFields[key];
if (isNumeric(value)) {
source[key] = 1 * value;
continue;
}
jsonSubString = extractJson(value);
if (jsonSubString !== null) {
source['$' + key] = JSON.parse(jsonSubString);
}
source[key] = value;
}
}
return source;
}
jsonSubString = extractJson(message);
if (jsonSubString !== null) {
return JSON.parse(jsonSubString);
}
return {};
}
function extractJson(message) {
var jsonStart = message.indexOf('{');
if (jsonStart < 0) return null;
var jsonSubString = message.substring(jsonStart);
return isValidJson(jsonSubString) ? jsonSubString : null;
}
function isValidJson(message) {
try {
JSON.parse(message);
} catch (e) { return false; }
return true;
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function post(body, callback) {
var requestParams = buildRequest(endpoint, body);
var request = https.request(requestParams, function(response) {
var responseBody = '';
response.on('data', function(chunk) {
responseBody += chunk;
});
response.on('end', function() {
var info = JSON.parse(responseBody);
var failedItems;
var success;
if (response.statusCode >= 200 && response.statusCode < 299) {
failedItems = info.items.filter(function(x) {
return x.index.status >= 300;
});
success = {
"attemptedItems": info.items.length,
"successfulItems": info.items.length - failedItems.length,
"failedItems": failedItems.length
};
}
var error = response.statusCode !== 200 || info.errors === true ? {
"statusCode": response.statusCode,
"responseBody": responseBody
} : null;
callback(error, success, response.statusCode, failedItems);
});
}).on('error', function(e) {
callback(e);
});
request.end(requestParams.body);
}
function buildRequest(endpoint, body) {
var endpointParts = endpoint.match(/^([^\.]+)\.?([^\.]*)\.?([^\.]*)\.amazonaws\.com$/);
var region = endpointParts[2];
var service = endpointParts[3];
var datetime = (new Date()).toISOString().replace(/[:\-]|\.\d{3}/g, '');
var date = datetime.substr(0, 8);
var kDate = hmac('AWS4' + process.env.AWS_SECRET_ACCESS_KEY, date);
var kRegion = hmac(kDate, region);
var kService = hmac(kRegion, service);
var kSigning = hmac(kService, 'aws4_request');
var request = {
host: endpoint,
method: 'POST',
path: '/_bulk',
body: body,
headers: {
'Content-Type': 'application/json',
'Host': endpoint,
'Content-Length': Buffer.byteLength(body),
'X-Amz-Security-Token': process.env.AWS_SESSION_TOKEN,
'X-Amz-Date': datetime
}
};
var canonicalHeaders = Object.keys(request.headers)
.sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; })
.map(function(k) { return k.toLowerCase() + ':' + request.headers[k]; })
.join('\n');
var signedHeaders = Object.keys(request.headers)
.map(function(k) { return k.toLowerCase(); })
.sort()
.join(';');
var canonicalString = [
request.method,
request.path, '',
canonicalHeaders, '',
signedHeaders,
hash(request.body, 'hex'),
].join('\n');
var credentialString = [ date, region, service, 'aws4_request' ].join('/');
var stringToSign = [
'AWS4-HMAC-SHA256',
datetime,
credentialString,
hash(canonicalString, 'hex')
] .join('\n');
request.headers.Authorization = [
'AWS4-HMAC-SHA256 Credential=' + process.env.AWS_ACCESS_KEY_ID + '/' + credentialString,
'SignedHeaders=' + signedHeaders,
'Signature=' + hmac(kSigning, stringToSign, 'hex')
].join(', ');
return request;
}
function hmac(key, str, encoding) {
return crypto.createHmac('sha256', key).update(str, 'utf8').digest(encoding);
}
function hash(str, encoding) {
return crypto.createHash('sha256').update(str, 'utf8').digest(encoding);
}
I'm currently working in wso2 carbon. I have developed one gadget and successfully integrated as well but gadget-util.js file showing an error of
Uncaught TypeError: Cannot read property 'getTenantDomain' of undefined
at getGadgetLocation
my code is gadget-util.js
var getGadgetLocation = function (callback) {
var gadgetLocation = "/portal/store/carbon.super/fs/gadget/circle_d3";
var PATH_SEPERATOR = "/";
if (gadgetLocation.search("store") != -1)
{
wso2.gadgets.identity.getTenantDomain(function (tenantDomain) {
var gadgetPath = gadgetLocation.split(PATH_SEPERATOR);
var modifiedPath = '';
for (var i = 1; i < gadgetPath.length; i++) {
if (i === 3) {
modifiedPath = modifiedPath.concat(PATH_SEPERATOR, tenantDomain);
} else {
modifiedPath = modifiedPath.concat(PATH_SEPERATOR, gadgetPath[i])
}
}
callback(modifiedPath);
});
} else {
callback(gadgetLocation)
}
callback(gadgetLocation);
}
please help me
You need to require identity feature[1] in gadget.xml
<Require feature="wso2-gadgets-identity" />
e.g https://github.com/wso2/product-das/blob/master/modules/distribution/src/repository/conf/template-manager/gadget-templates/numberchart/gadget.xml#L5
[1] http://mail.wso2.org/mailarchive/dev/2016-August/066568.html
I'm currently working on Xamarin and I'm confused with the facebook sharing option in xamarin forms particularly in Xamarin Android the IOS code is
public void ShareOnFacebook(IFacebookDelegate pDele)
{
string[] perm = {"publish_actions"};
if (AccessToken.CurrentAccessToken == null || !AccessToken.CurrentAccessToken.HasGranted("publish_actions"))
{
UIViewController mainController = UIApplication.SharedApplication.KeyWindow.RootViewController;
_manager.LogInWithPublishPermissions(perm, mainController, (result, error) =>
{
if (error != null || result.IsCancelled)
{
}
else {
ShareNow();
}
});
} else {
ShareNow();
}
}
The only thing which stops me is Xamarin Android facebook post sharing.
Can anyone modify this code according to Xamarin Android Or share his/her own code .
I have implemented share for twitter and fb .
iOS version
you can share using native social services from ios and if not available use
OAuth2Authenticator to get access token then post using FB graph
public void ShareViaSocial(string serviceType, string urlToShare)
{
socialKind = serviceType == "Twitter" ? SLServiceKind.Twitter : SLServiceKind.Facebook;
if (SLComposeViewController.IsAvailable(socialKind))
{
_socialComposer = serviceType == "Twitter" ? SLComposeViewController.FromService(SLServiceType.Twitter) : SLComposeViewController.FromService(SLServiceType.Facebook);
_socialComposer.AddUrl(new Uri(urlToShare));
viewController.PresentViewController(_socialComposer, true, () =>
{
_socialComposer.CompletionHandler += (result) =>
{
Device.BeginInvokeOnMainThread(() =>
{
viewController.DismissViewController(true, null);
if (result == SLComposeViewControllerResult.Done)
{ OnShare(this, ShareStatus.Successful); }
else
{ OnShare(this, ShareStatus.NotSuccessful); }
});
};
});
}
//If user doest have fb app and no credential for social services we use fb graph
else if (socialKind == SLServiceKind.Facebook)
{
var auth = new OAuth2Authenticator(
clientId: SharedConstants.FacebookLiveClientId,
scope: SharedConstants.FacebookScopes,
authorizeUrl: new Uri(SharedConstants.FacebookAuthorizeUrl),
redirectUrl: new Uri(SharedConstants.FacebookRedirectUrl));
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
auth.AllowCancel = true;
auth.Completed += (s, e) =>
{
//hide the webpage after completed login
viewController.DismissViewController(true, null);
// We presented the UI, so it's up to us to dimiss it on iOS.
if (e.IsAuthenticated)
{
Account fbAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
var requestUrl = new Uri("https://graph.facebook.com/me/feed");
var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
}
//If user doest have twitter app and no credential for social services we use xanarub auth for token and call twitter api for sending tweets
else
{
var auth = new OAuth1Authenticator(
SharedConstants.TwitterConsumerKey,
SharedConstants.TwitterConsumerSecret,
new Uri(SharedConstants.TwitterRequestUrl),
new Uri(SharedConstants.TwitterAuth),
new Uri(SharedConstants.TwitterAccessToken),
new Uri(SharedConstants.TwitterCallBackUrl));
auth.AllowCancel = true;
// auth.ShowUIErrors = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, e) =>
{
// We presented the UI, so it's up to us to dismiss it.
viewController.DismissViewController(true, null);
if (e.IsAuthenticated)
{
Account twitterAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
//for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
//auth.IsUsingNativeUI = true;
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
}
}
Android version
You can use native facebook ShareDialog and if isn't available use OAuth2Authenticator to get access token then post using FB graph
and using OAuth1Authenticator for posing on twitter
public void ShareViaSocial(string serviceType, string urlToShare)
{
ShareDialog di = new ShareDialog(MainActivity.Instance);
var facebookShareContent = new ShareLinkContent.Builder();
facebookShareContent.SetContentUrl(Android.Net.Uri.Parse(urlToShare));
if (serviceType == "Facebook")
{
if (di.CanShow(facebookShareContent.Build(), ShareDialog.Mode.Automatic))
{
di.Show(facebookShareContent.Build());
}
else
{
var auth = new OAuth2Authenticator(
clientId: 'ClientId',
scope: "public_profile,publish_actions",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri( "http://www.facebook.com/connect/login_success.html"));
MainActivity.Instance.StartActivity(auth.GetUI(MainActivity.Instance.ApplicationContext));
auth.AllowCancel = true;
auth.Completed += (s, e) =>
{
if (e.IsAuthenticated)
{
Account fbAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
var requestUrl = new Uri("https://graph.facebook.com/me/feed");
var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
}
}
else
{
var auth = new OAuth1Authenticator(
'TwitterConsumerKey',
'TwitterConsumerSecret',
new Uri("https://api.twitter.com/oauth/request_token"),
new Uri("https://api.twitter.com/oauth/authorize"),
new Uri("https://api.twitter.com/oauth/access_token"),
new Uri('TwitterCallBackUrl'));
auth.AllowCancel = true;
// auth.ShowUIErrors = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, e) =>
{
// We presented the UI, so it's up to us to dismiss it.
if (e.IsAuthenticated)
{
Account twitterAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
//for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
//auth.IsUsingNativeUI = true;
MainActivity.Instance.StartActivity(auth.GetUI(MainActivity.Instance.ApplicationContext));
}
}
I can't seem to fetch new data in Internet Explorer 9. For the purpose of an example I test the store this way:
App.__container__.lookup('store:main').find('style')
The only error I receive is the following:
SCRIPT5022: Error: Assertion Failed: [object Object]
Does Ember-data works out of the box (without polyfills, ...) in Internet Explorer 9?
versions:
Ember: 1.9.1
Ember-data: 1.0.0-beta.12
Problem solved. When doing an AJAX request with jQuery, this normally happens through the XMLHttpRequest object.
On IE8-9, this object is not present, instead it uses XDomainRequest. The simplest fix for this is adding: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest.
ember-data works out of the box with IE8+. According to this issue:
We've been supporting IE8 with our platform (built on Ember) for a
while now. Things I know:
shim/sham is not needed, it's polyfilled by Ember and Ember-Data.
You will need it if you want additional things like .bind() on a function, then you must prepend it to the vendor file (using Brocfile)
and we only include the shim for that purpose, not the sham
Solution Synthesis
Reason :
On IE8-9, this object is not present, instead it uses XDomainRequest.
Solution :
The issue is solved. When using an AJAX request with jQuery. Normally this is done through the XMLHttpRequest object. A simple fix would be using the Open-Source jQuery-ajaxTransport-XDomainRequest
Code : Adding :
jQuery-ajaxTransport-XDomainRequest.js
/*!
* jQuery-ajaxTransport-XDomainRequest - v1.0.4 - 2015-03-05
* https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
* Copyright (c) 2015 Jason Moon (#JSONMOON)
* Licensed MIT (/blob/master/LICENSE.txt)
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals.
factory(jQuery);
}
}(function($) {
// Only continue if we're on IE8/IE9 with jQuery 1.5+ (contains the ajaxTransport function)
if ($.support.cors || !$.ajaxTransport || !window.XDomainRequest) {
return $;
}
var httpRegEx = /^(https?:)?\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^(\/\/|' + location.protocol + ')', 'i');
// ajaxTransport exists in jQuery 1.5+
$.ajaxTransport('* text html xml json', function(options, userOptions, jqXHR) {
// Only continue if the request is: asynchronous, uses GET or POST method, has HTTP or HTTPS protocol, and has the same scheme as the calling page
if (!options.crossDomain || !options.async || !getOrPostRegEx.test(options.type) || !httpRegEx.test(options.url) || !sameSchemeRegEx.test(options.url)) {
return;
}
var xdr = null;
return {
send: function(headers, complete) {
var postData = '';
var userType = (userOptions.dataType || '').toLowerCase();
xdr = new XDomainRequest();
if (/^\d+$/.test(userOptions.timeout)) {
xdr.timeout = userOptions.timeout;
}
xdr.ontimeout = function() {
complete(500, 'timeout');
};
xdr.onload = function() {
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: 200,
message: 'success'
};
var responses = {
text: xdr.responseText
};
try {
if (userType === 'html' || /text\/html/i.test(xdr.contentType)) {
responses.html = xdr.responseText;
} else if (userType === 'json' || (userType !== 'text' && /\/json/i.test(xdr.contentType))) {
try {
responses.json = $.parseJSON(xdr.responseText);
} catch(e) {
status.code = 500;
status.message = 'parseerror';
//throw 'Invalid JSON: ' + xdr.responseText;
}
} else if (userType === 'xml' || (userType !== 'text' && /\/xml/i.test(xdr.contentType))) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
try {
doc.loadXML(xdr.responseText);
} catch(e) {
doc = undefined;
}
if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
status.code = 500;
status.message = 'parseerror';
throw 'Invalid XML: ' + xdr.responseText;
}
responses.xml = doc;
}
} catch(parseMessage) {
throw parseMessage;
} finally {
complete(status.code, status.message, responses, allResponseHeaders);
}
};
// set an empty handler for 'onprogress' so requests don't get aborted
xdr.onprogress = function(){};
xdr.onerror = function() {
complete(500, 'error', {
text: xdr.responseText
});
};
if (userOptions.data) {
postData = ($.type(userOptions.data) === 'string') ? userOptions.data : $.param(userOptions.data);
}
xdr.open(options.type, options.url);
xdr.send(postData);
},
abort: function() {
if (xdr) {
xdr.abort();
}
}
};
});
return $;
}));
I am developing my first Dashboard Widget and trying to call a webservice. But I keep on getting XMLHTTPRequest status 0.
Following is the code
var soapHeader = '<?xml version=\"1.0\" encoding=\"utf-8\"?>\n'
+'<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n'
+'<soap:Body>\n'
+'<UsersOnline xmlns=\"http://wsSync\" />\n'
+'</soap:Body>\n'
+'</soap:Envelope>';
var destinationURI = 'http://ws.storan.com/webservicesformraiphone/wssync.asmx';
var actionURI = 'http://wsSync/UsersOnline';
function callWebService() {
try{
SOAPObject = new XMLHttpRequest();
SOAPObject.onreadystatechange = function() {fetchEnd(SOAPObject);}
SOAPObject.open('POST', destinationURI, true);
SOAPObject.setRequestHeader('SOAPAction', actionURI);
SOAPObject.setRequestHeader('Content-Length', soapHeader.length);
SOAPObject.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
var requestBody = soapHeader;
SOAPObject.send(requestBody);
} catch (E)
{
alert('callWebService exception: ' + E);
}
}
function fetchEnd(obj)
{
if(obj.readyState == 4){
if(obj.status==200)
{
alert("Yahooooooo");
}
}
}
Any ideas?
have you added
<key>AllowNetworkAccess</key>
<true/>
to the plist? if not the outside world will not be available.
You may also encounter problems if trying to cross domains.