How can I resend a post/get data in case of failure? - firefox-addon

I tried to use addProgressListener but I don't know how to get post data in onStateChange and send it back.
exports.main = function() {
var {Cc, Ci, Cu} = require("chrome");
var windows = require("sdk/windows").browserWindows;
const windowUtils = require("sdk/window/utils");
var {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var { setTimeout, clearTimeout } = require("sdk/timers");
var gBrowser = windowUtils.getMostRecentBrowserWindow().getBrowser();
var tabs = require("sdk/tabs");
const STATE_START = Ci.nsIWebProgressListener.STATE_START;
const STATE_STOP = Ci.nsIWebProgressListener.STATE_STOP;
const STATE_REDIRECTING = Ci.nsIWebProgressListener.STATE_REDIRECTING;
const STATE_TRANSFERRING = Ci.nsIWebProgressListener.STATE_TRANSFERRING;
const STATE_RESTORING = Ci.nsIWebProgressListener.STATE_RESTORING;
var timer = null;
var counter = 0;
var start_url = '';
var retry = false;
var myListener = {
QueryInterface: XPCOMUtils.generateQI(Ci),
onState: function(aWebProgress, aRequest, aFlag, aStatus) {
console.log('test');
},
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {
Ci.nsIUploadChannel2
if(!aRequest.name.startsWith('http')) {
return false;
}
if (!(start_url && (start_url == aRequest.name))) {
if (!aWebProgress.isLoadingDocument && !retry) {
return false;
}
}
retry = false;
if (aFlag & STATE_START) {
if (timer) {
clearTimeout(timer);
timer = null
start_url = '';
counter = 0
}
console.log("start");
start_url = aRequest.name;
timer = setTimeout(function() {
if (counter < 5) {
// console.log("after start");
console.log("aRequest.name: ", aRequest.name);
new_tab = gBrowser.addTab(aRequest.name);
gBrowser.removeCurrentTab();
gBrowser.selectedTab = new_tab;
retry = true;
counter += 1
myListener['onStateChange'](aWebProgress, aRequest,
aFlag, aStatus);
} else {
gBrowser.removeCurrentTab();
}
}, 10000)
}
if (aFlag & STATE_STOP) {
if (timer) {
console.log("stop");
clearTimeout(timer);
timer = null
start_url = '';
counter = 0
}
}
},
onLocationChange: function(aProgress, aRequest, aURI) {
start_url = aRequest.name;
console.log('onLocationChange: ', aRequest.name)
},
onProgressChange: function(aWebProgress, aRequest, curSelf,
maxSelf, curTot, maxTot) {
console.log('onProgressChange: ', aRequest.name)
},
onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) {
console.log('onStatusChange: ', aRequest.name)
},
onSecurityChange: function(aWebProgress, aRequest, aState) {
console.log('onSecurityChange: ', aRequest.name)
}
}
gBrowser.addProgressListener(myListener);
}
I also tried to use observerService but none of those topics makes it possible to keep track of each request and make my plans.
observerService.addObserver(this, "http-on-opening-request", false);
observerService.addObserver(this, "http-on-examine-merged-response", false);
observerService.addObserver(this, "http-on-examine-cached-responsee", false);
observerService.addObserver(this, "http-on-examine-response", false);
I assume that the data request can be obtained using nsIUploadChannel but I do not understand how to use it.

