fail to create operation with c8yDeviceControl.creat - cumulocity

I'm new to cumulocity application development. Now I'm learning to use Smart App Toolkit to develop HTML5 application.
I could create device in my Tenant, and could run some operations with servces provided in the SDK. However, I failed to create operation with c8yDeviceControl.create(). I got 400 (bad request) error code after the operation, and if I look deeper with chrome develop tool, it shows
{error: "Failed to parse JSON string"},
Here is my code, which I pick up from the Smart SDK sample code, with modifition to reference my deviceId:
var operation = {
deviceId: 12111,
com_cumulocity_model_WebCamDevice: {
name: 'take picture',
parameters: {
duration: '5s',
quality: 'HD'
}
}
};
c8yDeviceControl.create(operation);
Could anyone provide me a help to fix this problem?
Thanks.

The deviceID needs to be a string. This works:
var operation = {
deviceId: '1211',
com_cumulocity_model_WebCamDevice: {
name: 'take picture',
parameters: {
duration: '5s',
quality: 'HD'
}
}
};
c8yDeviceControl.create(operation);
Sorry for the inconvenience, we'll update the documentation.

Related

Mapbox API - update tileset

I am trying to replace tileset resources - using the https://docs.mapbox.com/api/maps/mapbox-tiling-service/#replace-a-tileset-source. I get the 200 response code for tilesetId I provide, but I cannot see my changes when I check it in my mapbox -> studio -> tilesets section.
const updateURL = `https://api.mapbox.com/tilesets/v1/sources/${username}/${id}?access_token=${accessToken}`;
const updateTilesetOptions = {
'method': 'PUT',
'url': updateURL,
'headers': {
'Content-Type': 'multipart/form-data'
},
formData: {
'file': {
'value': Buffer.from(fileToUpload.data).toString(),
'options': {
'filename': fileToUpload.name,
'contentType': null
}
}
}
};
const updateResponse = await requestPromise(updateTilesetOptions);
console.log("updateResponse.statusCode " , updateResponse.statusCode)
if (updateResponse.statusCode >= 400) {
return {
message: updateResponse.statusMessage,
code: updateResponse.statusCode,
source: "Update Tileset"
}
}
Can someone suggest what I am doing wrong. Note: I also tried to publish tileset after udpating the source, but I am getting 400 error.
I received a reply from Mapbox. This is the correct process;
(1) Delete the existing tileset source. If you just update the existing tileset, you are indeed appending data to it.
(2) Create a new tileset source with the same ID
(3) Publish your updated tileset. Please note that this suggests that you already have a tileset recipe configured for the existing tileset
Please let me know if it works for you. It works for me now. I was missing the publishing step.

How to configure dynamic links for a Firebase project?

