Calling Firebase Function from Unity throws error - javascript

I am having problems with my Unity3D calling Firebase Functions function. My code is actually copied from https://firebase.google.com/docs/functions/callable.
My function code is following: (just copied this file actually)
https://github.com/firebase/quickstart-js/blob/a579893cfa33121952aeed9069c1554ed4e65b7e/functions/functions/index.js#L44-L50
and in Unity I have this:
//Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = "message";
data["push"] = true;
//Call the function and extract the operation from the result.
var function = FirebaseFunctions.DefaultInstance.GetHttpsCallable("addMessage");
function.CallAsync(data).ContinueWith((task) => {
if (task.IsFaulted)
{
foreach (var inner in task.Exception.InnerExceptions)
{
if (inner is FunctionsException)
{
Debug.Log(inner.Message);
}
}
}
else
{
Debug.Log("Finished: " + task.Result.Data);
}
});
But I am getting this result:
Response is not valid JSON object.
What am I doing wrong?
Thank you for your help!!!

I was still working on that problem and suddenly it worked. I dont know why to be honest, because the could looks exactely the same and I did not change anything on that.

Related

Javascript - cannot pass classes's function return into classes's variable

I program usually in python and I am trying something that usually works in python. I have a function in a class. Its a callback function of mqtt library. What I want is to save the message(in a function onMessageArrived) that I receive into class variable called (this.)buffer.
class sub{
constructor(hostname,port,clientid,topic){
this.buffer = [];
this.hostname=hostname;
this.port=port;
this.clientid = clientid;
this.topic = topic;
this.client = new Paho.MQTT.Client(hostname,port, clientid);
// set callback handlers
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived; <----Problem
// connect the client
this.client.connect({onSuccess:this.onConnect});
}
onConnect(){
console.log('OnConnect');
}
onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
this.buffer.push(message.payloadString) <-------------Problem
}
subs(){
this.client.subscribe(this.topic)
}
publ(message){
var mg = new Paho.MQTT.Message(message);
mg.destinationName = this.topic;
this.client.send(mg);
}
}
Problem is that function onMessageArrived doesnt push message into this.buffer variable-it looks like the function has no idea its inside class and therefore I cannot access class variable through 'this.'. In python it works this way. I am quite desperate because I looks to me like that function is totaly isolated and there is no other way than just print the message.
the error:
onConnectionLost:AMQJS0005E Internal error. Error Message: Cannot read
property 'push' of undefined, Stack trace: TypeError: Cannot read property
'push' of undefined
Thanks in advance

Word add-in: Get whole document but File.getSliceAsync method not returning

I'm creating an Office Add-in and am having trouble with the javascript file.getFileAsync method in Word Online (Word 2013 desktop is fine).
I'm using sample code from github...
https://github.com/OfficeDev/office-js-docs/blob/master/docs/word/get-the-whole-document-from-an-add-in-for-powerpoint-or-word.md
My code looks like this...
function getFile() {
Office.context.document.getFileAsync(Office.FileType.Text,
{ sliceSize: 65536},
function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
// Get the File object from the result.
var myFile = result.value;
var state = {
file: myFile,
counter: 0,
sliceCount: myFile.sliceCount
};
getSlice(state);
}
});
}
function getSlice(state) {
state.file.getSliceAsync(state.counter, function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
sendSlice(result.value, state);
state.file.closeAsync();
}
else if(result.status == 'failed')
state.file.closeAsync();
});
}
Before calling file.getSliceAsync the data looks good - myFile.sliceCount is 1. The result function is never called and no errors are thrown in the console.
Thanks for any help you can provide!
UPDATE: this issue is fixed and live. Please try it again it must work now.
thanks!
---------------- ORIGINAL ANSWER JUST FOR REFERENCE ----------------------------
Yes, there is a regression right now in Word Online preventing the code to run successfully. The specific issue is that the file.getSliceAsync method is never calling the call-back function. This only happens with the TEXT type, if you want to get the docx or pdf this should work ok. This issue will be fixed in a couple of weeks.
You have an alternative if you want to get the text of the document you can use the new APIs for Word check out this sample:
Word.run(function(context) {
var myBody = context.document.body;
context.load(myBody);
return context.sync()
.then(function(){
console.log(myBody.text);
});
});
Hope this helps!
Thanks for reporting this issue!
Juan.

Breeze Partial initializer