Try this, untested, didnt even check for typos.
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {
if (aRequest instanceof Ci.nsIHttpChannel) {
if (aRequest.QueryInterface(Ci.nsIHttpChannel).uploadStream) {
// see line 10 - https://gist.github.com/Noitidart/28624e20bfee2dc128c4#file-gistfile1-txt-L10
}
}
if(!aRequest.name.startsWith('http')) {
return false;
}

Related

Alexa skill testing error: Error handled: Cannot read property 'value' of undefined

Please help me if any body resolved the issue and below is my lambda funciton code.
when i comment all funcitons in exports.handler funciton and execute/test single function it is working but if we enable all funcitons then i am getting the error as Error handled: Cannot read property 'value' of undefined
Node JS code for alexa skill kit for different intents created.
GetNewFactHandler,
CreateJIRAIssueHandler,
UpdateJIRAIssueHandler,
GetJIRAIssueHandler,
GetJIRAIssueCountHandler,
/* eslint-disable func-names */
/* eslint-disable no-console */
var http = require('http');
var https = require('https');
var projectKey='';
var iType='';
var keyValueID='';
var userName='';
var IssueNumber='';
const Alexa = require('ask-sdk');
const GetNewFactHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest'
|| (request.type === 'IntentRequest'
&& request.intent.name === 'GetNewFactIntent');
},
handle(handlerInput) {
const factArr = data;
const factIndex = Math.floor(Math.random() * factArr.length);
const randomFact = factArr[factIndex];
const speechOutput = GET_FACT_MESSAGE + randomFact;
return handlerInput.responseBuilder
.speak(speechOutput)
.withSimpleCard(SKILL_NAME, randomFact)
.getResponse();
},
};
var reqTimeout = 3000;
const CreateJIRAIssueHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const proKey = request.intent.slots.PROJECTKEY.value;
const issueType = request.intent.slots.ISSUETYPE.value;
iType = capitalize_Words(issueType);
projectKey = proKey.toUpperCase();
return request.type === 'IntentRequest' &&
request.intent.name === 'CreateJIRAIssue';
},
async handle(handlerInput) {
const createIssue = await createJiraIssue(projectKey, iType);
const speechOutput = JSON.parse(createIssue).key;
return handlerInput.responseBuilder
.speak('Issue ' + speechOutput + ' created')
.getResponse();
},
};
function capitalize_Words(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
//mule real time server
var muleCreateIssuePath = '/jira/createissue';
var muleProtocol = 'https';
var createIssueMethod = 'POST';
var muleUpdateIssuePath = '/jira/issue/';
var updateIssueMethod = 'PUT';
var getIssueMethod = 'GET';
var MuleReqOpts = {
host: '',
port: 443,
path: undefined, // To be set.
method: undefined,
headers: {
'Content-Type': 'application/json'
},
agent: false,
// auth: jiraUsername + ':' + jiraPassword
auth: ''
};
var MuleHttp = muleProtocol === 'https' ? https : http;
function createJiraIssue(projectKey, iType) {
MuleReqOpts.path = muleCreateIssuePath;
MuleReqOpts.method = createIssueMethod;
var MuleReqBody = {
'fields': {
'project': {
'key': projectKey
},
'summary': 'Test Message',
'description': 'Issue created for alexa skill kit from Integration alexa to jira',
'issuetype': {
'name': iType // Make sure your JIRA project configuration(s) supports this Issue Type.
}
}
};
return doApiCall(MuleHttp, MuleReqOpts, MuleReqBody, 'creating issue', 201);
};
function doApiCall(httplib, reqOpts, reqBody, happening, successCode) {
return new Promise(((resolve, reject) => {
var req = httplib.request(reqOpts, (res) => {
res.setEncoding('utf8');
let returnData = '';
res.on('data', (chunk) => {
returnData += chunk;
});
res.on('end', () => {
resolve(returnData);
});
res.on('error', (error) => {
reject(error);
});
});
req.write(JSON.stringify(reqBody));
req.end();
req.on('error', function(err) {
context.done(new Error(' request error: ' + err.message));
});
req.setTimeout(reqTimeout, function() {
context.done(new Error(' request timeout after ' + reqTimeout + ' milliseconds.'));
});
}));
};
const UpdateJIRAIssueHandler = {
canHandle(handlerInput) {
console.log('1');
const request = handlerInput.requestEnvelope.request;
console.log('2');
userName = request.intent.slots.USER.value;
var keyValue = request.intent.slots.PROJECTKEY.value;
console.log('keyValue : ' + keyValue);
keyValueID = keyValue.toUpperCase();
IssueNumber = request.intent.slots.ISSUENUMBER.value;
let INumber = Number(IssueNumber);
console.log('IssueNumber value: '+INumber);
console.log('key value id: ' + keyValueID);
return request.type === 'IntentRequest' &&
request.intent.name === 'UpdateJIRAIssue';
},
async handle(handlerInput) {
const updateIssue = await updateJiraIssue(userName);
console.log('updateIssue log: ' + updateIssue);
const speechOutput = JSON.parse(updateIssue).responseMessage;
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function updateJiraIssue(userName) {
console.log('inside method: ' +userName);
MuleReqOpts.method = updateIssueMethod;
var postdata = {
"fields": {
"assignee": {
"name": userName
}
}
}
return doApiUpdateCall(MuleHttp, MuleReqOpts, postdata, 'updating issue', 201);
};
function doApiUpdateCall(httplib, options, postdata, happening, successCode) {
options.path = muleUpdateIssuePath + keyValueID +'-'+IssueNumber ;
return new Promise(((resolve, reject) => {
var req = httplib.request(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log(returnData);
});
res.on('end', () => {
resolve(returnData);
});
console.log('1');
console.log('Body: ');
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
var jirapostString = JSON.stringify(postdata);
console.log(jirapostString);
req.write(jirapostString);
req.end();
}));
};
const GetJIRAIssueHandler = {
canHandle(handlerInput) {
console.log('1');
const request = handlerInput.requestEnvelope.request;
var keyValue = request.intent.slots.Issue.value;
console.log('keyValue: ' + keyValue);
keyValueID = keyValue.toUpperCase();
return request.type === 'IntentRequest' &&
request.intent.name === 'GetJIRAIssue';
},
async handle(handlerInput) {
const getIssue = await GetJIRAIssue();
console.log('getIssue log: ' + getIssue);
const assigneeName = JSON.parse(getIssue).fields.assignee.name;
const key = JSON.parse(getIssue).fields.assignee.key;
const reporterName = JSON.parse(getIssue).fields.reporter.name;
const issueType = JSON.parse(getIssue).fields.issuetype.name;
const projectName = JSON.parse(getIssue).fields.project.name;
const summaryDetails = JSON.parse(getIssue).fields.summary;
const speechOutput = 'Here are the issue details summary: Assignee : ' + assigneeName.concat(' ,reporter : ' + reporterName, ' ,Issue Key : ' + key, ' ,IssueType : ' + issueType, ' ,ProjectName : ' + projectName, ' ,Summary : ' + summaryDetails);
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function GetJIRAIssue() {
MuleReqOpts.method = getIssueMethod;
return doApiGetIssueCall(MuleHttp, MuleReqOpts, 'get issue details', 201);
};
function doApiGetIssueCall(httplib, options, happening, successCode) {
options.path = muleUpdateIssuePath + keyValueID;
return new Promise(((resolve, reject) => {
https.get(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log('response :', returnData);
});
res.on('end', () => {
resolve(returnData);
});
});
}));
};
const GetJIRAIssueCountHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
userName = request.intent.slots.USER.value;
console.log('userName Value: ' + userName);
const issueType = request.intent.slots.ISSUETYPE.value;
iType = capitalize_Words(issueType);
return request.type === 'IntentRequest' &&
request.intent.name === 'GetJIRAIssueCount';
},
async handle(handlerInput) {
const getIssueCount = await GetJIRAIssueCount();
console.log('getIssue log: ' + getIssueCount);
const total = JSON.parse(getIssueCount).total;
const speechOutput = ('Here is the '+iType+' count details: ' +total );
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function GetJIRAIssueCount() {
MuleReqOpts.method = getIssueMethod;
return doApiGetIssueCountCall(MuleHttp, MuleReqOpts, 'get issue count details', 201);
};
function doApiGetIssueCountCall(httplib, options, happening, successCode) {
options.path = muleUpdateIssuePath + userName +'/'+iType;
return new Promise(((resolve, reject) => {
https.get(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log('response :', returnData);
});
res.on('end', () => {
resolve(returnData);
});
});
}));
};
const HelpHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& request.intent.name === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(HELP_MESSAGE)
.reprompt(HELP_REPROMPT)
.getResponse();
},
};
const ExitHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& (request.intent.name === 'AMAZON.CancelIntent'
|| request.intent.name === 'AMAZON.StopIntent');
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(STOP_MESSAGE)
.getResponse();
},
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`Error handled: ${error.message}`);
return handlerInput.responseBuilder
.speak('Sorry, an error occurred.')
.reprompt('Sorry, an error occurred.')
.getResponse();
},
};
const SKILL_NAME = 'Space Facts';
const GET_FACT_MESSAGE = 'Here\'s your fact: ';
const HELP_MESSAGE = 'You can say tell me a space fact, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
const data = [
'A year on Mercury is just 88 days long.',
'Despite being farther from the Sun, Venus experiences higher temperatures than Mercury.',
'Venus rotates counter-clockwise, possibly because of a collision in the past with an asteroid.',
'On Mars, the Sun appears about half the size as it does on Earth.',
'Earth is the only planet not named after a god.',
'Jupiter has the shortest day of all the planets.',
'The Milky Way galaxy will collide with the Andromeda Galaxy in about 5 billion years.',
'The Sun contains 99.86% of the mass in the Solar System.',
'The Sun is an almost perfect sphere.',
'A total solar eclipse can happen once every 1 to 2 years. This makes them a rare event.',
'Saturn radiates two and a half times more energy into space than it receives from the sun.',
'The temperature inside the Sun can reach 15 million degrees Celsius.',
'The Moon is moving approximately 3.8 cm away from our planet every year.',
];
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
GetNewFactHandler,
CreateJIRAIssueHandler,
UpdateJIRAIssueHandler,
GetJIRAIssueHandler,
GetJIRAIssueCountHandler,
HelpHandler,
ExitHandler,
SessionEndedRequestHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();
Check all of your code for instances where you are looking for someObject.someNestedProperty.value.
I suspect that your slot values in your Intents are not the same as defined in your model/some-LANG.json file. Trying to access value property from someObject without a someNestedProperty will cause your error (i.e. request.intent.slots.PROJECTKEY.value).
If this is a Alexa-hosted skill, CloudWatch logging is built right in. Open the Alexa Developer Console, edit your skill, then go to the Code tab. On the bottom left, you should see a link for Logs: Amazon CloudWatch. You can log anything you want with a simple console.log() statement.
Also, be aware that the ask-sdk-core npm package contains helper methods to get slotValues (among other great tools). For more information, see this link: https://developer.amazon.com/en-US/docs/alexa/alexa-skills-kit-sdk-for-nodejs/utilities.html
Thanks all for your suggestions and prompt response.
Now the issue is resolved and the solution is the addRequestHandlers method will execute methods sequentially even if you execute/trigger third handler it will execute 1st and 2nd and goes to 3rd one. Here the issue is when you trigger a 3rd handler command from alexa it will passs the slot values related to the 3rd handler utterance and hence the 1st and 2nd haldler having slot values are not able to resolve and failed. so i put a condition overthere to skip 1st and 2nd handler execution and it worked.

