I am trying to create a JSONStore in a Mobilefirst 7.0 hybrid app. The issue I am having is to be able to detect that the JSONStore is already there on subsequent runs of the app. The documentation says you have to have called WL.JSONStore.init(...) before calling WL.JSONStore.get(...).
So the question is, on subsequent runs of the app (meaning the app ran for the first time and created the JSONStore successfully) and this is a new run, what is the proper way to check if the JSONStore already exists?
If I have to call init again, how do I do that without wiping out what is there?
I am currently using this snippet of code to detect...
function checkJSONStore() {
alert("In checkJSONStore");
var collectionName;
try {
// Check to see if JSONStore exists...
collectionName = WL.JSONStore.get('appStore');
} catch (e) {
// TODO: handle exception
alert("checkJSONStore: Exception = " + e.message);
}
alert("Returning from checkJSONStore: " + collectionName);
return collectionName;
}
Here is the code that create the store...it runs successfully.
function initJSONStore() {
console.log("In initJSONStore:");
var collectionName = "appStore";
var Data = {
item: 'newinstall',
value: 1
};
var JSONStoreCollections = {};
JSONStoreCollections[collectionName] = {};
JSONStoreCollections[collectionName].searchFields = {item: 'string'};
try {
console.log("Destroy any collections before we start");
WL.JSONStore.destroy().then(function () {
//handle success
console.log("initJSONStore: JSONStore destroy success");
})
.fail(function (error) {
//handle failure
console.log("initJSONStore: JSONStore destroy failure: " + error);
});
console.log("Calling WL.JSONStore.init");
WL.JSONStore.init(JSONStoreCollections).then(function () {
console.log("initJSONStore: JSONStore init success");
WL.JSONStore.get('appStore').add(Data).then(function () {
console.log("initJSONStore: JSONStore add success");
}).fail(function (error) {
console.log("initJSONStore: JSONStore add failure: " + error);
});
}).fail(function (error) {
console.log("initJSONStore: JSONStore init failure");
});
} catch (e) {
// TODO: handle exception
//console.log("initJSONStore: Exception = " + e.message);
alert("initJSONStore: Exception = " + e.message);
}
console.log("Exiting initJSONStore:");
}
Calling .init again will not wipe your already-created collection. Only by calling .destroy will the already-created collection be destroyed... and so on the next init it will be (re-)created.
Related
I've created an app and try to register for webhooks, and then fetch the list of all webhooks.
I use this code for this (/server/middleware/auth.js):
const webhook = new Webhook({ session: session });
webhook.topic = "products/update";
webhook.address = "https://api.service.co/items/update";
webhook.format = "json";
console.log("registering products/update");
try {
await webhook.save({
update: true,
});
} catch (error) {
console.log(error);
}
const webhookSecond = new Webhook({ session: session });
webhookSecond.topic = "products/create";
webhookSecond.address = "https://api.service.co/items/webhooks";
webhookSecond.format = "json";
console.log("registering products/create");
try {
await webhookSecond.save({
update: true,
});
} catch (error) {
console.log(error);
}
console.log("getting all webhooks");
try {
let webhooks = await Webhook.all({
session: session,
});
console.log(webhooks);
} catch (error) {
console.log(error);
}
Everything works fine for a development store. However, when I try to launch this script on a third-party customer store, then I get this error:
HttpRequestError: Failed to make Shopify HTTP request: FetchError: invalid json response body at https://shopname.myshopify.com/admin/api/2022-04/webhooks.json reason: Unexpected end of JSON input
The app permissions/scopes are: read_checkouts, read_orders, read_inventory, read_products, read_customers
I got this error 3 times, even for Webhook.all.
Could you please tell me what can cause this error, and how could it be fixed?
This error was caused by the lack of access provided by the owner of the store to my collaborator developer account. Manage settings access was required.
React-native-document-picker not working in android
after selecting image app stopped.
react-native ver:-59.5
react-native-document-picker --v:-3.2.4
I am using this code.
var results = await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.images],
});
for(var res of results) {
this.setState({
getSecondFile:res,
chosepic_2:res.uri
})
console.log(
res.uri,
res.type, // mime type
res.name,
res.size
);
}
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}```
In my project. i used another library i.e react-native-open-doc and it not work properly in my project.and i used android studio for found out the error.
you can use this code for find the file in console
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types. allFiles],
});
console.log(
res
);
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
}````
I create a function to handle transaction, then I call it to multi places. I got crash when another transaction not yet complete when I open new transaction.
Here my code:
const RealmMakeTransaction = async (action) => {
try {
realm.GetInstance().beginTransaction();
let response = await action();
realm.GetInstance().commitTransaction();
return response;
} catch (e) {
realm.GetInstance().cancelTransaction();
}
};
You can easily check if realm is already in transaction or not before calling beginTransaction() by calling realm.GetInstance().isInTransaction
Your code will look like :
const RealmMakeTransaction = async (action) => {
//use single instance
let realm = realm.GetInstance();
try {
if( realm.isInTransaction)
realm.cancelTransaction();
realm.beginTransaction();
let response = await action();
realm.commitTransaction();
return response;
} catch (e) {
realm.cancelTransaction();
realm.close();
}
};
I am trying to join a meeting anonymously through a meeting URI and this does not seem to work. I went to the SKYPE UCWA site and went to the interactive SDK - and tried to join a meeting anonymously from there but the page does not do anything.
https://ucwa.skype.com/websdk
Below is the code that I am trying to join a meeting anonymously, but the call to client.signInManager.signIn never completes and neither any exception is thrown.
Looking for suggestions to resolve this issue. Also, if someone has working code of joining a meeting anonymously using SKYPE web sdk (UCWA), please share the same. Thanks.
function InitialiseSkype() {
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebAppCtor = api.application;
window.skypeWebApp = new api.application();
client = new window.skypeWebAppCtor;
//once intialised, sign in
alert("Skype SDK Initialized");
JoinAnonymous();
}, function (err) {
console.log(err);
alert('Cannot load the SDK.');
});
}
function JoinAnonymous(){
client.signInManager.signIn({
version: config.Version,
name: $('#name').val(),
meeting: $('#meetingUri').val()
}).then(function () {
alert('Signed In, Anonymously');
var conversation = application.conversationsManager.getConversationByUri(uri);
}, function (error) {
alert(error);
});
}
Actually I did sign in anonymously using that code :
//Init
var config = {apiKey: 'a42fcebd-5b43-4b89-a065-74450fb91255', // SDK
apiKeyCC: '9c967f6b-a846-4df2-b43d-5167e47d81e1' // SDK+UI
};
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebApp = new api.application;
}, function (err) {
console.log("cannot load the sdk package", err);
});
//Actual code
var uri ="sip:xxxxxxxx;gruu;opaque=app:conf:focus:id:xxxxxxxx";
window.skypeWebApp.signInManager.signIn({
name: "pseudo",
meeting:uri
}).then(function () {
alert('Signed In, Anonymously');
}, function (error) {
alert(error);
});
I did connect with the uri given in the ucwa.skype interactive web sdk page.
But I did not manage to join the conversation after that, probably because the interactive sample does not really create the room.
I can join a meeting from a office365 account while logged in with a sample account. However I can not join anonymously my meeting room.
Do you try with an on-premise account or with a office365 account ?
Looks like Anonymous join for a meeting is not yet available for Skype For Business online.
New update of WebSDK now support anonymous meeting join for SfB Online
(function () {
'use strict';
// this will be populated when the auth token is fetched
// it is later needed to sign into Skype for Business
var authDetails = {};
// A reference to the Skype SDK application object
// set during initialization
var app;
displayStep(0);
registerUIListeners();
// Initializing the Skype application
Skype.initialize({
apiKey: '9c967f6b-a846-4df2-b43d-5167e47d81e1'
}, function (api) {
console.log('Skype SDK initialization successful');
app = api.UIApplicationInstance;
// Once it is initialized, display a UI prompt for a meeting URL
displayStep(1);
}, function (err) {
console.error('Skype SDK initialization error:', err);
});
// After the user submits the meeting URL the next step is to
// fetch an auth token
function getToken(evt) {
var input = evt.target.querySelector('input'),
meetingUrl = input.value,
request = new XMLHttpRequest(),
data;
evt.preventDefault();
console.log('Fetching auth token from meeting url:', meetingUrl);
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
var sessionId = guid();
data = 'ApplicationSessionId=' + sessionId +
'&AllowedOrigins=' + encodeURIComponent(window.location.href) +
'&MeetingUrl=' + encodeURIComponent(meetingUrl);
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
authDetails.discoverUrl = response.DiscoverUri;
authDetails.authToken = "Bearer " + response.Token;
console.log('Successfully fetched the anonymous auth token and discoverUrl', authDetails);
displayStep(2);
}
else {
console.error('An error occured, fetching the anonymous auth token', request.responseText);
}
}
};
request.open('post', 'http://webrtctest.cloudapp.net/getAnonTokenJob');
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
// This uses the auth token and discovery URL to sign into Skype
// and join the meeting
function joinAVMeeting(evt) {
var input = evt.target.querySelector('input'),
name = input.value;
evt.preventDefault();
console.log('Joinig meeting as:', name);
app.signInManager.signIn({
name: name,
cors: true,
root: { user: authDetails.discoverUrl },
auth: function (req, send) {
// Send token with all requests except for the GET /discover
if (req.url != authDetails.discoverUrl)
req.headers['Authorization'] = authDetails.authToken;
return send(req);
}
}).then(function () {
// When joining a conference anonymously, the SDK automatically creates
// a conversation object to represent the conference being joined
var conversation = app.conversationsManager.conversations(0);
console.log('Successfully signed in with anonymous online meeting token');
registerAppListeners(conversation);
// This turns on local video and joins the meeting
startVideoService(conversation);
}).catch(function (error) {
console.error('Unable to join conference anonymously:', error);
});
function registerAppListeners(conversation) {
conversation.selfParticipant.video.state.when('Connected', function () {
console.log('Showing self video');
document.querySelector('.self').style.display = 'inline-block';
setupContainer(conversation.selfParticipant.video.channels(0), document.querySelector('.self .video'));
displayName(document.querySelector('.self'), conversation.selfParticipant);
console.log('The video mode of the application is:', conversation.videoService.videoMode());
if (conversation.videoService.videoMode() === 'MultiView') {
// Loading the sample in any other browser than Google Chrome means that
// the videoMode is set to 'MultiView'
// Please refer to https://msdn.microsoft.com/en-us/skype/websdk/docs/ptvideogroup
// on an example on how to implement group video.
}
// When in active speaker mode only one remote channel is available.
// To display videos of multiple remote parties the video in this one channel
// is switched out automatically, depending on who is currently speaking
if (conversation.videoService.videoMode() === 'ActiveSpeaker') {
var activeSpeaker = conversation.videoService.activeSpeaker;
setupContainer(activeSpeaker.channel, document.querySelector('.remote .video'));
activeSpeaker.channel.isVideoOn.when(true, function () {
document.querySelector('.remote').style.display = 'inline-block';
activeSpeaker.channel.isStarted(true);
console.log('ActiveSpeaker video is available and has been turned on.');
});
activeSpeaker.channel.isVideoOn.when(false, function () {
document.querySelector('.remote').style.display = 'none';
activeSpeaker.channel.isStarted(false);
console.log('ActiveSpeaker video is not available anymore and has been turned off.');
});
// the .participant object changes when the active speaker changes
activeSpeaker.participant.changed(function (newValue, reason, oldValue) {
console.log('The ActiveSpeaker has changed. Old ActiveSpeaker:', oldValue && oldValue.displayName(), 'New ActiveSpeaker:', newValue && newValue.displayName());
if (newValue) {
displayName(document.querySelector('.remote'), newValue);
}
});
}
});
conversation.state.changed(function (newValue, reason, oldValue) {
if (newValue === 'Disconnected' && (oldValue === 'Connected' || oldValue === 'Connecting')) {
console.log('The conversation has ended.');
reset();
}
});
}
function setupContainer(videoChannel, videoDiv) {
videoChannel.stream.source.sink.format('Stretch');
videoChannel.stream.source.sink.container(videoDiv);
}
function displayName(container, person) {
container.querySelector('.displayName .detail').innerHTML = person.displayName();
}
function startVideoService(conversation) {
conversation.videoService.start().then(null, function (error) {
console.error('An error occured joining the conversation:', error);
});
displayStep(3);
}
}
function endConversation(evt) {
var conversation = app.conversationsManager.conversations(0);
evt.preventDefault();
conversation.leave().then(function () {
console.log('The conversation has ended.');
reset();
}, function (error) {
console.error('An error occured ending the conversation:', error);
}).then(function () {
reset();
});
}
//-----------------------------------------------------------------------
//UI helper functions
function displayStep(step) {
var nodes = document.querySelectorAll('.step');
for (var i = 0; i < nodes.length; ++i) {
var node = nodes[i];
node.style.display = 'none';
if (i === step) {
node.style.display = 'block';
}
}
}
function registerUIListeners() {
document.querySelector('.step1').onsubmit = getToken;
document.querySelector('.step2').onsubmit = joinAVMeeting;
document.querySelector('.step3').onsubmit = endConversation;
}
function reset() {
window.location = window.location.href;
}
})();
https://github.com/OfficeDev/skype-docs/blob/master/Skype/WebSDK/samples/Meetings/Anonymous%20Online/standalone/index.js
I'm having issues with a the Oracle DB module:
https://github.com/oracle/node-oracledb/blob/master/doc/api.md
I have an application which has between 300 and 900 hits per hour (normally from around 100 users). The application has many $.post requests in the background to retrieve information from a database and display to the user.
I've recently switched to this module as it is Oracle's own (I was using https://github.com/joeferner/node-oracle previously).
Here's how I have it set out:
/bin/www
oracledb.createPool(
{
user : 'USER'
password : 'PASS',
connectString : 'DB:1521/SID:POOLED',
connectionClass : 'ARBITRARY_NAME',
poolMin : 1,
poolMax : 50,
poolTimeout : 300
},
function(err, pool)
{
if (err) {
console.log(err);
}
require('../libs/db')(pool); // Export pool to separate file
}
)
/libs/db.js
module.exports = function(pool) {
// Require oracle module for formatting
var oracledb = require('oracledb');
// Export acquire and query function
module.exports.acquire_and_query = function(sql, params, callback){
// ACQUIRE connection from pool
pool.getConnection(function(err, connection){
// NUMBER OF CONNCETIONS OPEN
console.log("ORACLE: CONNX OPEN: " + pool.connectionsOpen);
// NUMBER OF CONNEXTIONS IN USE
console.log("ORACLE: CONNX IN USE: " + pool.connectionsInUse);
if (err) {
console.log(err.message);
return;
}
// Use connection to QUERY db and return JSON object
connection.execute(sql, params, {maxRows: 1000, isAutoCommit: true, outFormat: oracledb.OBJECT}, function(err, result){
// Error Handling
if (err) {
console.log(err.message); // Log the error
return false; // Return false for our error handling
}
// Release the connection back to the pool
connection.release(function(err) {
if (err) {
console.log(err.message);
return;
}
})
// Return callback with rowset first, out bind paramaters second
return callback(result.rows, result.outBinds, result.rowsAffected);
})
})
}
}
This module "acquire_and_query" is called from with in our application, and has SQL and it's params passed in to be executed.
The Oracle DB has a maximum allowed of Pooled connections set to 80 (and we are not exceeding them) - and generally looks pretty happy.
The node application however is constantly throwing out an ORA-24418: Cannot open further sessions, and I am unsure how to resolve this.
Thanks.
Resolved - Issue: My poor coding!
I had unwittingly set a Socket.IO event to update the view for EVERYONE connected multiple times (rather than querying the database once, then sending the view over the socket...) sigh
I was also even more stupidly using a for loop in a transaction based query (which was INSERTing multiple data on each run)... Once I had changed this to a recursive pattern - it went ran swimmingly!
Good article here about for loops and recursive patterns: http://www.richardrodger.com/2011/04/21/node-js-how-to-write-a-for-loop-with-callbacks/#.VaQjJJNViko
Anyway - here's what I use now (and it works rather well)
Using node-oracledb v0.6 (https://github.com/oracle/node-oracledb) and Express 4 (http://expressjs.com/)
bin/www
/**
* Database
*/
// AS PER DOCUMENTATION: https://github.com/oracle/node-oracledb/blob/master/examples/dbconfig.js
var dbconfig = require("../libs/dbconfig.js");
oracledb.connectionClass = dbconfig.connectionClass,
oracledb.createPool({
user: dbconfig.user,
password: dbconfig.password,
connectString: dbconfig.connectString,
poolMax: 44,
poolMin: 2,
poolIncrement: 5,
poolTimeout: 4
}, function(err, pool) {
if (err) {
console.log("ERROR: ", new Date(), ": createPool() callback: " + err.message);
return;
}
require('../libs/oracledb.js')(pool);
});
libs/oracledb.js
module.exports = function(pool) {
////////////////////////////
// INSTANTIATE THE DRIVER //
////////////////////////////
var oracledb = require("oracledb");
//////////////////////
// GET A CONNECTION //
//////////////////////
var doConnect = function(callback) {
console.log("INFO: Module getConnection() called - attempting to retrieve a connection using the node-oracledb driver");
pool.getConnection(function(err, connection) {
// UNABLE TO GET CONNECTION - CALLBACK WITH ERROR
if (err) {
console.log("ERROR: Cannot get a connection: ", err);
return callback(err);
}
// If pool is defined - show connectionsOpen and connectionsInUse
if (typeof pool !== "undefined") {
console.log("INFO: Connections open: " + pool.connectionsOpen);
console.log("INFO: Connections in use: " + pool.connectionsInUse);
}
// Else everything looks good
// Obtain the Oracle Session ID, then return the connection
doExecute(connection, "SELECT SYS_CONTEXT('userenv', 'sid') AS session_id FROM DUAL", {}, function(err, result) {
// Something went wrong, releae the connection and return the error
if (err) {
console.log("ERROR: Unable to determine Oracle SESSION ID for this transaction: ", err);
releaseConnection(connection);
return callback(err);
}
// Log the connection ID (we do this to ensure the conncetions are being pooled correctly)
console.log("INFO: Connection retrieved from the database, SESSION ID: ", result.rows[0]['SESSION_ID']);
// Return the connection for use in model
return callback(err, connection);
});
});
}
/////////////
// EXECUTE //
/////////////
var doExecute = function(connection, sql, params, callback) {
connection.execute(sql, params, { autoCommit: false, outFormat: oracledb.OBJECT, maxRows:1000 }, function(err, result) {
// Something went wrong - handle the data and release the connection
if (err) {
console.log("ERROR: Unable to execute the SQL: ", err);
//releaseConnection(connection);
return callback(err);
}
// Return the result to the request initiator
// console.log("INFO: Result from Database: ", result)
return callback(err, result);
});
}
////////////
// COMMIT //
////////////
var doCommit = function(connection, callback) {
connection.commit(function(err) {
if (err) {
console.log("ERROR: Unable to COMMIT transaction: ", err);
}
return callback(err, connection);
});
}
//////////////
// ROLLBACK //
//////////////
var doRollback = function(connection, callback) {
connection.rollback(function(err) {
if (err) {
console.log("ERROR: Unable to ROLLBACK transaction: ", err);
}
return callback(err, connection);
});
}
//////////////////////////
// RELEASE A CONNECTION //
//////////////////////////
var doRelease = function(connection) {
connection.release(function(err) {
if (err) {
console.log("ERROR: Unable to RELEASE the connection: ", err);
}
return;
});
}
//////////////////////////////
// EXPORT THE FUNCTIONALITY //
//////////////////////////////
module.exports.doConnect = doConnect;
module.exports.doExecute = doExecute;
module.exports.doCommit = doCommit;
module.exports.doRollback = doRollback;
module.exports.doRelease = doRelease;
}
Example Usage
//////////////////////////////
// REQUIRE RELEVANT MODULES //
//////////////////////////////
var db = require("../libs/oracledb.js");
var oracledb = require('oracledb');
var sql = "";
///////////////////////////
// RETRIEVE CURRENT DATE //
///////////////////////////
module.exports.getCurDate = function(callback) {
sql = "SELECT CURRENT_DATE FROM DUAL";
db.doConnect(function(err, connection){
console.log("INFO: Database - Retrieving CURRENT_DATE FROM DUAL");
if (err) {
console.log("ERROR: Unable to get a connection ");
return callback(err);
} else {
db.doExecute(
connection, sql
, {} // PASS BIND PARAMS IN HERE - SEE ORACLEDB DOCS
, function(err, result) {
if (err) {
db.doRelease(connection); // RELEASE CONNECTION
return callback(err); // ERROR
} else {
db.doRelease(connection); // RELEASE CONNECTION
return callback(err, result.rows); // ALL IS GOOD
}
}
);
}
});
}
This error message is raised when the sessMax parameter supplied in OCISessionPoolCreate has been reached.
So, my first move would be verify if database sessions are being closed correctly.
When this error message arises execute the following three actions:
1.- (using sqlplus) show parameter sess
2.- (using sqlplus)
select username,machine,program,count(*) from v$session
group by username,machine ,program
order by 4 ;
3.- verify in alert.log if there are any other ORA- messages during this event.
Did you perform this steps ? (share your results)