How execute a FQL Insights query with Facebook Graph API - facebook-graph-api

I try without success to execute a FQL query using Graph API to get the value of Insights counters.
Does anyone know how I can do this?
I use "Facebook C# SDK" version 5.4.1, C# 4.0.
If I use C# sample code provided in the documentation
var fb = new FacebookClient(m_accessToken);
dynamic result = fb.Query("SELECT name, uid FROM user WHERE uid= me()");
I receive a good response
{"name":"","uid":100002632407830}
With the same syntax, If I request "pages_fans" Insights counter and use library 5.4.1
var fb = new FacebookClient(m_accessToken);
dynamic result = fb.Query("SELECT metric, value FROM insights WHERE object_id=6176018219 AND metric='page_fans' AND end_time=end_time_date('2011-12-31') AND period=period('lifetime')");
I receive always an empty response
{[]}
With the same code but with library 5.2.1
I receive always a good response
{[{"metric":"page_fans","value":"125535"}]}
It is the same problem described here : Error with FQL query with library 5.4.1 but with another syntax.
Currently I use FQL Insights queries using REST API (with libary 5.2.1) but I want to migrate to FQL Insights queries using the Graph API (with library 5.4.1) because the REST API is deprecated.
Where is the bug:
In my syntax request?
In the "Facebook C# SDK" library?
On Facebook server?
Best regards.

I made a request with the Facebook Graph API Explorer
https://graph.facebook.com/fql?q=SELECT metric, value FROM insights
WHERE object_id=6176018219 AND metric='page_fans' AND
end_time=end_time_date('2011-12-31') AND period=period('lifetime')
I receive always an empty response.
{
"data": [
]
}
It is a Facebook's bug.
A bug was created about it on Facebook : http://developers.facebook.com/bugs/232510993491615?browse=search_4f08c675cce9d2265724293

I found another way to retrieving the info which works reliably
I found another way of retrieving insights which seems to be reliable.
documentation found here http://developers.facebook.com/docs/reference/api/insights/.
with more options to allow format and period changes - below example.
https://graph.facebook.com/2439131959/insights/application_active_users/[period]?format=json&since=[timestamp]&until=[timestamp]&access_token=[access_token]
period is day, month, week, lifetime.
timestamp has to be a valid PST midnight only.
access_token = could be.
1. nothing for the metrics that don't need permission.
2. app_id|secret_code or
3. your authentication token granted that you have access to the insight data of the application or pages (ie owner or insight users).
C# sdk example:
FacebookClient fbClient = new FacebookClient([appID], [secret]);
DateTime untilDate= (new DateTime([Now].Year, [Now].Month, [Now].Day));
DateTime sinceDate= (new DateTime([Now].Year, [Now].Month, [Now].Day)).AddDays(-1);
TimeSpan t = (untilDate- new DateTime(1970, 1, 1));
int timestampUntil = (int)t.TotalSeconds;
t = (sinceDate- new DateTime(1970, 1, 1));
int timeStampSince = (int)t.TotalSeconds;
var result = (IDictionary<string, object>)fbClient.Get([appID] + "/insights/" + [metricID] + "/" + [period] + "?format=json&since="+timeStampSince+"&until="+timestampUntil );
Console.WriteLine(result["data"]);

Make sure you have the correct permissions when you get your Access Token
<fb:login-button perms="read_insights"></fb:login-button>

This issue related to Facebook C# SDK.
Probably best thing you can do is file a bug on codeplex, and replace usage of end_time_date to "time in seconds" and period to "lifetime".

Related

Where to find sample C# .NET code for Google's People API?

I have an installed app that uses .NET and the Contacts API. I'm trying to convert to the People API. I'm having trouble getting started and finding a sample that shows how to use People API with the .NET library. For example, the samples listed under the Peoples API documentation doesn't include .NET. Where can I find a .NET sample for the People API?
Start with this ;)
https://googleapis.dev/dotnet/Google.Apis.PeopleService.v1/latest/api/Google.Apis.PeopleService.v1.html
Get the nuget called Google.Apis.PeopleService.v1 https://github.com/googleapis/google-api-dotnet-client
Also, I'm sure you have seen this https://developers.google.com/people/v1/profiles
It has some .net examples.
What exactly are you trying to accomplish?
I am just about to complete converting an app that used contacts API to people API using a service account for the company.
ps. I can't copy the whole namespace in the answer hense answer with a link.
Edited: 20210608
Person person = new Person();
person.EmailAddresses = new List<EmailAddress>();
person.EmailAddresses.Add(new EmailAddress() { Type = "work", Value = "sample#domain.com" });
person.Names = new List<Name>();
person.Names.Add(new Name() { FamilyName = "Lname2", GivenName = "Fname" });
// link to peopleService code can be found in the comments
// it's basically initializing PeopleServiceService with service account credentials
Person retVal = peopleService.People.CreateContact(person).Execute();

