Facebook sdk for Unity: error - unityscript

As facebook just released it's new sdk for Unity. I m trying to use FB.API method and getting a lot of troubles with it. Like this is code I have written in UnityScript in my Unity project.
function LoginCallback() {
Debug.Log("User id is"+ FB.UserId);
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, LogCallback, null);
FBUtil.Log(FB.UserId); // Use this to sync progress, etc.
}
function LogCallback(response:String) {
// Debug.Log(response);
var profile = FBUtil.DeserializeJSONProfile(response);
var friends = FBUtil.DeserializeJSONFriends(response);
}
I am getting this error in Unity Log
BCE0005: Unknown identifier: 'FBUtil'.
And if I comment out the FBUtil part and just try to print the json string by writing this
function LoginCallback() {
Debug.Log("User id is"+ FB.UserId);
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, LogCallback, null);
}
function LogCallback(response:String) {
Debug.Log(response);
}
I am able to get Fb.UserId but I am not getting the response with the following details like first_name, friends. The error in DDMS Log is this
"09-04 21:35:04.534: E/Unity(23893): (Filename: ./Runtime/ExportGenerated/AndroidManaged/UnityEngineDebug.cpp Line: 54)
"
Someone help me out.

Related

How to properly handle Google SDK errors in Google App Script

I am writing a google web app which uses the Admin Directory a lot. However I was wondering how the error handling should be done since I do not get a proper error object back when a request to the api fails.
Example: I want to check if a custom schema exists and if not I want to do something else:
try{
var resp = AdminDirectory.Schemas.get("129898rgv", "someCustomSchema");
}catch(err){
// if schema does not exist do this
schemaNotExistFunction();
Logger.log(err);
}
Unfortunately I do not even get the http status code back from the err. Is there another way to handle errors in Google Apps Script?
Instead of
Logger.log(error)
use
Logger.log('%s, %s',error.message, error.stack);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error for a complete list of Error instance properties
The above because Logger.log parses the parameter as string. When you pass an error object error.name is logged, by the other hand by using
Example
Running the following code in an standalone project using the new runtime (V8) will log a couple of messages.
function myFunction() {
try{
SpreadsheetApp.getUi();
} catch (error) {
Logger.log(error);
Logger.log('%s, %s', error.message, error.stack);
}
}
Another alternative is to use console.log instead of Logger.log
function myFunction() {
try{
SpreadsheetApp.getUi();
} catch (error) {
console.log(error);
console.log('%s, %s', error.message, error.stack);
}
}

Issue with FCM Push Notification Android

I was able to receive push notifications some months ago, a day ago i started to work again on the app now the issue is it's not able to receive push notification. It does provide FCM token but onMessageReceived never gets called also if i try with Postman it gives an error of Mismatchsender ID, but the scenario here is a bit confusing. If i change the package name (after creating new project on console and added new goole-service.json file) it doesn't let me register for FCM token. i've stuck in this situation from last day. can anybody please help? what i'm doing wrong.
Here is implementaion of FCMToken
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseIIDService : FirebaseInstanceIdService
{
const string TAG = "MyFirebaseIIDService";
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
Log.Debug(TAG, "Refreshed token: " + refreshedToken);
SendRegistrationToServer(refreshedToken);
}
void SendRegistrationToServer(string token)
{
// Add custom implementation, as needed.
}
}
Here it gives me error if i change my package name to any other,
Error: Java.Lang.IllegalStateException: Default FirebaseApp is not
initialized in this process
try
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
// PushNotificationManager.Initialize(this, false);
} catch(Exception ee)
{
}
I've solved my issue with with customization of FirebaseInitialize after creating new project on Firebase here is my code. But one bad thing is here that when new token gets initialized it never gets called on FirebaseInstanceIdReceiver.
var options = new FirebaseOptions.Builder()
.SetApplicationId("<AppID>")
.SetApiKey("<ApiKey>")
.SetDatabaseUrl("<DBURl>")
.SetStorageBucket("<StorageBucket>")
.SetGcmSenderId("<SenderID>").Build();
var fapp = FirebaseApp.InitializeApp(this, options);

