Sencha touch XML response to JSON - xml-parsing

I have recently started a project in Sencha touch with existing Web-services.
Being very new to the technology, I am facing certain issues in accomplishing some functionality.
Problem
I have to call login service and the request goes like:
http://domain.sub.com/Service.asmx/LoginService?body={"Username":"maj#smaj.com","Password":"p12345","Token":122112321123212123,"Method":"Login","LabId":"(null)","Hash":"fr3f33f3334348u8yy8hfuhdu8bdy7y89u89x8998c89789c87d78r9","DeviceType":"iPhone Simulator","DeviceId":"91BF3299-A94C-5AD3-9C35-A5C9BBBB6AA8","ApplicationType":"iPhone","Id":"998390494"}
but the response is coming in XML format as:
RESPONSE:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://domain2.sub2.com/MobileWebService/">{"Id":"null","Message":"Logged In.","Status":true,"LoggedIn":true}</string>
I have to parse this xml to json to get : {"Id":"null","Message":"Logged In.","Status":true,"LoggedIn":true} out of the response.
then use the Status, LoggedIn and Id to verify the login.
My Idea
I am not sure whether its right, I am trying to create two stores, xmlStore and JsonStore.
??
How will I store the xml response inside a string.
How Will I pass this string to Json Store (at the place of url?)
I may sound very naive to this, but this is my problem ;)
Please guide.
EDIT:
I realized tha I am diving cross domain request.
is that what is causing problems or confusion. How to deal with it suppose I did not had cross domain requests?

If you are doing cross domain requests use scripttag in your proxy in place of ajax. Here is a json example
ex.
mApp.stores.onlineStore = new Ext.data.Store({
model: 'XPosts',
proxy: {
type: 'scripttag',
url : 'http://domain.com/data.json',
reader: new Ext.data.JsonReader({
root: 'pages'
}),
timeout: 3000,
listeners: {
exception:function () {
console.log("onlineStore: failed");
},
success: function(){
console.log("onlineStore: success");
}
}
},
autoLoad: true
});
Offline store:
mApp.stores.offlineStore = new Ext.data.Store({
model: 'XPosts',
proxy: {
type: 'localstorage',
id: 'appdata',
reader: new Ext.data.JsonReader({
root: 'pages'
})
},
autoLoad: true
});
Then, in your launch :
this.stores.onlineStore.addListener('load', function () {
console.log("onlineStore: online");
mApp.stores.offlineStore.proxy.clear();
console.log("offlineStore: cleared");
this.each(function (record) {
console.log("offlineStore: adding record");
mApp.stores.offlineStore.add(record.data)[0];
});
mApp.stores.offlineStore.sync();
console.log("offlineStore: synced");
mApp.stores.offlineStore.load();
});
this.stores.onlineStore.load();
May have some bugs so beforewarned!

Related

IBM DataPower - How to handle HTML Response from openurl?