I have a Single Page Application that is working pretty well so far but I have run into an issue I am unable to figure out. I am using breeze to populate a list of projects to be displayed in a table. There is way more info than what I actually need so I am doing a projection on the data. I want to add a knockout computed onto the entity. So to accomplish this I registered and entity constructor like so...
metadataStore.registerEntityTypeCtor(entityNames.project, function () { this.isPartial = false; }, initializeProject);
The initializeProject function uses some of the values in the project to determine what the values should be for the computed. For example if the Project.Type == "P" then the rowClass should = "Red".
The problem I am having is that all the properties of Project are null except for the ProjNum which happens to be the key. I believe the issue is because I am doing the projection because I have registered other initializers for other types and they work just fine. Is there a way to make this work?
EDIT: I thought I would just add a little more detail for clarification. The values of all the properties are set to knockout observables, when I interrogate the properties using the javascript debugger in Chrome the _latestValue of any of the properties is null. The only property that is set is the ProjNum which is also the entity key.
EDIT2: Here is the client side code that does the projection
var getProjectPartials = function (projectObservable, username, forceRemote) {
var p1 = new breeze.Predicate("ProjManager", "==", username);
var p2 = new breeze.Predicate("ApprovalStatus", "!=", "X");
var p3 = new breeze.Predicate("ApprovalStatus", "!=", "C");
var select = 'ProjNum,Title,Type,ApprovalStatus,CurrentStep,StartDate,ProjTargetDate,CurTargDate';
var isQaUser = cookies.getCookie("IsQaUser");
if (isQaUser == "True") {
p1 = new breeze.Predicate("QAManager", "==", username);
select = select + ',QAManager';
} else {
select = select + ',ProjManager';
}
var query = entityQuery
.from('Projects')
.where(p1.and(p2).and(p3))
.select(select);
if (!forceRemote) {
var p = getLocal(query);
if (p.length > 1) {
projectObservable(p);
return Q.resolve();
}
}
return manager.executeQuery(query).then(querySucceeded).fail(queryFailed);
function querySucceeded(data) {
var list = partialMapper.mapDtosToEntities(
manager,
data.results,
model.entityNames.project,
'ProjNum'
);
if (projectObservable) {
projectObservable(list);
}
log('Retrieved projects using breeze', data, true);
}
};
and the code for the partialMapper.mapDtosToEntities function.
var defaultExtension = { isPartial: true };
function mapDtosToEntities(manager,dtos,entityName,keyName,extendWith) {
return dtos.map(dtoToEntityMapper);
function dtoToEntityMapper(dto) {
var keyValue = dto[keyName];
var entity = manager.getEntityByKey(entityName, keyValue);
if (!entity) {
extendWith = $.extend({}, extendWith || defaultExtension);
extendWith[keyName] = keyValue;
entity = manager.createEntity(entityName, extendWith);
}
mapToEntity(entity, dto);
entity.entityAspect.setUnchanged();
return entity;
}
function mapToEntity(entity, dto) {
for (var prop in dto) {
if (dto.hasOwnProperty(prop)) {
entity[prop](dto[prop]);
}
}
return entity;
}
}
EDIT3: Looks like it was my mistake. I found the error when I looked closer at initializeProject. Below is what the function looked like before i fixed it.
function initializeProject(project) {
project.rowClass = ko.computed(function() {
if (project.Type == "R") {
return "project-list-item info";
} else if (project.Type == "P") {
return "project-list-item error";
}
return "project-list-item";
});
}
the issue was with project.Type I should have used project.Type() since it is an observable. It is a silly mistake that I have made too many times since starting this project.
EDIT4: Inside initializeProject some parts are working and others aren't. When I try to access project.ProjTargetDate() I get null, same with project.StartDate(). Because of the Null value I get an error thrown from the moment library as I am working with these dates to determine when a project is late. I tried removing the select from the client query and the call to the partial entity mapper and when I did that everything worked fine.
You seem to be getting closer. I think a few more guard clauses in your initializeProject method would help and, when working with Knockout, one is constantly battling the issue of parentheses.
Btw, I highly recommend the Knockout Context Debugger plugin for Chrome for diagnosing binding problems.
Try toType()
You're working very hard with your DTO mapping, following along with John's code from his course. Since then there's a new way to get projection data into an entity: add toType(...) to the end of the query like this:
var query = entityQuery
.from('Projects')
.where(p1.and(p2).and(p3))
.select(select)
.toType('Project'); // cast to Project
It won't solve everything but you may be able to do away with the dto mapping.
Consider DTOs on the server
I should have pointed this out first. If you're always cutting this data down to size, why not define the client-facing model to suit your client. Create DTO classes of the right shape(s) and project into them on the server before sending data over the wire.
You can also build metadata to match those DTOs so that Project on the client has exactly the properties it should have there ... and no more.
I'm writing about this now. Should have a page on it in a week or so.

Javascript Variable Sometimes Undefined