Various errors using VisionServiceClient in XamarinForms

I am trying to create a simple Xamarin forms app which allows the user to browse for or take a photo and have azure cognitive services tag the photo using a custom vision model.
I am unable to get the client to successfully authenticate or find a resource per the error message in the exception produced by the VisionServiceClient. Am I missing something? What would be the correct values to use for the arguments to VisionServiceClient?
All keys have been removed from the below images, they are populated.
Exception thrown in VS2017:
'Microsoft.ProjectOxford.Vision.ClientException' in System.Private.CoreLib.dll
Call to VisionServiceClient:
private const string endpoint = #"https://eastus2.api.cognitive.microsoft.com/vision/prediction/v1.0";
private const string key = "";
VisionServiceClient visionClient = new VisionServiceClient(key, endpoint);
VisualFeature[] features = { VisualFeature.Tags, VisualFeature.Categories, VisualFeature.Description };
try
{
AnalysisResult temp = await visionClient.AnalyzeImageAsync(imageStream,
features.ToList(), null);
return temp;
}
catch(Exception ex)
{
return null;
}
VS Exception Error:
Azure Portal for cognitive services:
Custom Vision Portal:
It looks like you're confusing the Computer Vision and the Custom Vision APIs. You are attempting to use the client SDK for the former using the API key of the latter.
For .NET languages, you'll want the Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction NuGet package.
Your code will end up looking something like this:
ICustomVisionPredictionClient client = new CustomVisionPredictionClient()
{
ApiKey = PredictionKey,
Endpoint = "https://southcentralus.api.cognitive.microsoft.com"
};
ImagePrediction prediction = await client.PredictImageAsync(ProjectId, stream, IterationId);
Thank you to cthrash for the extended help and talking with me in chat. Using his post along with a little troubleshooting I have figured out what works for me. The code is super clunky but it was just to test and make sure I'm able to do this. To answer the question:
Nuget packages and classes
Using cthrash's post I was able to get both the training and prediction nuget packages installed, which are the correct packages for this particular application. I needed the following classes:
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models
Endpoint Root
Following some of the steps Here I determined that the endpoint URL's only need to be the root, not the full URL provided in the Custom Vision Portal. For instance,
https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/
Was changed to
https://southcentralus.api.cognitive.microsoft.com
I used both the key and endpoint from the Custom Vision Portal and making that change I was able to use both a training and prediction client to pull the projects and iterations.
Getting Project Id
In order to use CustomVisionPredictionClient.PredictImageAsync you need a Guid for the project id and an iteration id if a default iteration is not set in the portal.
I tested two ways to get the project id,
Using project id string from portal
Grab the project id string from the portal under the project settings.
For the first argument to PredictImageAsync pass
Guid.Parse(projectId)
Using the training client
Create a new CustomVisionTrainingClient
To get a list of <Project> use
TrainingClient.GetProjects().ToList()
In my case I only had a single project so I would just need the first element.
Guid projectId = projects[0].Id
Getting Iteration Id
To get the iteration id of a project you need the CustomVisionTrainingClient.
Create the client
To get a list of <Iteration> use
client.GetIterations(projectId).ToList()
In my case I had only a single iteration so I just need the first element.
Guid iterationId = iterations[0].Id
I am now able to use my model to classify images. In the code below, fileStream is the image stream passed to the model.
public async Task<string> Predict(Stream fileStream)
{
string projectId = "";
//string trainingEndpoint = "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.2/Training/";
string trainingEndpoint = "https://southcentralus.api.cognitive.microsoft.com/";
string trainingKey = "";
//string predictionEndpoint = "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/";
string predictionEndpoint = "https://southcentralus.api.cognitive.microsoft.com";
string predictionKey = "";
CustomVisionTrainingClient trainingClient = new CustomVisionTrainingClient
{
ApiKey = trainingKey,
Endpoint = trainingEndpoint
};
List<Project> projects = new List<Project>();
try
{
projects = trainingClient.GetProjects().ToList();
}
catch(Exception ex)
{
Debug.WriteLine("Unable to get projects:\n\n" + ex.Message);
return "Unable to obtain projects.";
}
Guid ProjectId = Guid.Empty;
if(projects.Count > 0)
{
ProjectId = projects[0].Id;
}
if (ProjectId == Guid.Empty)
{
Debug.WriteLine("Unable to obtain project ID");
return "Unable to obtain project id.";
}
List<Iteration> iterations = new List<Iteration>();
try
{
iterations = trainingClient.GetIterations(ProjectId).ToList();
}
catch(Exception ex)
{
Debug.WriteLine("Unable to obtain iterations.");
return "Unable to obtain iterations.";
}
foreach(Iteration itr in iterations)
{
Debug.WriteLine(itr.Name + "\t" + itr.Id + "\n");
}
Guid iteration = Guid.Empty;
if(iterations.Count > 0)
{
iteration = iterations[0].Id;
}
if(iteration == Guid.Empty)
{
Debug.WriteLine("Unable to obtain project iteration.");
return "Unable to obtain project iteration";
}
CustomVisionPredictionClient predictionClient = new CustomVisionPredictionClient
{
ApiKey = predictionKey,
Endpoint = predictionEndpoint
};
var result = await predictionClient.PredictImageAsync(Guid.Parse(projectId), fileStream, iteration);
string resultStr = string.Empty;
foreach(PredictionModel pred in result.Predictions)
{
if(pred.Probability >= 0.85)
resultStr += pred.TagName + " ";
}
return resultStr;
}