Camera doesn't work after compilation

I use Ionic Framework.
Camera works perfectly in Ionic View. But it doesn't work after compilitaion on iOS.
Please, help to find out what is the problem.
Camera code in services.js:
app.factory('FileService', function() {
var images;
var IMAGE_STORAGE_KEY = 'dav-images';
function getImages() {
var img = window.localStorage.getItem(IMAGE_STORAGE_KEY);
if (img) {
images = JSON.parse(img);
} else {
images = [];
}
return images;
};
function addImage(img) {
images.push(img);
window.localStorage.setItem(IMAGE_STORAGE_KEY, JSON.stringify(images));
};
return {
storeImage: addImage,
images: getImages
}
});
app.factory('ImageService', function($cordovaCamera, FileService, $q, $cordovaFile) {
function optionsForType(type) {
var source;
switch (type) {
case 0:
source = Camera.PictureSourceType.CAMERA;
break;
case 1:
source = Camera.PictureSourceType.PHOTOLIBRARY;
break;
}
return {
quality: 90,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: source,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
}
function saveMedia(type) {
return $q(function(resolve, reject) {
var options = optionsForType(type);
$cordovaCamera.getPicture(options).then(function(imageBase64) {
FileService.storeImage(imageBase64);
});
})
}
return {
handleMediaDialog: saveMedia
}
});
Camera code in controllers.js:
app.controller('CameraController', function($scope, $cordovaDevice, $cordovaFile, $ionicPlatform, $cordovaEmailComposer, $ionicActionSheet, ImageService, FileService) {
$ionicPlatform.ready(function() {
$scope.images = FileService.images();
$scope.$apply();
});
$scope.addMedia = function() {
$scope.hideSheet = $ionicActionSheet.show({
buttons: [
{ text: 'Take photo' },
{ text: 'Photo from library' }
],
titleText: 'Add images',
cancelText: 'Cancel',
buttonClicked: function(index) {
$scope.addImage(index);
}
});
}
$scope.addImage = function(type) {
$scope.hideSheet();
ImageService.handleMediaDialog(type).then(function() {
$scope.$apply();
});
}
$scope.sendEmail = function() {
if ($scope.images != null && $scope.images.length > 0) {
var mailImages = [];
var savedImages = $scope.images;
for (var i = 0; i < savedImages.length; i++) {
mailImages.push('base64:attachment'+i+'.jpg//' + savedImages[i]);
}
$scope.openMailComposer(mailImages);
}
}
$scope.openMailComposer = function(attachments) {
var bodyText = '<html><h2>My Images</h2></html>';
var email = {
to: '',
attachments: attachments,
subject: 'Devdactic Images',
body: bodyText,
isHtml: true
};
$cordovaEmailComposer.open(email, function(){
console.log('email view dismissed');
}, this);
}
});
To resolve this problem you need to compile an app with XCode.
After XCode compilation camera works correctly.
Probably, the problem with camera was caused by Ionic compilation.

Kendo UI Treelist rows disappears after editing

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

IE 11 changing URL

I am getting strange behaviour in IE 11.
When I go to my web application using URL
"hostname:port/myapp-web/app/login.jsp"
The login page is displayed, And Login is done successfully.
Now. Problem is that, after logging in, App's landing page is index.html.
So URL should be "hostname:port/myapp-web/app/index.html"
Instead, IE changes it to "hostname:port///index.html"
Now, when I try to do any other operation or navigation, it fails because base URL is changed and my JS code cannot find app context root and all AJAX calls fails.
I tried searching over internet for the same, but couldn;t find any answer.
Please help if anyone has idea about such behaviour.
P.S. App is working fine in IE: 8/9, Chrome and FF.
I found something related to UTF-* character URLs but my app uses plain text URL with NO special characters.
App is developed using Spring for server side and KnockoutJS, HTML for UI.
Thanks in advance for the help.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=EDGE" />
<!-- script includes -->
</head>
<body>
<!-- NavigationBar -->
</body>
<script type="text/javascript">
app.initialize(); // app.js
$.getJSON('/myapp-web/Security/authorise', function (response) {
app.common.navbar.reRenderNavBar(response);
app.navigation = new Navigation("AdminHome"); // navigation.js
// This navigation causes IE11 to change URL to http://host:port///#AdminHome
// it should be // http://host:port/myapp-web/app/index.html#AdminHome
});
</script>
</html>
Navigation.js
var ua = window.navigator.userAgent
var msie = ua.indexOf("MSIE ")
var ieVer = -1;
if (msie > 0) {
var ieVer = ua.substring(msie + 5, ua.indexOf(".", msie));
//console.log(ieVer);
}
var NavigationInput = function (pName, pValue) {
this.paramName = pName;
this.paramValue = pValue;
this.toString = function () {
return pName + ":" + pValue;
}
}
var Navigation = function (startupView) {
var self = this;
this.navInput = [];
this.navViewModel = null;
this.navViewModelInitComplete = false;
// this.navigate = function navigate(view) {
//
// if (view !== this.currentView) {
// self.loadView(view, true, null);
// }
// }
this.navigateWithParams = function navigateWithParams(view, params) {
self.loadView(view, true, params);
}
this.goBack = function goBack() {
history.go(-1);
//history.back();
}
this.loadView = function (view, pushHistory, params) {
var contentframe = $("#content");
//app.consolePrintInfo("navigation", "previous view: " + self.currentView + " new view: " + view);
if (typeof (self.currentView) != 'undefined' && self.currentView
&& self.currentView.toLowerCase() == view.toLowerCase()
&& isParamsEqual(params)) {
return;
}
var constructedView;
constructedView = "Views/" + view + "/" + view + ".html"
contentframe.load(constructedView, function () {
self.currentView = view;
modUrl = view;
if (params != null) {
if (params instanceof String) {
modUrl = params;
}
else {
var queryStr = self.convertParamsToQueryString(params);
modUrl += "?" + queryStr;
}
// if (typeof(app.navigation.navViewModel) != 'undefined'
// && app.navigation.navViewModel
// && !app.navigation.navViewModelInitComplete)
// {
// app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(self.convertQueryStringToParams(modUrl));
// }
}
if (pushHistory) {
if (ieVer > 6) {
window.history.pushState(view, null, modUrl);
}
else {
window.history.pushState(view, null, "#" + modUrl);
}
}
app.consolePrintInfo("navigation", "modified url:" + modUrl + " view model: " + app.navigation.navViewModel);
var navInputs = self.convertQueryStringToParams(modUrl);
self.urlInputs = navInputs;
app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(navInputs);
//$.getScript("Views/" + view + ".js", function () {
//});
});
isParamsEqual = function (iParams) {
if ((typeof(self.urlInputs) == 'undefined' || !self.urlInputs)
&& (typeof(iParams) == 'undefined' || !iParams)) {
return true;
}
else if (app.utility.isObjectNull(self.urlInputs) && app.utility.isObjectNull(iParams)) {
return true;
}
else {
return false;
}
}
}
this.convertParamsToQueryString = function (params) {
var result = "";
for (var i = 0; i < params.length; i++) {
if (i > 0) {
result += "&";
}
result += params[i].paramName + "=" +
params[i].paramValue;
}
return result;
};
this.convertQueryStringToParams = function (modUrl) {
var inputs = null;
var fragments = modUrl.split("?");
if (fragments && fragments.length == 2) {
var f = fragments[1].split("&");
if (f && f.length > 0) {
for (var i = 0; i < f.length; i++) {
var inp = f[i].split("=");
if (inputs == null) inputs = [];
inputs.push(new NavigationInput(inp[0], inp[1]));
}
}
}
return inputs;
};
this.back = function () {
if (history.state) {
var view = self.getView();
self.loadView(view, false, self.convertQueryStringToParams(location.href));
} else {
var view = self.getView();
self.loadView(view, true, self.convertQueryStringToParams(location.href));
}
};
this.getView = function () {
var fragments = location.href.split('#');
if (fragments && fragments.length === 2) {
var inFrag = fragments[1].split('?');
if (inFrag && inFrag.length === 2) {
return inFrag[0];
}
else {
return fragments[1];
}
} else {
return startupView;
}
};
this.loadView(this.getView(), true, this.convertQueryStringToParams(location.href));
$(window).on('popstate', self.back);
}
app.js:
-----------------
app = {};
// utilities
app.utility = {};
app.ui = {};
// common
app.common = {};
// validation
app.validation = {};
// common components
app.common.navbar = {};
app.common.authorisation = {};
app.initialize = function () {
$.blockUI.defaults.message = '<h4><img src="images/busy.gif" /> Processing...</h4>';
$.blockUI.defaults.css.border = '2px solid #e3e3e3';
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
//$(document).click(function() { $(".popover").remove(); });
}
app.consolePrintInfo = function (tag, message) {
if (typeof(console) != 'undefined' && console)
console.info(tag + ": " + message);
}
app.ui.showAppError = function (message) {
app.consolePrintInfo("App", "displaying error message: " + message);
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-info');
$('#error-console').addClass('alert-error');
$('#error-console').html(message);
}
app.ui.showAppInfo = function (message) {
app.consolePrintInfo("App", "displaying info message: " + message);
$('#error-console').show();
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-error');
$('#error-console').addClass('alert-info');
$('#error-console').html(message);
$('#error-console').fadeOut(4000);
}
app.utility.addQueryParameter = function (url, paramName, paramValue) {
var rUrl = url;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
if (rUrl.indexOf("?") != -1) {
rUrl = rUrl + "&" + paramName + "=" + paramValue;
}
else {
rUrl = rUrl + "?" + paramName + "=" + paramValue;
}
}
return rUrl;
}
app.utility.addSearchParameter = function (paramName, paramValue) {
var rValue = undefined;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
rValue = paramName + ":" + paramValue;
}
return rValue;
}
app.utility.searchParameter = function (inputKeyArray, paramName) {
if (inputKeyArray instanceof Array) {
for (var i = 0; i < inputKeyArray.length; i++) {
if (inputKeyArray[i].paramName == paramName) {
return inputKeyArray[i].paramValue;
}
}
}
return undefined;
}
app.utility.isObjectNull = function (obj) {
return typeof(obj) == 'undefined' || obj == undefined || !obj;
}
app.utility.isObjectNotNull = function (obj) {
return typeof(obj) != 'undefined' && obj;
}
app.utility.isFunction = function (obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
app.utility.parseError = function (em) {
if (!app.utility.isObjectNull(em)) {
jem = JSON.parse(em);
var keyArray = new Array();
keyArray.push(jem.errorCode);
keyArray.push(jem.errorMessage);
return keyArray;
}
else {
return undefined;
}
}
app.utility.showAppErrorDialog = function (errTitle, errMessage) {
if (!app.utility.isObjectNull(errMessage)) {
var $message = $("Error:" + errMessage)
.dialog({autoOpen: false, width: 300, title: errTitle, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showErrorDialog = function (err) {
if (!app.utility.isObjectNull(err)) {
var $message = $('<div><p>Unfortunately, there has been error in the server!</p><p>' + err[1] + '</p><p>Please send the screenshot to developer team</div>')
.dialog({autoOpen: false, width: 300, title: err[0], modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showDialog = function (heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text)) {
var $message = $('<div><p>' + text + '</p></div>')
.dialog({autoOpen: false, width: 300, title: heading, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.populateToolTip = function () {
$("img[id^='tooltip']").each(function () {
var idName = $(this).attr("id");
$('#' + idName).tooltip('toggle');
$('#' + idName).tooltip('hide');
});
};
app.utility.isNotEmptyNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) && ("" + input).indexOf("-") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNotEmptyWholeNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) &&
("" + input).indexOf("-") == -1 && ("" + input).indexOf(".") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNumberValue = function (input) {
if (!isNaN(input) && isFinite(input)) {
return true;
}
return false;
};
app.utility.doHttpRequest = function (input) {
if (app.utility.isObjectNull(input) || app.utility.isObjectNull(input.rURL)) {
app.utility.showDialog("Error!", "Unable to find required inputs. Error in sending request");
return false;
}
app.consolePrintInfo("HTTP REQUEST: ", "[URL] :" + input.rURL);
app.consolePrintInfo("HTTP REQUEST: ", "[Type] :" + input.rType);
app.consolePrintInfo("HTTP REQUEST: ", "[Input] :" + input.rDataToSend);
$.ajax({
url: input.rURL,
type: input.rType,
contentType: 'application/json',
cache: false,
data: input.rDataToSend,
dataType: 'json'
}).success(function (response) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - success] :" + JSON.stringify(response));
if (!app.utility.isObjectNull(input.rOnSuccessFunction)) {
input.rOnSuccessFunction(response);
}
else if (!app.utility.isObjectNull(input.rOnSuccessMessage)) {
app.utility.showDialog("Complete", input.rOnSuccessMessage);
}
}).error(function (response) {
if (response.status == 401) {
// session expired. redirect to login page.
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Session Expired");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Session Expired', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
// Remove the cached data
//comp_storage.remove("lastStoredValue");
//comp_storage.remove("permissionStr");
//window.open("/aid-web/logout", "_self");
app.utility.doLogout();
}
}}
);
$message.dialog('open');
}
else if (response.status == 400) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Server Error");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Server Error', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
else {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] :" + response.responseText);
if (!app.utility.isObjectNull(input.rOnErrorFunction)) {
input.rOnErrorFunction(response.responseText);
}
else if (!app.utility.isObjectNull(input.rOnErrorMessage)) {
app.utility.showDialog("Error", input.rOnErrorMessage);
}
}
});
};
app.utility.doLogout = function () {
comp_storage.remove("lastStoredValue");
comp_storage.remove("permissionStr");
window.open("/aid-web/logout", "_self");
};
// common
// Nav bar component
app.common.navbar.reRenderNavBar = function (content) {
// [SAMPLE] To update the common component. create a view model of that
// component. set the needed variables.
// and *definately call applyBindings()*
app.common.navbar.navBarViewModel = new ko.navBarComponent.viewModel({
// set compt. values if needed. like below.
//navBarComponent_isEmpty:ko.observable(false)
});
app.common.navbar.navBarViewModel.navBarComponent_reRender(content);
ko.applyBindings(app.common.navbar.navBarViewModel, $('#nav-bar').get(0));
}
// Authorisation component
app.common.authorisation.storeRoleInfo = function (permissionArr) {
comp_auth.storeRoleInfo(permissionArr);
};
app.common.authorisation.isRolePresent = function (roleName) {
return comp_auth.isRolePresent(roleName);
};
// validation
app.validation.highlightElement = function (id, text) {
}
app.validation.highlightError = function (eleId, heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text) && !app.utility.isObjectNull(eleId)) {
$("#" + eleId).addClass("ui-state-error");
var $message = $('<div><p>' + text + '</p></div>')
.dialog({
autoOpen: true,
width: 300,
title: heading, modal: true,
close: function () {
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
},
buttons: {
Ok: function () {
$(this).dialog("close");
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
}
},
overlay: {
opacity: 0.1,
},
}
).parent().addClass("ui-state-error");
}
}