I know this question has been asked several times, but I couldn't seem to find a solution that worked for me in any of the previous questions. I have a variable that gets set when my HTML page is done loading, but sometimes when my code tries to access that variable, it says that it is undefined. I'm not sure why, since I believe I am waiting for everything to load properly. This exception seems to happen randomly, as most of the time all the code runs fine. Here's a simplified version of my code:
var globalVar;
function initStuff(filePath) {
// I wait till the HTML page is fully loaded before doing anything
$(document).ready(function(){
var video = document.getElementById("videoElementID");
// My parseFile() function seems to run smoothly
var arrayOfStuff = parseFile(filePath);
if (arrayOfStuff == null) {
console.error("Unable to properly parse the file.");
} else {
setGlobalVariable(arrayOfStuff);
video.addEventListener("play", updateVideoFrame, false);
}
});
}
function setGlobalVariable(arrayOfStuff) {
window.globalVar = arrayOfStuff;
}
function updateVideoFrame() {
// A bunch of other code happens first
// This is the line that fails occasionally, saying
// "window.globalVar[0].aProperty.anArray[0] is undefined"
var test = window.globalVar[0].aProperty.anArray[0].aProperty;
}
The only thing that I can think of that might be causing this problem is some sort of synchronicity issue. I don't see why that would be the case, though. Help please!
Edit:
In case the asynchronicity issue is coming from my parseFile(xmlFile) method, here is what I'm doing there. I thought it couldn't possibly be causing the issue, since I force the method to happen synchronously, but in case I'm wrong, here it is:
function parseKML(xmlFile) {
var arrayOfStuff = new Array();
// Turn the AJAX asynchronicity off for the following GET command
$.ajaxSetup( { async : false } );
// Open the XML file
$.get(xmlFile, {}, function(xml) {
var doc = $("Document", xml);
// Code for parsing the XML file is here
// arrayOfStuff() gets populated here
});
// Once I'm done processing the XML file, I turn asynchronicity back on, since that is AJAX's default state
$.ajaxSetup( { async : true } );
return arrayOfStuff;
}
The first thing you should do in your code is figure out which part of:
window.globalVar[0].aProperty.anArray[0]
is undefined.
Since you have multiple chained property references and array references, it could be many different places in the chain. I'd suggest either set a breakpoint right before your reference it examine what's in it or use several console.log() statement sto output each nested piece of the structure in order to find out where your problem is.
console.log("globalVar = " + globalVar);
console.log("globalVar[0] = " + globalVar[0]);
console.log("globalVar[0].aProperty = " + globalVar[0].aProperty);
console.log("globalVar[0].aProperty.anArray = " + globalVar[0].aProperty.anArray);
console.log("globalVar[0].aProperty.anArray[0] = " + globalVar[0].aProperty.anArray[0]);
If the problem is that globalVar isn't yet set, then you have a timing problem or an initialization problem.
If the problem is that one of the other properties isn't set, then you aren't initializing globalVar with what you think you are.
You may also want to write your code more defensibly so it fails gracefully if some of your data isn't set properly.
You need to use defensive programming.
http://www.javascriptref.com/pdf/ch23_ed2.pdf
Example:
var video = document.getElementById("videoElementID") || 0;
-
if( video && video.addEventListener ){
video.addEventListener("play", updateVideoFrame, false);
}
Here's another version of your code.
window.globalVar = globalVar || [];
function setGlobalVariable(arrayOfStuff) {
window.globalVar = arrayOfStuff;
}
function updateVideoFrame() {
// A bunch of other code happens first
// This is the line that fails occasionally, saying
// "window.globalVar[0].aProperty.anArray[0] is undefined"
if( window.globalVar ){
var g = window.globalVar || [];
var d = (g[0] || {})["aProperty"];
// etc...
}else{
console.error( "test error." );
}
}
function initStuff(filePath) {
// I wait till the HTML page is fully loaded before doing anything
$(document).ready(function () {
var video = $("#videoElementID");
// My parseFile() function seems to run smoothly
var arrayOfStuff = parseFile(filePath) || [];
if (arrayOfStuff == null || video == null ) {
console.error("Unable to properly parse the file.");
} else {
setGlobalVariable(arrayOfStuff);
video.bind("play", updateVideoFrame);
}
});
}

JS: Using variable names to call function

Im working with jQuery. I have an app that makes ajax requests to server that responds with JSON.
in some cases the response from the server will indicate the name of a JS function to be called
{"responseType":"callback", "callback":"STUFF.TestCallback","callbackData":"this is in the callback"}
If the responseType is "callback" as above the JSON is passed to a function to handle this response type. (the var "response" contains the JSON above)
STUFF.callback = function(response){
if(typeof response.callback =='function'){
console.log("All Good")
response.callback(response);
}else{
console.log("Hmm... Cant find function",response.callback );
}
}
STUFF.TestCallBack = function(data){
alert("it worked");
}
But when I do this I get the error "response.callback is not a function".
Any comments on why this is not working and how to do this properly would be greatly appreciated.
A String is a String, not a Function.
response.callback() doesn't work because it is the same as "STUFF.TestCallback"() not STUFF.TestCallback()
You probably want to have the data structured something more like "callback": "TestCallback" then then do:
STUFF[response.callback](response);
Here you use the String to access a property of STUFF. (foo.bar and foo['bar'] being equivalent.)
You could transform that "namespace.func" into a call like this:
STUFF.callback = function(response) {
var fn = response.callback.split("."), func = window;
while(func && fn.length) { func = func[fn.shift()]; }
if(typeof func == 'function') {
console.log("All Good")
func(response);
} else{
console.log("Hmm... Cant find function", response.callback);
}
}
What this does it grab the function by getting window["STUFF"] then window["STUFF"]["TestCallback"] as it loops, checking if each level is defined as it goes to prevent error. Note that this works for any level function as well, for example "STUFF.One.Two.func" will work as well.
You propably could do
var myfunction = eval(response.callback);
myfunction(response);
although using eval() is considered as a bad style by some javascript developers.

Categories

Resources