I tried looking for the solution in the forum but I was unable to find something similar to what I'm trying to achieve. I have a gateway script in an MPG which kinda looks like this:
session.INPUT.readAsJSON(function (error, json) {
if (error){
throw error;
} else {
var SAMLResponse = json['SAMLResponse'];
var RelayState = json['RelayState'];
var urlopen = require('urlopen');
var options = {
target: 'https://************.com/e32d32der2tj90g8h4',
method: 'POST',
headers: { 'HEADER_NAME' : 'VALUE'},
contentType: 'application/json',
timeout: 60,
sslClientProfile: 'ClientProfile',
data: {"SAMLResponse": SAMLResponse, "RelayState": RelayState}
};
urlopen.open(options, function(error, response) {
if (error) {
session.output.write("urlopen error: "+JSON.stringify(error));
} else {
var responseStatusCode = response.statusCode;
var responseReasonPhrase = response.reasonPhrase;
response.readAsBuffer(function(error, responseData){
if (error){
throw error;
} else {
session.output.write(responseData);
console.log(responseData);
}
});
}
});
}
});
I'm doing a POST request and the response I get from the urlopen function is an HTML page, how to I display the contents of that page in my browser? I need that to initiate a process flow. am I going in the wrong direction here? what's the best way to POST to a URI and display it's response in DataPower?
with regards to my experience with DataPower, I just started learning, So I might not be familiar with many of the concepts.
Thanks in Advance!
session.INPUT.readAsJSON() would indicate that you are receiving JSON data as the input (from the POST).
Since you are building this in a Multi-Protocol Gateway (MPGW) you need to set the Response type to non-xml if the response is HTML and if there is no backend call being made (other than the url-open()) you also must set the skip-backside=1 variable.
Is the scenario as:
JSON HTTP Request -> [MPGW] -> url-open() -> Backend server --|
HTTP Response <-----------------------------------------|
Or:
JSON HTTP Request -> [MPGW] -> url-open() --| (skip-backside)
HTTP Response <------------------------|
If there is no backend call I would recommend building this in a XML Firewall (XMLFW) service instead and set it to "loopback" and non-xml.
If there is a backend and that is where you are sending your HTML from the url-open() then only MPGW Response type needs to be set to non-xml.
If it is the second option the you can just set the payload and headers in GWS and just call the target (https://************.com/e32d32der2tj90g8h4) as teh MPGW backside connection, no need for the url-open().

Service worker for web traffic analysis

I have developed an application to analyse the network traffic while playing a youtube video. It uses chrome.webRequest and I calculate the traffic using onHeadersReceived event.
I want to do the same using service workers so that the application becomes browser independent. I fetch event of service worker, but it does not work.
Any suggestions how I can proceed?
Well, the broad idea is to listen to the fetch event, extract the information you need and allow the request to reach the network. You have a working demo in the Service Worker Cookbook: https://serviceworke.rs/api-analytics.html but the relevant code is here (in the cookbook you have the annotated source as well):
self.onfetch = function(event) {
event.respondWith(
// Log the request…
log(event.request)
// …and then actually perform it.
.then(fetch)
);
};
// Post basic information of the request to a backend for historical purposes.
function log(request) {
var returnRequest = function() {
return request;
};
var data = {
method: request.method,
url: request.url
};
return fetch(LOG_ENDPOINT, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'content-type': 'application/json' }
})
.then(returnRequest, returnRequest);
}

cannot get extjs grid to populate with proxy data call

