I have a command line application which executes a query. Here is the code.
Problem is that it receives an access token of the form "abc...|xyz...". There is
no session portion. But the token returned is useless for executing my query to
select insights for a page of mine. Help !!
const string permissions = "manage_pages,read_insights,offline_access";
dynamic oauthClient = new FacebookOAuthClient() ;
oauthClient.AppId = username ;
oauthClient.AppSecret = password ;
dynamic parameters = new ExpandoObject() ;
parameters.scope = permissions ;
parameters.response_type = "token" ;
// parameters.grant_type = "client_credentials" ;
dynamic result = oauthClient.GetApplicationAccessToken(parameters);
string token = result.access_token ;
// token comes back as "abc...|xyz..."
var fb = new FacebookClient(token);
string query = " select metric, value " +
" from insights " +
" where object_id = MY_PAGE and " +
" metric in ( 'page_impressions' , 'page_stories') and " +
" end_time >= end_time_date('2012-02-21') and " +
" end_time <= end_time_date('2012-02-11') and " +
" period = period('day') " ;
dynamic result2 = fb.Query(query) ; // Exception generated on this line.
return result2 ;
Any ideas?
The error you are getting is from Facebook and it is simply saying you don't have a valid token to make the request. You must request a user access token using OAuth. After you have a valid access token you can make your request with the following code:
var fb = new FacebookClient("valid_user_access_token");
string query = "YOUR FQL QUERY HERE";
dynamic result = fb.Query(query);
To learn how to get a valid access token read the Facebook documentation here: https://developers.facebook.com/docs/authentication/
Related
Is there a way to export multiple SQL tables as csv by issuing specific queries from cloud-sql.
Below is the code i currently have. When I call the exportTables for multiple tables back to back, I see a 409 error. It's probably becaause cloud-sql instance is busy with an export and it's not allowing subsequent export request.
How can I get this to work ? What would be the ideal solution here.
private void exportTables(String table_name, String query)
throws IOException, InterruptedException {
HttpClient httpclient = new HttpClient();
PostMethod httppost =
new PostMethod(
"https://www.googleapis.com/sql/v1beta4/projects/"
+ "abc"
+ "/instances/"
+ "zxy"
+ "/export");
String destination_bucket =
String.join(
"/",
"gs://" + "test",
table_name,
DateTimeUtil.getCurrentDate() + ".csv");
GoogleCredentials credentials =
GoogleCredentials.getApplicationDefault().createScoped(SQLAdminScopes.all());
AccessToken access_token = credentials.refreshAccessToken();
access_token.getTokenValue();
httppost.addRequestHeader("Content-Type", "application/json");
httppost.addRequestHeader("Authorization", "Bearer " + access_token.getTokenValue());
String request =
"{"
+ " \"exportContext\": {"
+ " \"fileType\": \"CSV\","
+ " \"uri\":\""
+ destination_bucket
+ "\","
+ " \"databases\": [\""
+ "xyz"
+ "\"],"
+ " \"csvExportOptions\": {"
+ " \"selectQuery\": \""
+ query
+ "\""
+ " }\n"
+ " }"
+ "}";
httppost.setRequestEntity(new StringRequestEntity(request, "application/json", "UTF-8"));
httpclient.executeMethod(httppost);
if (httppost.getStatusCode() > 200) {
String response = new String(httppost.getResponseBody(), StandardCharsets.UTF_8);
if (httppost.getStatusCode() != 409) {
throw new RuntimeException(
"Exception occurred while exporting the table: " + table_name + " Error " + response);
} else {
throw new IOException("SQL instance seems to be busy at the moment. Please retry");
}
}
httppost.releaseConnection();
logger.info("Finished exporting table {} to {}", table_name, destination_bucket);
}
I don't have suggestion to fix the issue on Cloud SQL directly, but a solution to execute in sequence the export thanks to a new tool: Workflow
Define the data format that you want, in JSON, to define ONE export.
Then provide an array of configuration to your workflow
In this workflow,
Make a loops on the configuration array
Perform an API call to Cloud SQL to generate the export on each configuration
Get the answer of the API Call, you have the jobId
Sleep a while
Check if the export is over (with the jobId).
If not, sleep and check again
If yes, loop (and thus start the next export)
It's serverless and the free tier makes this use case free.
The backend of my application makes a request to:
https://graph.facebook.com/v2.8/me?access_token=<firebase-access-token>&fields=id,name,first_name,birthday,email,picture.type(large){url}&format=json&method=get&pretty=0&suppress_http_code=1
I get a successful (200) response with the JSON data I expect and picture field as such:
"picture": {
"data": {
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=<asid>&height=200&width=200&ext=<ext>&hash=<hash>"
}
}
(where in place of <asid> and <ext>, there are numbers and <hash> is some alphanumeric string).
However, when I make a GET request to the platform-lookaside URL above, I get a 404 error.
It's been happening every time since my very first graph.facebook request for the same user. The very first one returned a platform-lookaside URL which pointed to a proper image (not sure if this is simply coincidence).
Is there something I'm doing wrong or is this likely a bug with the Facebook API?
FB currently seems to have issues with some CDNs and therefore your issue might be only temporary. You should also see missing/broken images on some places on fb dot com. Worst time to debug your issue :)
Try this code it worked for me
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
try {
String name = object.getString("name");
String email = object.getString("email");
String last_name = object.getString("last_name");
String first_name = object.getString("first_name");
String middle_name = object.getString("middle_name");
String link = object.getString("link");
String picture = object.getJSONObject("picture").getJSONObject("data").getString("url");
Log.e("Email = ", " " + email);
Log.e("facebookLink = ", " " + link);
Log.e("name = ", " " + name);
Log.e("last_name = ", " " + last_name);
Log.e("first_name = ", " " + first_name);
Log.e("middle_name = ", " " + middle_name);
Log.e("pictureLink = ", " " + picture);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Sttaaaaaaaaaaaaaaaaa", e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,link,last_name,first_name,middle_name,picture");
request.setParameters(parameters);
request.executeAsync();
I have been reading https://powerbi.microsoft.com/en-us/blog/announcing-data-refresh-apis-in-the-power-bi-service/
In this post, it mentions "To get the group ID and dataset ID, you can make a separate API call".
Does anybody know how to do this from the dashboard URL, or do I have to embed the group id and dataset id in my app alongside the dashboard URL???
To get the group ID and dataset ID, you can make a separate API call.
This sentence isn't related to a dashboard, because in one dashboard you can put visuals showing data from many different datasets. These different API calls are Get Groups (to get list of groups, find the one you want and read it's id) and Get Datasets In Group (to find the dataset you are looking for and read it's id).
But you should already know the groupId anyway, because the dashboard is in the same group.
Eventually, you can get datasetId from particular tile using Get Tiles In Group, but I do not know a way to list tiles in dashboard using the Rest API.
This is a C# project code to get the dataset id from Power BI.
Use the below method to call the 'Get' API and fetch you the dataset Id.
public void GetDatasetDetails()
{
HttpResponseMessage response = null;
HttpContent responseContent = null;
string strContent = "";
PowerBIDataset ds = null;
string serviceURL = "https://api.powerbi.com/v1.0/myorg/admin/datasets";
Console.WriteLine("");
Console.WriteLine("- Retrieving data from: " + serviceURL);
response = client.GetAsync(serviceURL).Result;
Console.WriteLine(" - Response code received: " + response.StatusCode);
try
{
responseContent = response.Content;
strContent = responseContent.ReadAsStringAsync().Result;
if (strContent.Length > 0)
{
Console.WriteLine(" - De-serializing DataSet details...");
// Parse the JSON string into objects and store in DataTable
JavaScriptSerializer js = new JavaScriptSerializer();
js.MaxJsonLength = 2147483647; // Set the maximum json document size to the max
ds = js.Deserialize<PowerBIDataset>(strContent);
if (ds != null)
{
if (ds.value != null)
{
foreach (PowerBIDatasetValue item in ds.value)
{
string datasetID = "";
string datasetName = "";
string datasetWeburl = "";
if (item.id != null)
{
datasetID = item.id;
}
if (item.name != null)
{
datasetName = item.name;
}
if (item.qnaEmbedURL != null)
{
datasetWeburl = item.qnaEmbedURL;
}
// Output the dataset Data
Console.WriteLine("");
Console.WriteLine("----------------------------------------------------------------------------------");
Console.WriteLine("");
Console.WriteLine("Dataset ID: " + datasetID);
Console.WriteLine("Dataset Name: " + datasetName);
Console.WriteLine("Dataset Web Url: " + datasetWeburl);
} // foreach
} // ds.value
} // ds
}
else
{
Console.WriteLine(" - No content received.");
}
}
catch (Exception ex)
{
Console.WriteLine(" - API Access Error: " + ex.ToString());
}
}
points to remember:
Make sure these classes exist in your project
PowerBIDataset is a class with List
PowerBIDatasetValue is a class with id, name and webUrl (all string data type) data members
provide below constants in your project class
const string ApplicationID = "747d78cd-xxxx-xxxx-xxxx-xxxx";
// Native Azure AD App ClientID -- Put your Client ID here
const string UserName = "user2#xxxxxxxxxxxx.onmicrosoft.com";
// Put your Active Directory / Power BI Username here (note this is not a secure place to store this!)
const string Password = "xyxxyx";
// Put your Active Directory / Power BI Password here (note this is not secure pace to store this! this is a sample only)
call this GetDatasetDetails() method in the Main method of your project class
and finally
use the below 'Get' API to get the Group Id
https://api.powerbi.com/v1.0/myorg/groups
The aws console show two columns State and Status Checks, when an instance is launching. A state of Running is not a true reflection of state because the Status Checks could fail.
Anyone have any examples of .net C# code to check the Status Check state?
The closest I have is this:
var request = new DescribeInstanceStatusRequest();
request.InstanceId = insts.Select(i => i.InstanceId).ToList();
DescribeInstanceStatusResponse response = ec2Client.DescribeInstanceStatus(request);
InstanceStatus instanceStatus = response.DescribeInstanceStatusResult.InstanceStatus[0];
Console.WriteLine("Availability zone - " + instanceStatus.AvailabilityZone);
Console.WriteLine("Instance State Code - " + instanceStatus.InstanceState.Code);
Console.WriteLine("Instance State Name - " + instanceStatus.InstanceState.Name);
foreach (InstanceStatusEvent statusEvent in instanceStatus.InstanceStatusEvent)
{
Console.WriteLine("Event Code - " + statusEvent.Code);
Console.WriteLine("Event Description - " + statusEvent.Description);
Console.WriteLine("Earliest Scheduled Start Time - " + statusEvent.NotBefore);
Console.WriteLine("Latest Scheduled End Time - " + statusEvent.NotAfter);
}
But that just gives the State, not the Status Checks.
You need to look deeper into the InstanceStatus object. The status checks are in the InstanceStatusDetail and the SystemStatusDetail properties. Here is a snippet that gets that information for you:
var status = result.InstanceStatus[0];
Console.WriteLine("Instance Status = " + status.InstanceStatusDetail.Status);
Console.WriteLine("Instance Status Detail Name = " + status.InstanceStatusDetail.Detail[0].Name);
Console.WriteLine("Instance Status Detail Status = " + status.InstanceStatusDetail.Detail[0].Status);
Console.WriteLine("System Status = " + status.SystemStatusDetail.Status);
Console.WriteLine("System Status Detail Name = " + status.SystemStatusDetail.Detail[0].Name);
Console.WriteLine("System Status Detail Status = " + status.SystemStatusDetail.Detail[0].Status);
Using Lucee (cfml) I got it like this:
<cfset var DescribeInstanceStatusRequest = CreateObject('java','com.amazonaws.services.ec2.model.DescribeInstanceStatusRequest', jarLocation).init()>
<cfset var describeInstanceStatusRequest = DescribeInstanceStatusRequest.withInstanceIds([arguments.instanceId])>
<cfset var statusresult = ec2client.describeInstanceStatus(describeInstanceStatusRequest).getInstanceStatuses()[1].getInstanceStatus().getDetails()[1].getStatus()>
this (statusresult) gives "passed" if the server has passed all checks.
note: coldfusion handles arrays differently so if for example you were translating back to java you would use [0] instead of 1.
If you only want the status: running, stopped etc
<cfset var result = ec2client.describeInstanceStatus(describeInstanceStatusRequest).getInstanceStatuses()[1].getInstanceState().getName()>
i am working with AD Server,i want to get the maxpwdAge attribute value...
i already try ADSi for that,but it gives an issue.
VARIANT var;
bsNamingContext=L"maxpwdAge";
hr = ADsGetObject(pszADsPath, IID_IADsUser, (void**) &pUser);
if(SUCCEEDED(hr))
{
VariantInit(&var);
hr = pUser->Get(bsNamingContext, &var);
}
but,it gives -2147463155 (8000500d) error...
but i am using bsNamingContext=L"cn";
it gives the CN values correctly...
anyone can resolve it?
maxpwdAge is not included in user/contact/person LDAP class, so you can not retrieve it that way.
You need to query it from domain object, not user object
Try this:
Const ONE_HUNDRED_NANOSECOND = .000000100 ' .000000100 is equal to 10^-7
Const SECONDS_IN_DAY = 86400
Set objDomain = GetObject("LDAP://DC=fabrikam,DC=com") ' LINE 4
Set objMaxPwdAge = objDomain.Get("maxPwdAge") ' LINE 5
If objMaxPwdAge.LowPart = 0 Then
WScript.Echo "The Maximum Password Age is set to 0 in the " & _
"domain. Therefore, the password does not expire."
WScript.Quit
Else
dblMaxPwdNano = Abs(objMaxPwdAge.HighPart * 2^32 + objMaxPwdAge.LowPart)
dblMaxPwdSecs = dblMaxPwdNano * ONE_HUNDRED_NANOSECOND ' LINE 13
dblMaxPwdDays = Int(dblMaxPwdSecs / SECONDS_IN_DAY) ' LINE 14
WScript.Echo "Maximum password age: " & dblMaxPwdDays & " days"
End If
UPDATE:
To convert large integer to human readable value use IADsLargeInteger dispatch interface
Note 1 : Example is in VB, but you can easily rewrite it, because of COM.
Note 2 : maxpwdAge is not configured per user, but per domain (until fine-grained password policies are enabled)
Further readings:
http://msdn.microsoft.com/en-us/library/ms974598.aspx [Recommended]
http://msdn.microsoft.com/en-us/library/cc220201%28prot.20%29.aspx
http://ldapwiki.willeke.com/wiki/AD%20Determining%20Password%20Expiration
http://ldapwiki.willeke.com/wiki/Domain%20Wide%20Account%20Policies
I struggled with this one too. Eventually, I was able to get it with the following criteria.
baseDN: 'DC=myofficedomain,DC=local',
filter: '(objectClass=domain)',
attributes: ['maxPwdAge']
I hope this helps anyone else using ldapsearch or NodeJS with ActiveDirectory.