Azure mobile service table filter - node.js

I am trying to get users that are present in array onlineUsers, but it is giving me following error. Can someone please give me work around if this doesn't work
CODE:
exports.post = function(request, response) {
var onlineUsers = ["6990"];
// Tables
var userTable = request.service.tables.getTable('Users');
userTable.where(
function(ou) {
return ou.search(this.id) != -1;
},onlineUsers).read({
success : function(users){
response.send(statusCodes.OK, { message : users });
}
});
};
ERROR:
Error in script '/api/test_find.js'. Error: The expression 'ou.search(this.id)'' is not supported.

Try the following:
userTable.where(function(ou) {
return this.id in ou;
}, onlineUsers)
Keep in mind that the SQL generated contains a separate where clause for each element of onlineUsers, so it can become quite inefficient if the array contains many elements. We're looking at improving the query API.

Related

Azure stored procedure in Azure portal not working although SQL query works

The following stored procedure failed to produce any result even though the SQL query used in it produced results when tested on the Azure portal.
function checktemp() {
var context = getContext();
var container = context.getCollection();
var response = context.getResponse();
let query = `SELECT DISTINCT {"Elevator": t.connectiondeviceid,
"Vibration": t["vibration"],
"Temperature": t["temperature"]}
FROM t
WHERE t["temperature"] > 75
AND t.EventEnqueuedUtcTime > "2019-08-03T20:30:51.905Z"
ORDER BY t["temperature"] DESC`
// Query documents and take 1st item.
var isAccepted = container.queryDocuments(
container.getSelfLink(), query,
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) {
response.setBody('no docs found');
}
else {
var body = { moststrain: feed[0] };
response.setBody(JSON.stringify(body));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
I expect to have items returned, but I always get 'no docs found'. My partition key is /ConnectionDeviceId.
Tested your sample document with your stored procedure code,it works for me.Your SP structure should be fine.
Some mistake with the spell of property(ConnectionDeviceId) you provide,it should be ConnectionDeviceId in sql:t.ConnectionDeviceId.
To solve such issue like something works in the portal, no results in SP, i suggest you removing query statements partially step by step to locate which part of SQL causes no results.
Anyway,the issue is related to partition key. When you query data in the portal, it scans all the partitions. However,if you execute SP,it only scans specific partition.
Since the data is partitioned on 'connectiondeviceid', I was supposed to provide a value of it during execution of the stored procedure.

Cloudrail - Twitter API - GetIdentifier fails

I'm using cloudrail-node-js v.2.17.3.
I want to simply get an unique Identifier for Twitter Authentication.
However, this always returns an error :
{ [Error: The URL the RedirectReceiver returns does not contain all necessary keys in the query, it's missing at least oauth_token,oauth_verifier]
message: 'The URL the RedirectReceiver returns does not contain all necessary keys in the query, it\'s missing at least oauth_token,oauth_verifier' }
Here is my code :
const cloudrail = require('cloudrail-si');
cloudrail.Settings.setKey(cloudrailKey);
let Service = new cloudrail.services.Twitter(cloudrail.RedirectReceivers.getLocalAuthenticator(3000), twitterKey, twitterSecret, `http://localhost:3000`, "state");
Service.getIdentifier(function (err, id) {
console.log(err, id);
});
Thanks in advance.

DocumentDB / CosmosDB - Entity with the specified id does not exist in the system

i tried to connect documentdb from my asp.net website but i am getting this error.
Entity with the specified id does not exist in the system
DocumentClientException: Entity with the specified id does not exist in the system
code as follows in aspx code behind
protected async void Page_Load(object sender, EventArgs e)
{
Response.Write("Page Load<br/>");
await GetData();
}
public async Task GetData()
{
try
{
Response.Write("<br/> Get Data function Start<br/><br/>");
using (var client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]))
{
//await client.OpenAsync();
RequestOptions reqOpt = new RequestOptions { PartitionKey = new PartitionKey(209) };
var parameters = new dynamic[] { 1 };
StoredProcedureResponse<object> result = await client.ExecuteStoredProcedureAsync<object>(
UriFactory.CreateStoredProcedureUri(ConfigurationManager.AppSettings["database"], ConfigurationManager.AppSettings["pcsd"], "GetMemberbyId"), reqOpt, parameters);
Response.Write(result.Response.ToString());
}
Response.Write("<br/><br/> Get Data function End");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
stored procedure as follows
function GetMemberbyId(memId) {
var collection = getContext().getCollection();
//return getContext().getResponse().setBody('no docs found');
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root m where m.memberId='+memId,
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) getContext().getResponse().setBody('no docs found');
else getContext().getResponse().setBody(feed);
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
in my localhost it's working fine but website published to azure web apps and running i am getting above error
I just spent a couple of hours troubleshooting this, only to find that I had firewalled my instance to a point where I could not connect locally. Keep in mind that the Azure portal document query will obviously still work even when you have no direct access via the API / C# client.
Try setting the firewall to allow All Networks temporarily to check access.
I would check in the portal that the "GetMemberbyId" is the name of the stored procedure for the collection you are trying to run it on. Could be the stored procedure is on a different collection or that the stored procedure is named something else.
If that all checks out.. I have had more luck with the __.filter() way of querying documents on the server. See:
http://azure.github.io/azure-documentdb-js-server/

Uploading a file from Autodesk A360 to bucket in NodeJS

I am using the Forge data management API to access my A360 files and aim to translate them into the SVF format so that I can view them in my viewer. So far I have been able to reach the desired item using the ForgeDataManagement.ItemsApi, but I don't know what to do with the item to upload it to the bucket in my application.
From the documentation it seems like uploadObject is the way to go (https://github.com/Autodesk-Forge/forge.oss-js/blob/master/docs/ObjectsApi.md#uploadObject), but I don't know exactly how to make this function work.
var dmClient = ForgeDataManagement.ApiClient.instance;
var dmOAuth = dmClient.authentications ['oauth2_access_code'];
dmOAuth.accessToken = tokenSession.getTokenInternal();
var itemsApi = new ForgeDataManagement.ItemsApi();
fileLocation = decodeURIComponent(fileLocation);
var params = fileLocation.split('/');
var projectId = params[params.length - 3];
var resourceId = params[params.length - 1];
itemsApi.getItemVersions(projectId, resourceId)
.then (function(itemVersions) {
if (itemVersions == null || itemVersions.data.length == 0) return;
// Use the latest version of the item (file).
var item = itemVersions.data[0];
var contentLength = item.attributes.storageSize;
var body = new ForgeOSS.InputStream();
// var body = item; // Using the item directly does not seem to work.
// var stream = fs.createReadStream(...) // Should I create a stream object lik suggested in the documention?
objectsAPI.uploadObject(ossBucketKey, ossObjectName, contentLength, body, {}, function(err, data, response) {
if (err) {
console.error(err);
} else {
console.log('API called successfully. Returned data: ' + data);
//To be continued...
}
I hope someone can help me out!
My current data:
ossObjectName = "https://developer.api.autodesk.com/data/v1/projects/"myProject"/items/urn:"myFile".dwfx";
ossBucketKey = "some random string based on my username and id";
Regards,
torjuss
When using the DataManagement API, you can either work with
2 legged oAuth (client_credentials) and access OSS' buckets and objects,
or 3 legged (authorization_code) and access a user' Hubs, Projects, Folders, Items, and Revisions
When using 3 legged, you do access someones content on A360, or BIM360 and these files are automatically translated by the system, so you do not need to translate them again, not to transfer them on a 2 legged application bucket. The only thing you need to do it is get the manifest of the Item or its revision and use the URN to see it in the viewer.
Checkout an example here: https://developer.autodesk.com/en/docs/data/v2/reference/http/projects-project_id-versions-version_id-GET/
you'll see something like
Examples: Successful Retrieval of a Specific Version (200)
curl -X GET -H "Authorization: Bearer kEnG562yz5bhE9igXf2YTcZ2bu0z" "https://developer.api.autodesk.com/data/v1/projects/a.45637/items/urn%3Aadsk.wipprod%3Adm.lineage%3AhC6k4hndRWaeIVhIjvHu8w"
{
"data": {
"relationships": {
"derivatives": {
"meta": {
"link": {
"href": "/modelderivative/v2/designdata/dXJuOmFkc2sud2lwcWE6ZnMuZmlsZTp2Zi50X3hodWwwYVFkbWhhN2FBaVBuXzlnP3ZlcnNpb249MQ/manifest"
}
},
Now, to answer teh other question about upload, I got an example available here:
https://github.com/Autodesk-Forge/forge.commandline-nodejs/blob/master/forge-cb.js#L295. I copied the relevant code here for everyone to see how to use it:
fs.stat (file, function (err, stats) {
var size =stats.size ;
var readStream =fs.createReadStream (file) ;
ossObjects.uploadObject (bucketKey, fileKey, size, readStream, {}, function (error, data, response) {
...
}) ;
}) ;
Just remember that ossObjects is for 2 legged, where as Items, Versions are 3 legged.
We figured out how to get things working after some support from Adam Nagy. To put it simple we had to do everything by use of 3 legged OAuth since all operations involves a document from an A360 account. This includes accessing and showing the file structure, translating a document to SVF, starting the viewer and loading the document into the viewer.
Also, we were targeting the wrong id when trying to translate the document. This post shows how easily it can be done now, thanks to Adam for the info!

Overriding delete operation on Azure Mobile Services table

I'd like to override delete operation on my Azure Mobile Services table to make it more like update then real delete. I have additional column named IsDeleted and I'd like to set it's value to true when delete operation is executed.
I figured out, that what I need is:
fire my own 'update' inside del function,
delete current request.execute()
prepare and sent response by myself
That meens my del function should look like that:
function del(id, user, request) {
// execute update query to set 'isDeleted' - true
// return standard response
request.respond();
}
As you can see I'm missing the first part of the function - the update one. Could you help me writing it? I read Mobile Services server script reference but there is no info about making additional queries inside a server script function.
There are basically two ways to do that - using the tables object, and using the mssql object. The links point to the appropriate reference.
Using mssql (I didn't try it, you may need to update your SQL statement):
function del(id, user, request) {
var sql = 'UPDATE <yourTableName> SET isDeleted = true WHERE id = ?';
mssql.query(sql, [id], {
success: function() {
request.respond(statusCodes.OK);
}
});
}
Using tables (again, only tested in notepad):
function del(id, user, request) {
var table = tables.getTable('YourTableName');
table.where({ id: id }).read({
success: function(items) {
if (items.length === 0) {
request.respond(statusCodes.NOT_FOUND);
} else {
var item = items[0];
item.isDeleted = true;
table.update(item, {
success: function() {
request.respond(statusCodes.OK, item);
}
});
}
}
});
}
There is a Node.js driver for SQL Server that you might want to check out.
The script component of Mobile Services uses node.js. You might want to check out the session from AzureConf called Javascript, meet cloud

Resources