Since google is shutting down it's url shortening service, I want to move my project to FDL.
I am using the api to shorten the url following this:
https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_a_long_link
and I am using Postman to call the api but I keep getting this error.
{
"error": {
"code": 400,
"message": "Your project has not configured Dynamic Links. [https://firebase.google.com/docs/dynamic-links/rest#before_you_begin]",
"status": "INVALID_ARGUMENT"
}
}
I am using the correct api key and the project id.
Had the same issue- and thats the answer i got from the firebase team:
Take note that to be able to view your Dynamic Link domain you'll have
to add an app first. If you're using Firebase Dynamic Link as a
substitute to Google Shortener, you can create a sample application
(dummy app) for your project to proceed creating a Firebase Dynamic
Links. Just enter dummy values for the iOS bundle ID or Android
package name (ex: “my.dummy.app”) to continue.
then you'll put the id you'll get from it (e.g. https://dedfgu.app.goo.gl) instead of the place holder (https://abc123.app.goo.gl).
Good luck!
You can try following way
var Url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key={API-Key}";
$.ajax({
type: 'POST',
dataType: 'json',
url: Url,
contentType:'application/json',
data: JSON.stringify({
"dynamicLinkInfo": {
"domainUriPrefix": "https://newxpress.page.link",
"link": {Your-Link},
"androidInfo": {
"androidPackageName": "com.newxpress"
},
"iosInfo": {
"iosBundleId": "com.newxpress.iosapp"
}
}
}),
success: function (jsondata) {
console.log(jsondata);
},
error: function (result) {
console.log(result);
}
});

How to store the data in local device using JSONStore in worklight?

I'm doing Login Page in worklight using JavaScript and jquery, the username and password should validate the data getting from JSONstore?
How to store the data locally using JSONStore in worklight and how does i get the data from JSONStore while validating the username and password?
In below code where my data will store and get, if the username and password has typed where it validate:
var collections = {
people : {
searchFields : {name: 'string'}
},
orders : {
searchFields: {name: 'string'}
}
};
WL.JSONStore.init(collections)
.then(function () {
return WL.JSONStore.init(collections);
})
.then(function () {
return WL.JSONStore.init(collections);
})
.then(function () {
alert('Multiple inits worked');
})
.fail(function (err) {
lert('Multiple inits failed' + err.toString());
});
How to solve the issue?
You really should never ever store username and password locally in the device. That does not sound very secure...
Additionally, where is the username and password coming from? How should the logic be able to validate the credentials? It needs to compare whatever is inputted with something, to know that it is correct. An implementation cannot be done without otherwise, so you need to provide the answer to this...
In the meanwhile, you can take a look at the following tutorial: Offline Authentication.
The included sample application assumes you have first authenticated with a backend system, and later allows for authenticating locally, "offline", in case an Internet connection is not available. For this it uses JSONStore to securely authenticate.
The tutorial include a thorough implementation example, be sure to follow it, and to provide the missing information in your question.
This tutorial explains how to use the JSONStore API, including the Add method: https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/data/jsonstore/jsonstore-javascript-api/
var collectionName = 'people';
var options = {};
var data = {name: 'yoel', age: 23};
WL.JSONStore.get(collectionName).add(data, options).then(function () {
// handle success
}).fail(function (error) {
// handle failure
});

angular fullstack generator can not send iamge stored in mongodb

What a want to achieve is simple. I am using angular fullstack generator to produce the skeleton. User should be able to upload a profile picture along with their name, email etc. I am using angular-file-uplpoad to send the multipart form request. And according to its wiki, I also used code below.
// Requires multiparty
multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty(),
// Requires controller
UserController = require('./controllers/UserController');
// Example endpoint
router.post('/api/user/uploads', multipartyMiddleware, UserController.uploadFile);
I am also using gridfs-stream to stream the profile image into mongo gridfs. Everything seems fine here. Because if I stream the profile image into server local file, I can actually open and view the image. The problem is that, now I want to send the image back to the browser. I wrote code below
var Grid = require('gridfs-stream');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);
var fs = require('fs');
/*
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
hashedPassword: String,
provider: String,
salt: String,
phone: String,
projects: [{
type : Schema.Types.ObjectId,
ref : 'Project'
}],
profile_picture: Schema.Types.ObjectId
});
*/
// each user has a _id for a image file in mongodb
getFile : function() {
var readstream = GridFS.createReadStream({
_id : this.profile_picture,
});
response.writeHead(200, {'Content-Type': 'iamge/png' });
readstream.pipe(response);
},
But this does not work. To test it. I even use fs.createReadStream(filename) to load a static image stored in the server side. The image is actually sent but the it's a broken image received in the browser. I also tried response.download('filename'); still does not work. Any suggestions?
Thanks!
You wrote: {'Content-Type': 'iamge/png' }
Fix it to: {'Content-Type': 'image/png' }
Let me know if that solves it because I am also having problems and have similar code.

How to create a custom user authentication in Meteor?

I am trying to create the following authentication for an app:
User enters phone number and receives an SMS with a code generated in the server (the SMS is handled through an external service). If the user enters the right code he is logged in.
This means I must have two login stages: registering user with a phone and logging him in with the code, so this is what I think the client should look like:
Meteor.getSmsCode = function(phone, username, callback) {
Accounts.callLoginMethod({
methodName: 'getsmscode',
methodArguments: [{
getsmscode: true,
phone: phone,
username: username
}],
userCallback: callback
});
};
Meteor.loginWithCode = function(phone, code, callback) {
Accounts.callLoginMethod({
methodName: 'login',
methodArguments: [{
hascode: true,
phone: phone,
code: code
}],
userCallback: callback
});
};
But I am confused about the server side - there should be two methods:
the first should only register a user (and communicate with the SMS service) and second should log him in.
This is the server test code for now:
Meteor.users.insert({phone: '123456789', code: '123', username:'ilyo'});
Accounts.registerLoginHandler(function(loginRequest) {
var user = Meteor.users.findOne({phone: loginRequest.phone});
if(user.code !== loginRequest.code) {
return null;
}
var stampedToken = Accounts._generateStampedLoginToken();
var hashStampedToken = Accounts._hashStampedToken(stampedToken);
Meteor.users.update(userId,
{$push: {'services.resume.loginTokens': hashStampedToken}}
);
return {
id: user._id,
token: stampedToken.token
};
});
And this is what happens when I try it:
Why an I getting the 500?
Why doesn't the user have a code and phone fields?
What method should I use for the getSmsCode?
Meteor.createUser is described on How can I create users server side in Meteor?
Then, the Accounts.onCreateUser would contain business logic http://docs.meteor.com/#accounts_oncreateuser
A more exact message for the 500 would be on the server-side stdout. Probably security.
Your Login Handler must return an object as follows:
{ userId: user._id }
Sorry I don't elaborate in the whole problem, I don't agree on your full approach but looks you are in the right path to get the feature you need.
Also, this question is one year old, now there are a few packages at atmosphere that address this kind of authentication =)