Google plus API returns error code 401 when publishing - c#

I am using Google Plus API for .Net for implementing sharing on google plus using WebAuthenticationBroker. It returns a token after the user gets logged in but when I send a moments post request it returns error 401.
My code on clicking on image is
String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http://www.google.com&response_type=code&scope=" + Uri.EscapeDataString("https://www.googleapis.com/auth/plus.stream.write https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.login");
PlusService service = new PlusService();
System.Uri StartUri = new Uri(GoogleURL);
System.Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");
WebAuthenticationBroker.AuthenticateAndContinue(new Uri(GoogleURL), EndUri);
now when it returns after authenticating I have called method upload on google in continue which is as follows--
PlusService service = new PlusService();
Moment body = new Moment();
ItemScope itemScope = new ItemScope();
itemScope.Id = "replacewithuniqueforaddtarget";
itemScope.Image = "http://www.google.com/s2/static/images/GoogleyEyes.png";
itemScope.Type = "";
itemScope.Description = "The description for the action";
itemScope.Name = "An example of add activity";
body.Object = itemScope;
body.Type = "http://schema.org/AddAction";
MomentsResource.InsertRequest insert =
new MomentsResource.InsertRequest(
service,
body,
"me",
MomentsResource.InsertRequest.CollectionEnum.Vault);
Moment wrote = insert.Execute();
But it returns exception 401. The code to post I found on Google Console Help. Can somebody help in this?

I finally found out that google APIs are not directly open to third party developers and it just made my case void and had to use HTTP method for this. Thanks #DalmTo for answering.

Related

Issues publishing image to Facebook Page via Graph API SDK .NET

Attempting this on .NET Core 3.1
After several hours of trying to publish a photo to my public facebook page (as in business page) of which I am the admin and have a long-term token for...
I keep getting the following response to my request using the official Facebook SDK for .NET. However, the image itself is never loaded.
{{"id":"786692942226147","post_id":"113260773923227_786692942226147"}}
The request looks like
var imageMedia = new FacebookMediaObject { FileName = file.FileName, ContentType = file.ContentType };
var stream = file.OpenReadStream();
var bytes = await stream.ReadAsByteArrayAsync();
imageMedia.SetValue(bytes);
var fbClient = new FacebookClient(credential.Token)
{
AppId = _config.GetValue<string>("FacebookClientId"),
AppSecret = _config.GetValue<string>("FacebookSecret")
};
dynamic parameters = new ExpandoObject();
parameters.message = request.Message;
parameters.file = imageMedia;
var result = await fbClient.PostTaskAsync($"{credential.PageId}/photos", parameters, token);
I'm sure it has something to do with the parameters I'm passing in, like parameters.file... but the docs for this thing are VERY unclear... as in "literally does not exist"
Anyone with experience getting this working, please point me in the right direction?
The solution is to change parameters.file to parameters.image...

function to search in youtube