PowerBI Failed to execute 'atob' on 'Window' in parsePowerBIAccessToken

Randomly today my powerbi embedded code has been throwing:
DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
at window.atob (eval at <anonymous> (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1326:504), <anonymous>:1:83)
at e.parsePowerBIAccessToken (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:2331307)
at e.isTokenTenantValid (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:2331046)
at t.isPowerBIAccessTokenValid (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:31523)
at t.promptForLogin (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:31233)
at m.scope.promptForLogin (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:25515)
at fn (eval at compile (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1444:307), <anonymous>:4:374)
at m.$digest (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1350:310)
at https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:1626830
at t.i [as _next] (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:189984)
I checked the access token and they appear valid. (No different to the ones working yesterday). I added a debug hook into window.atob and it seems like something inside of parsePowerBIAccessToken is passing undefined to atob. I can't figure out why though unless this code changed.
Kind of stuck on how to figure out the issue. (Not helping that Chrome seems to struggle to debug the lines without crashing).
The code path is trying to run the embed token through this code:
e.prototype.parsePowerBIAccessToken = function() {
return JSON.parse(atob(i.powerBIAccessToken.split(".")[1]))
}
Odd because the code is clearly using "tokenType: models.TokenType.Embed," and thus probably shouldn't be going down that code path?
I noticed it works if I'm logged into the MS account though, so it's using cookies.
If you copy and paste the embed URL from a report it'll have autoAuth=true in the URL. You must remove this from the embed URL or it attempts to use your cookies to authenticate. (It'll also try to use the embed token like an access token and execute wrong code, so that's MS's bug).
In my JS code I removed the autoAuth from the embed url and it'll skip trying to use cookies.
embedURL = embedURL.replace(/autoAuth=true&/ig, '');
You should always get the embed URL using the REST APIs.
From the embed for your customers (Embed Token) documentation
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;
// You need to provide the workspaceId where the dashboard resides.
ODataResponseListReport reports = await client.Reports.GetReportsInGroupAsync(workspaceId);
// Get the first report in the group.
Report report = reports.Value.FirstOrDefault();
// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Reports.GenerateTokenInGroup(workspaceId, report.Id, generateTokenRequestParameters);
// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
EmbedToken = tokenResponse,
EmbedUrl = report.EmbedUrl,
Id = report.Id
};
You get the embed URL from the Report object.
The URL you got from powerbi.com is powerbi secure embed and it is not recommended to use this URL for another scenario.
We raised this issue with the PowerBI team. You are supposed to use an API call to get the embed URL for a report. There is an API tester here: https://learn.microsoft.com/en-us/rest/api/power-bi/reports/getreportingroup
Here is a playground for testing embedding: https://microsoft.github.io/PowerBI-JavaScript/demo/v2-demo/index.html

The App Insights API is deprecated and will stop working - What are the alternatives?

As of version 3.0 the App Insights API is deprecated.
Unfortunately I rely heavily on the app_event node to fetch information about the revenue. The code for that looks like this:
requests.request(
"GET",
"https://graph.facebook.com/v2.12/" + str(app_id) + "/app_insights/app_event/",
params={
"since":d1.strftime("%s"),
"until":d2.strftime("%s"),
"summary":"true",
"event_name":"fb_ad_network_revenue",
"aggregateBy": "SUM",
"breakdowns[0]":"placement",
"access_token": app_access_token
}
)
For new Apps I can't use this code anymore because the Graph API does not support it anymore:
The app tried to call version v2.12. This app can only call versions
v3.0 and higher, so the request defaulted to version v3.0.
How could I possibly port my code to version 3.0?
I ran into this problem as well. It looks like you can use the adnetworkanalytics endpoint now for this query. The parameters and data returned are of course slightly different than the app_event endpoint. Hurray for progress I guess.
Here are the docs:
https://developers.facebook.com/docs/audience-network/reporting-api