cordova record audio not work windows 10 mobile

I work for some time with the media cordova plugin on android and ios mobile on to record audio files. It works well. However on windows, while recording no error occurred, but no file exists. Just when the application goes into background and we return it, an error with code like 2147483648 (I have not found any information relevant to my problem with this code).
function recordAudio() {
var src = "ms-appdata:///temp/sound.m4a";;
var mediaRec = new Media(src,
// success callback
function() {
console.log("recordAudio():Audio Success");
},
// error callback
function(err) {
console.log("recordAudio():Audio Error: "+ err.code);
});
// Record audio
mediaRec.startRecord();
}
I can not find solutions or similar problems. The rest github does not included the problems.
In MediaProxy.js (plugins/cordova-plugin-media/mediaProxy.js)
There is this constant:
var PARAMETER_IS_INCORRECT = -2147024809;
Is this the error you are getting? If so, this only seems to be used in one place, if there is no scheme for the path. Take a look at setTemporaryFsByDefault() in that same file.

Issue deleting Google Shared Contact

I've been able to successfully add a contact via the API but I can't delete contacts that I've created.
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/shared-contacts
function deletecontact()
{
SharedContactsApp.setOAuth2AccessToken(getSharedContactsService().getAccessToken ());
var contacts = SharedContactsApp.getContactById('5c8b05ab8c9f68c6');
SharedContactsApp.deleteContact('5c8b05ab8c9f68c6');
}
I get the following error message:
TypeError: Cannot call method "getElements" of undefined. (line 200, file "Code", project "SharedContactsApp")
How to remove this error?
Additionally...
I've tried to set a Job Title using the code below but get the following error:
ReferenceError:"profile" is not defined. (line 142, file "Code")
function changeJobTitle2()
{
SharedContactsApp.setOAuth2AccessToken(getSharedContactsService().getAccessToken ());
var contact = SharedContactsApp.getContactById('82f05968956d66f');
profile.setJobTitle('Google Apps Expert');
}
I figured it out.
function hailmary()
{
SharedContactsApp.setOAuth2AccessToken(getSharedContactsService().getAccessToken());
var contact = SharedContactsApp.getContactById('82f05968956d66f');
SharedContactsApp.deleteContact(contact)
}

Resources