I write function for search in youtube.
I create project on "console.developers.google.com" . the name project is youtubesearch and I get apiKey.
I have the error
"An unhandled exception of type
'Google.GData.Client.InvalidCredentialsException' occurred in
Google.GData.Client.dll"
at foreach loop
my code is:
private void getsearch(string serchFor)
{
YouTubeRequestSettings setting = new YouTubeRequestSettings("youtubesearch", "APIkey","ise34857#gmail.com","password for my email");
YouTubeRequest Request = new YouTubeRequest(setting);
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
query.OrderBy = "viewCount";
query.Query = serchFor;
query.SafeSearch = YouTubeQuery.SafeSearchValues.Moderate;
Feed<Video> videofeed = Request.Get<Video>(query);
videoLookUp = new Dictionary<string, string>();
foreach (Video v in videofeed.Entries)
{
if (v.Media.Content!=null)
{
Console.WriteLine(v.Title);
Console.WriteLine(v.Media.Content.Url);
comboBox1.Items.Add(v.Title);
videoLookUp.Add(v.Title,v.Media.Content.Url);
}
}
}
Please check object setting if my parameter is right and tell me if I had any proplem in my code
Although the YouTube Data API (v2) has been officially deprecated, you can check in this documentation on how to properly authenticate your application using .NET client library. It also shows here how to properly use the YouTubeRequestSettings object.
To perform any operation using the YouTube API, you create a YouTubeRequestSettings object, which specifies the authentication information and authentication scheme to be used. With that object, you then create a YouTubeRequest object that you will use to actually perform the operations. (If you do not specify authentication information when creating the YouTubeRequestSettings object, then you will only be able to use the YouTubeRequest object to perform operations that do not require authentication.
YouTubeRequestSettings settings =
new YouTubeRequestSettings("example app", clientID, developerKey);
YouTubeRequest request = new YouTubeRequest(settings);
For more information and sample code, check this tutorial.

Need help interfacing with the National Rail Enquiries (UK) API (LDBWS)

I've registered for a token to access the National Rail (UK), Live Departure Boards API, but I can't seem to get it to work. Can anybody point out what I'm doing wrong?
I used WSDL.EXE to build a C# SOAP Proxy class, as specified here: https://realtime.nationalrail.co.uk/ldbws/
The generated .cs proxy file is 1318 lines long, but it looks correct.
My code is as follows: (LDBServiceSoap is the generated proxy class)
static void Main(string[] args)
{
LDBServiceSoap ldb = new LDBServiceSoap();
ldb.AccessTokenValue = new AccessToken() {
TokenValue = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
};
StationBoard sb = ldb.GetDepartureBoard(4, "WAT", "VIC", FilterType.from, 0, 120);
}
The Url is set inside the proxy class, so I can't think of anything else I need to do.
But when the debugger gets up to the GetDepartureBoard method, it throws a WebException "The request failed with HTTP status 401: Unauthorized."
Does anybody know what I'm missing / doing wrong here?
You're awesome!
If you obtained your access token through the OpenLDWS signup then your token will only work on the https://realtime.nationalrail.co.uk/OpenLDBWS/ endpoint that could be your problem
Not sure how you've generated your sources but I've managed to get a working version using this Web service client given WSDL to generate the sources from the WSDL:
wsimport -extension -keep -XadditionalHeaders https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2016-02-16
Then I call the method once the sources are on the classpath with the following:
AccessToken token = new AccessToken(); // This class is generated from the WSDL
token.setTokenValue("yourTokenHere");
Ldb ldb = new Ldb();
LDBServiceSoap api = ldb.getLDBServiceSoap();
GetBoardRequestParams reqParams = new GetBoardRequestParams();
reqParams.setCrs("STA"); // Station Code
reqParams.setNumRows(10);
reqParams.setTimeOffset(-120);
StationBoardResponseType departures = api.getDepartureBoard(reqParams, token);
Though the answer from Rob Evans did not completely provide the solution, it did show me the right direction. I had to implement this in C# and below code worked for me.
AccessToken token = new AccessToken();
token.TokenValue = "xxx-xxx-xxx";
ldb client = new ldb();
client.AccessTokenValue = token;
StationBoard sb = client.GetDepartureBoard(10, "ABW", "", FilterType.to, 0, 120);

Post message from Website to Facebook wall

I have a website made with ASP.NET webform .NET 4.5 C#. This site contains a forum(homemade by me), parts of this forum needs to be posted to the specific facebook wall(made for this webpage). What I need :
Post just created thread(message) from specific part of the forum to the corsponding facebook wall.
Optional : Sync the forum thread on webpage with message/comments on the specific facebook page
I have looked at these guides :
http://www.codeproject.com/Articles/569920/Publish-a-post-on-Facebook-wall-using-Graph-API
http://www.c-sharpcorner.com/UploadFile/raj1979/post-on-facebook-users-wall-using-Asp-Net-C-Sharp/
But im not sure that this is really the solution for me? I have tried to follow the guide but it does not look the same.
Edit :
dynamic result;
//https://developers.facebook.com/tools/explorer/
//https://developers.facebook.com/tools/access_token/
FacebookClient client = new FacebookClient(ConfigurationManager.AppSettings["FacebookAppToken"]);
//result = client.Get("debug_token", new
//{
// input_token = ConfigurationManager.AppSettings["FacebookAppToken"],
// access_token = ConfigurationManager.AppSettings["FacebookAppToken"]
//});
//result = client.Get("oauth/access_token", new
// {
// client_id = ConfigurationManager.AppSettings["FacebookAppId"],
// client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
// grant_type = "client_credentials",
// //redirect_uri = "http://www.MyDomain.net/",
// //code = ""
// });
result = client.Get("oauth/access_token", new
{
client_id = ConfigurationManager.AppSettings["FacebookAppId"],
client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
grant_type = "client_credentials"
});
client.AccessToken = result.access_token;
result = client.Post("[IdOfFacebookPage]/feed", new { message = "Test Message from app" });
//result.id;
result = client.Get("[IdOfFacebookPage]");
return false;
Approach to post to a facebook wall:
You need to register in facebook developer tools.
Create a app (fill a form).
Download FGT 5.0.480 (Facebook graph toolkit)
Reference FGT dlls in your web application.
FGT has methods to post to facebook wall but needs appId.
Use the app id of your app created in step 2.
To post to an user's wall through facebook, it is only possible through an app.
Try this asp .net app, which will allow you to post in your wall:
https://apps.facebook.com/aspdotnetsample/?fb_source=search&ref=br_tf
This will allow you to envision what you need.
Your app gets an appId with which you need to generate auth token.
Limitation: The user's wall where you want to post should have added the app created at step 2, this is compulsory and there is no work around.
When the user accesses the app for the first time, it automatically asks for permission to post to wall--> the user needs to accept it.
Hope this gives you an idea on how to go about doing this.
You can then post into the user's wall.
For Banshee's below request using Facebook SDK for .NET:
userId - facebook user id, wall to post the message
This user should have added the app created by you in step 1 else it will say unauthorized access.
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://www.stackoverflow.com/test.png";
messagePost.link = "http://www.stackoverflow.com";
messagePost.name = "This is a test name";
messagePost.caption = "CAPTION 1";
messagePost.description = "Test desc";
messagePost.message = "message"
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new {
client_id = "app_id",
client_secret = "app_secret",
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
try
{
var postId = fb.Post(userId + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle oauth exception
}
catch (FacebookApiException ex)
{
//handle facebook exception
}
You will need an extended token to publish to a wall.. Steps to get extended token is explained well by Banshee..
Edit: How to get extended token by Banshee:
Please follow this post
By creating a extended page token and use it to make the post everything works just fine. See this : How to get Page Access Token by code?
Im surprised that this simple task was so hard to get running and that there was vary little help to get.

Can't send Notifications using C# Facebook SDK

I am trying to send a notification (not app requests) to registered users, server-side using the C# Facebook SDK. I actually get a success message, but no notification is sent. Our app is not in sandbox and has canvas enabled. The code below show attempts to send both notifications and app requests--the notifications do nothing, but the app request works:
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "MY_APP_KEY",
client_secret = "MY_SECRET",
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
dynamic nparams = new ExpandoObject();
nparams.template = "Hello from my app!";
nparams.href = "Home";
dynamic requestParams = new ExpandoObject();
requestParams.message = "Hi there";
requestParams.title = "Please use this awesome app";
foreach (string facebookID in facebookIDs)
{
// This returns success:true, but doesn't actually do anything
var postResult = fb.Post(facebookID + "/notifications", nparams);
// This works and shows a request in the app center
var postResult2 = fb.Post(facebookID + "/apprequests", requestParams);
}
The fact that apprequests send here tells me the access token is ok, so why don't notifications work? We really need to do this server-side--has anyone been able to do that?
Got a response from facebook on this . . . basically, that this feature is in beta and it may just not work, despite giving Success responses
Good snippet Anthony. Appears to be working consistently now. +1 for your attempt.
PS: In case anyone stumbles upon this code, "facebookID" is a numeric Id and can be derived using the following link http://findmyfacebookid.com/

Categories

Resources