Failing to fetch CategorizedFacebookType

I have an application which I developed about a year ago and I'm
fetching facebook accounts like this:
facebookClient = new DefaultFacebookClient(access_token);
Connection<CategorizedFacebookType> con = facebookClient.fetchConnection("me/accounts", CategorizedFacebookType.class);
fbAccounts = con.getData();
It worked fine until about a month ago, but now it returns the
fbAccounts list empty. Why is that?
I was hoping moving from restfb-1.6.2.jar to restfb-1.6.9.jar would
help but no luck, it comes up empty on both.
What am I missing?
EDIT, to provide the code for another error I have with this API. The following code used to work:
String id = page.getFbPageID(); // (a valid facebook page id)
FBInsightsDaily daily = new FBInsightsDaily(); // an object holding some insights values
try {
Parameter param = Parameter.with("asdf", "asdf"); // seems like the param is required
JsonObject allValues = facebookClient.executeMultiquery(createQueries(date, id), JsonObject.class, param);
daily.setPageActiveUsersDaily((Integer)(((JsonArray)allValues.opt("page_active_users_daily")).getJsonObject(0)).opt("value"));
...
This throws the following exception:
com.restfb.json.JsonException: JsonArray[0] not found.
at com.restfb.json.JsonArray.get(JsonArray.java:252)
at com.restfb.json.JsonArray.getJsonObject(JsonArray.java:341)
Again, this used to work fine but now throws this.
You need the manage_pages permission from the user to access their list of adminned pages - a year ago I'm not sure you did - check that you're obtaining that permission from your users
{edit}
Some of the insights metrics were also deprecated, the specific values you're checking may no longer exist - https://developers.facebook.com/docs/reference/fql/insights/ should have the details of what is available now
Try to check your queries manually in the Graph API Explorer to eliminate any issues in your code and hopefully get more detailed error messages that your SDK may be swallowing

Upload file to SharePoint WSS 3.0 with WebRequest PUT

Hey, I've got this nice little piece of code, much like all the other versions of this method of upload using WSS WebServices. I've got one major problem though - once I have uploaded a file into my doc list, and updated the list item to write a comment/description, the file is stuck there. What I mean is that this method will not overwrite the file once I've uploaded it. Nobody else out there seems to have posted this issue yet, so .. anyone?
I have another version of the method which uses a byte[] instead of a Stream .. same issue though.
Note: I have switched off the 'require documents to be checked out before they can be edited' option for the library. No luck tho .. The doc library does have versioning turned on though, with a major version being created for each update.
private void UploadStream(string fullPath, Stream uploadStream)
{
WebRequest request = WebRequest.Create(fullPath);
request.Credentials = CredentialCache.DefaultCredentials; // User must have 'Contributor' access to the document library
request.Method = "PUT";
request.Headers.Add("Overwrite", "t");
byte[] buffer = new byte[4096];
using (Stream stream = request.GetRequestStream())
{
for (int i = uploadStream.Read(buffer, 0, buffer.Length); i > 0; i = uploadStream.Read(buffer, 0, buffer.Length))
{
stream.Write(buffer, 0, i);
}
}
WebResponse response = request.GetResponse(); // Upload the file
response.Close();
}
Original credits to: http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html
EDIT -- major finding .. when I call it from my nUnit test project it works fine. It seems it only fails when I call it from my WCF application (nUnit running under logged on user account, WCF app has app pool running under that same user -- my account, which also has valid permissions in SharePoint).
Nuts. "Now where to start?!", I muses to myself.
SOLVED -- I found a little bug - the file was being created in the right place, but the update path was wrong.. I ended up finding a folder full of files with many, many new versions.. doh!
Why not use the out-of-the-box SharePoint webservice, Lists.asmx? You'll find it in
http://SITEURL/___vti_bin/Lists.asmx
Edit, I checked out the link and it seems you are calling the out of the box web service. This has got be versioning related then. Can you check out the different versions that exist in the doc lib of the specific file? see if it perhaps gets added as a minor version through the service?
Have you tried using a capital T? SharePoint's webdav header processing is not very likely to be case-sensitive, but the protocol does specify a capital T. Oh, and what is the response? A 412 error code or something altogether different?