OncellChange Event of Slickgrid

I have a slickgrid with a checkbox column.
I want to capture the row id when the checkbox in the selected row is checked or unchecked.
Attached is the script for slickgrid in my view
I want when user checks the checkbox, active column in database should be set to true and when it is unchecked, Active column should be set to false.
<script type="text/javascript">
//$('input[type="button"]').enabled(false);
var grid;
var columnFilters = {};
var jsonmodel = #Html.Raw(Json.Encode(Model));
//function LoadNewMessagesData(messages) {
var dataView;
var data = [];
////console.log('lena:' + subdata.length);
$.each(jsonmodel, function (idx, spotlight) {
var pd = moment(spotlight.PostedDate);
data.push({ id: spotlight.ID, Department: spotlight.SubSection,Title: spotlight.Title, PostedDate: pd.format('YYYY-MM-DD'), Active: spotlight.Active })
});
var columns = [
{ id: '0', name: "Department", field: "Department", sortable: true},
{ id: '1', name: "Title", field: "Title", sortable: true},
{ id: '2', name: "PostedDate", field: "PostedDate", sortable: true }
];
var checkboxSelector = new Slick.CheckboxSelectColumn({
cssClass: "slick-cell-checkboxsel"
})
columns.push(checkboxSelector.getColumnDefinition());
var options = {
enableCellNavigation: true,
explicitInitialization: true,
enableColumnReorder: false,
multiColumnSort: true,
autoHeight: true,
forceFitColumns: true
};
dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
grid.registerPlugin(checkboxSelector);
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
console.log('testing');
grid.render();
});
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
var rowIndex;
grid.onCellChange.subscribe(function (e, args) {
console.log('onCellChange');
rowIndex = args.row;
});
if (grid.getActiveCell()) {
}
//onSelectedRowsChanged event, if row number was changed call some function.
grid.onSelectedRowsChanged.subscribe(function (e, args) {
if (grid.getSelectedRows([0])[0] !== rowIndex) {
console.log('onSelectedRowsChanged');
}
});
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
var comparer = function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
}
dataView.sort(comparer, args.sortAsc);
});
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
// dataView.setFilter(filter);
dataView.endUpdate();
//}
function RefreshMessagesGrid() {
//console.log('RefreshMessagesGrid');
//grid.invalidate();
grid.invalidateRows();
// Call render to render them again
grid.render();
grid.resizeCanvas();
}
</script>`enter code here`
Thanks in Advance !!!
You have to bind click event on rows....and get the id of the row whose checkbox is checked/unchecked
function bindClickOnRow() {
if($(this).find('.checkboxClass').attr('checked') == 'checked'){
checked = true;
} else {
checked = false;
}
rowId = $(this).attr('id');
}

Resources