I have gone from incorporating extjs in my original asp.net application which worked when hardcoding any data stores and binding them to the charts/grids. When I tried proxy url calls or even fetching the data from code behind and wrapping in json I still do not get the data into the grid. So I gave up and went with extjs and nodejs and still using mongodb; this worked perfectly but I still have to learn to create a better UI using express/jade etc which is a different project now. But then I came across using MVC with extjs and with a sample project tried the same thing (the sample had hardcoded data) and I cannot for the life of me get it to display the data.
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.state.*'
]);
Ext.onReady(function () {
Ext.QuickTips.init();
// setup the state provider, all state information will be saved to a cookie
Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [
{ name: 'username', type: 'string' }
]
});
Ext.define('UserStore', {
extend: 'Ext.data.Store',
model: 'User',
autoload: true,
proxy: {
type: 'ajax',
url: '/dashboard.aspx/getDBData',
reader: {
type: 'json',
root: 'users'
},
listeners:
{
exception: function (proxy, response, operation) {
Ext.MessageBox.show(
{
title: 'REMOTE EXCEPTION',
msg: operation.getError(), icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
});
}
}
}
});
var myStore = Ext.getStore('UserStore');
the url I am including here is the codebehind function that I initially tried which accesses the mongodb and returns json result. Not working.
Now from the extjs node.js application I have results coming into localhost:3000/userlist which returns a list from mongodb and displays it as follows:
extends layout
block content
h1.
User List
u1
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
Now would it be possible to use the same server and call the base url and then change the route.js file to return the mongodb json result or call the mongodb localhost:27017 and get a result. Really confused here
exports.index = function(db) {
return function(req, res) {
var collection = db.get('usercollection');
collection.find({},{}, function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
};
};
EDIT:
First thing I realized from asp.net perspective was that I was not calling a webservice just a codebehind method. Any comments will still be appreciated.
EDIT 2:
{"connTime":null,"userName":"101591196589145","clientName":null,
"feedUrl":null,"dconnTime":null,"errMessage":null,"ip":null}
You have identified a root in your store as 'users'
reader: {
type: 'json',
root: 'users'
},
But there is no root in your returned json such as:
{"users":[{"connTime":null,"userName":"101591196589145","clientName":null,
"feedUrl":null,"dconnTime":null,"errMessage":null,"ip":null}]}

Esri API 10.2 - Error code: 400 "Unable to complete operation"

I am developing an iOS Application for collecting data following "FeatureLayerEditingSample"(you can find it here: FeatureLayerEditingSample).
I use Esri's iOS sdk version 10.2
This error occurs random sampling when I try to add a new feature (simple or with attachments) to my feature layer.
Moreover sometimes only one or two specific attachments cannot be sync and the error says "because unable to complete operation".
Any ideas?
When using REST API to add new feature, please make sure you do your request using POST and make sure you have included f and features parameters in the POST body.
Below is an example of the POST request in JavaScript(AngularJS) - it can be easily transferred to any other language:
$scope.addFeature= function(){
var url = "http://services6.arcgis.com/dD0xfCNJ6qLYAvCQ/arcgis/rest/services/US_Election_2016/FeatureServer/0/addFeatures";
var newFeature = {
"geometry" : {"x" : -122.504002, "y" : 45.448060},
"attributes" : {
"CandidateName" : "Hillary Clinton"
},
"spatialReference" : {
"wkid" : "4326"
}
};
var features = [];
features.push(newFeature);
var featuresString = JSON.stringify(features);
data = "f=json&features="+featuresString;
var config={
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}};
$http.post(url, data, config)
.then(
function(response){
console.log(response);
},
function(response){
console.log(response);
}
);
}
The problem was I was using a versioned database. Removing the version all worked again.

Timeout issue for long requests on ajax POST

so I have a .NET MVC project with an Update controller called from an Ajax POST that can take a long time to run which causes a timeout exception.
When I debug it on my local machine it runs fine, however - when I publish it to my azure website and update it from there the request never successfully completes and Chrome's console reports:
POST http://mysiteaddress/Admin/UpdateLibrary/Update?Length=13 504 (Proxy Timeout ( This operation returned because the timeout period expired. ))
Attempting the same operation on a remote desktop within Firefox causes the console to report:
[07:42:13.856] POST http://mysiteaddress/Admin/UpdateLibrary/Update?Length=13 **[HTTP/1.1 502 Bad Gateway 182940ms]**
I've tried setting a long timeout within my web.config file
<httpRuntime executionTimeout="2000"/>
and within the body of my ajax call
$.ajax({
url: this.action,
type: 'POST',
data: $(this).serialize(),
success: function (data) {
document.write(data);
},
failure: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
},
timeout: 2000000 //Milliseconds
});
But no joy.
So this is not really a fix, but a workaround. Instead of making a single long request I had my javascript repeatedly query an ActionResult that returned some json deciding whether my long running process had finished. When it had completed I redirect the browser to a results screen.
$.updateProgressbar = function () {
$.get('#Url.Action("GetStatus", "UpdateLibrary", new { countryId = countryId }, Request.Url.Scheme)', function (data) {
$('#progressbar').progressbar('value', data.progress)
if (data.currentItem != null) {
$('#currentWorkItem').text('#l12.View_Update_currentlyWorking' + data.currentItem);
}
if (data.progress == 100) {
window.location =
'#Url.Action("UpdateResults", "UpdateLibrary", new { countryId = countryId }, Request.Url.Scheme)';
} else {
setTimeout($.updateProgressbar, 5000);
}
});
};
$(function () {
$("#progressbar").progressbar({ value: 0 });
setTimeout($.updateProgressbar, 5000);
});
It looks like on your local network to external azure site, you are going out through a proxy/gateway server. Does your company have any block-lists or white-lists for allowed/disallowed websites that might be intercepting and blocking the request?

Resources