I'm looking to try and get an MVC3 Canvas app working with the Facebook C# SDK, but am struggling to allow permissions - Below is my code, and when I open the app I get the 'Allow / Deny' dialog but when I click allow I get redirected to my app and the same dialog appears again (And again and so on no matter how many times I click allow)?
I guess I am missing something obvious... If I take the user_groups permission out it works fine, I just can't access the persons groups.
[CanvasAuthorize(Permissions = "user_groups")]
public class HomeController : Controller
{
public ActionResult Index()
{
IFacebookApplication settings = FacebookApplication.Current;
if (settings != null)
{
//CanvasPage = settings.CanvasPage;
//AppId = settings.AppId;
}
FacebookWebContext facebookContext = FacebookWebContext.Current;
FacebookSignedRequest signedRequest = facebookContext.SignedRequest;
var client = new FacebookWebClient(facebookContext.AccessToken);
dynamic me = client.Get("me");
var friends = client.Get("me/friends");
var groups = client.Get("me/groups");
ViewBag.Name = me.name;
ViewBag.Id = me.id;
JavaScriptSerializer sr = new JavaScriptSerializer();
var fbFriends = sr.Deserialize<FBFriends>(friends.ToString());
ViewData["friends"] = fbFriends.data;
return View("Friends");
}
}
Any help, tips or code samples greatly appreciated.
make sure u have set the appid and appsecret correctly.
download the source code and checkout the "samples" folder, there are a bunch of asp.net mvc samples.
Related
Since a few days I have been using Youtube's (Google's) API 3.0 (.NET Google API Library)
Everything was going smooth until I stumbled across a problem. I've tried many methods to figure out why I got a low amount of info from my results.
What I am trying in the code down below, is requesting the first comment on a video.
Then with that first comment (CommentThread), I am trying to retrieve all the replies of users that reacted on this comment.
I have tried getting information before, it works fine. I could loadup the entire comment section. Except for more than 5 replies per CommentThread. (CommentThread is basicly a comment under a video, where some have replies.)
This is my code, I have modified it alot of times, but from the looks of it. This one should work.
private static void searchReplies()
{
int count = 0;
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer() { ApiKey = Youtube.API.KEY });
List<string[]> comments = new List<string[]>();
var commentThreadsListRequest = youtube.CommentThreads.List("snippet,replies");
commentThreadsListRequest.VideoId = Youtube.Video.ID;
commentThreadsListRequest.Order = CommentThreadsResource.ListRequest.OrderEnum.Relevance;
commentThreadsListRequest.MaxResults = 1;
var commentThreadsListResult = commentThreadsListRequest.Execute();
foreach (var CommentThread in commentThreadsListResult.Items)
{
var commentListRequest = youtube.Comments.List("snippet");
commentListRequest.Id = CommentThread.Id;
var commentListResult = commentListRequest.Execute();
foreach (var Item in commentListResult.Items)
{
CommentThreadIDs.Add(Item.Id);
}
MessageBox.Show("COUNT:" + CommentThread.Replies.Comments.Count);
foreach (var Reply in CommentThread.Replies.Comments)
{
CommentThreadIDs.Add(Reply.Id);
}
}
}
I have checked my API and the video ID. They are all fine as I can request alot of other information.
I have tested this with several videos, but all videos where the first comment have more than 5 replies, it fails to get them all.
The result (Message Box with "Count:") I get (the amount of replies I get in CommentThread.Replies.Comments is 5. No matter what I do. Going to next page with a token does not work either as it is empty.
Does anyone know why it only returns 5 comments instead of more?
I found the answer with help of someone.
The problem was that I set the ID of a commentThread to a comment ID.
Instead I have to set the commentThread ID to the parent ID.
The following code fully replaces my old code if anyone ever needs it.
YouTubeService yts = new YouTubeService(new BaseClientService.Initializer() { ApiKey = "12345" });
var commentThreadsListRequest = yts.CommentThreads.List("snippet,replies");
commentThreadsListRequest.VideoId = "uywOqrvxsUo";
commentThreadsListRequest.Order = CommentThreadsResource.ListRequest.OrderEnum.Relevance;
commentThreadsListRequest.MaxResults = 1;
var commentThreadResult = commentThreadsListRequest.Execute().Items.First();
var commentListRequest = yts.Comments.List("snippet");
commentListRequest.Id = commentThreadResult.Id;
commentListRequest.MaxResults = 100;
var commentListResult = commentListRequest.Execute();
var comments = commentListResult.Items.Select(x => x.Snippet.TextOriginal).ToList();
I'm trying to link a c# application to a sharepoint directory, so I can create folders, download and upload files. However I am strugling with connecting to the correct folder.
I can retrieve the content from allitems.aspx, but I am not sure how to actually get the content from folder.
I have tried using the ClientContext - something like this:
ClientContext cxt = new ClientContext("https://xx.sharepoint.com/sites/");
cxt.Credentials = GetCredentials();
List list = cxt.Web.Lists.GetByTitle("Kontrakter");
var test = list.Views;
var test1 = cxt.Web.Lists;
cxt.Load(test1);
cxt.Load(list);
cxt.Load(test);
var a = 4;
var fullUri = new Uri("https://xx.sharepoint.com/sites/yy/Kontrakter/AllItems.aspx");
//var folder = cxt.Web.GetFolderByServerRelativeUrl(fullUri.AbsolutePath);
using (var rootCtx = new ClientContext(fullUri.GetLeftPart(UriPartial.Authority)))
{
rootCtx.Credentials = GetCredentials();
Uri webUri = Web.WebUrlFromPageUrlDirect(rootCtx, fullUri);
using (var ctx1 = new ClientContext(webUri))
{
ctx1.Credentials = GetCredentials();
var list1 = ctx1.Web.GetList(fullUri.AbsolutePath);
ctx1.Load(list1.RootFolder.Files);
ctx1.ExecuteQuery();
Console.WriteLine(list.RootFolder.Files.Count);
}
}
or via normal api calls like this:
https://xx.sharepoint.com/_api/Web/GetFolderByServerRelativeUrl('Kontrakter/Forms')/Files
The only way I can find some data is if I look into 'Shared documents/Forms'
I'm having problems understanding the directory structure and how I can actually find the content of files/folders.
Thanks in advance :)
Turned out I was missing a /sites in one of my uris.
I'm trying to make a targetingIdeaService API call to Google AdWords. This is my code so far:
[HttpGet]
public IEnumerable<string> Get()
{
var user = new AdWordsUser();
using (TargetingIdeaService targetingIdeaService = (TargetingIdeaService)user.GetService(AdWordsService.v201802.TargetingIdeaService))
{
// Create selector.
TargetingIdeaSelector selector = new TargetingIdeaSelector();
selector.requestType = RequestType.IDEAS;
selector.ideaType = IdeaType.KEYWORD;
selector.requestedAttributeTypes = new AttributeType[] {
AttributeType.KEYWORD_TEXT,
AttributeType.SEARCH_VOLUME,
AttributeType.AVERAGE_CPC,
AttributeType.COMPETITION,
AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
};
// Set selector paging (required for targeting idea service).
var paging = Paging.Default;
// Create related to query search parameter.
var relatedToQuerySearchParameter =
new RelatedToQuerySearchParameter
{ queries = new String[] { "bakery", "pastries", "birthday cake" } };
var searchParameters = new List<SearchParameter> { relatedToQuerySearchParameter };
var page = new TargetingIdeaPage();
page = targetingIdeaService.get(selector);
return new string[] { "value1", "value2" };
}
}
it looks ok, compiles at last, and so on. But then I went into debug mode. And I saw this:
So as you can see, the variable doesn't have the access token. The other data comes from app.config file.
I am quite certain the keys passed in are correct.
Then the code throws the famous invalid_grand error. In my case, I believe that's because the access token is not being generated. I'm new to AdWords and ASP.NET, so I probably missed something, but I have no idea what.
I used the
docs,
Code Structure instructions, and
code examples to put it all together.
I had my configuration wrong. I had to recreate all the credentials using incognito window. If you have any issues just open a thread here: https://groups.google.com/forum/#!forum/adwords-api
Im trying to move a file from one folder to another using the Google Drive API v3. I found documentation how to this here. I used the .NET sample code from the documentation page and created a method that looks like this:
public ActionResult MoveFile(string fileToMove, string destination)
{
DriveService service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = <USER CREDENTIAL>,
ApplicationName = "APPNAME"
});
var searchFiles = service.Files.List();
searchFiles.Corpus = FilesResource.ListRequest.CorpusEnum.User;
searchFiles.Q = "name = '" + fileToMove + "'";
searchFiles.Fields = "files(*)";
string fileToMoveId = searchFiles.Execute().Files[0].Id;
searchFiles.Q = "name = '" + destination + "'";
string destinationId = searchFiles.Execute().Files[0].Id;
//Code used from documentation
// Retrieve the existing parents to remove
var getRequest = service.Files.Get(fileToMoveId);
getRequest.Fields = "parents";
var file = getRequest.Execute();
var previousParents = String.Join(",", file.Parents);
// Move the file to the new folder
var updateRequest = service.Files.Update(file, fileToMoveId);
updateRequest.Fields = "id, parents";
updateRequest.AddParents = destinationId;
updateRequest.RemoveParents = previousParents;
file = updateRequest.Execute();
return RedirectToAction("Files", new {folderId = destinationId});
}
When I execute this code I get the following error:
The parents field is not directly writable in update requests. Use the
addParents and removeParents parameters instead.
The error doesn't really makes sense to me because this code sample came from the documentation page itself. I can't figure out what other paramters they mean. What addParents and removeParents parameters do they mean? Are updateRequest.AddParents and updateRequest.RemoveParents not the right parameters?
Ok here is the problem.
var updateRequest = service.Files.Update(file, fileToMoveId);
The method is requiring that you send a body of a file to be updated. This normally makes sense as any changes you want to make you can add to the body.
Now the problem you are having is that you got your file from a file.get. Which is totally normal. This is how you should be doing it. THe problem is there are some fields in that file that you cant update. So by sending the full file the API is rejecting your update. If you check Files: update under Request body you will see which fiends are updateable.
Issue:
Now this is either a problem with the client library or the API I am going to have to track down a few people at Google to see which is the case.
Fix:
I did some testing and sending an empty file object as the body works just fine. The file is moved.
var updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileToMove.Id);
updateRequest.AddParents = directoryToMove.Id;
updateRequest.RemoveParents = fileToMove.Parents[0];
var movedFile = updateRequest.Execute();
This method works well when working in your own drive, but not in a team drive where a file (folder) can only have 1 parent strictly. I do not have the solution in a team drive
I have pages that I admin in the Facebook and I want to share a link(not post) from that page using Facebook C# SDK. How can I do that? For clarify question, Facebook pages has link button that you can share link with page's picture.
Simply facebookclient.Post("me/feed",parameters);
For the parameters see https://developers.facebook.com/docs/reference/api/post/
messagePost["message"] = message;
messagePost["caption"] = caption;
messagePost["description"] = descr;
messagePost["link"] = "http://xxx";
FacebookClient fbClient = new FacebookClient(FacebookAdminToken); //users have to accept your app
dynamic fbAccounts = fbClient.Get("/" + FacebookAdminId + "/accounts");
if (pageID != null)
{
foreach (dynamic account in fbAccounts.data)
{
if (account.id == pageID)
{
messagePost["access_token"] = account.access_token;
break;
}
}
dynamic publishedResponse = fbClient.Post("/" + pageID + "/links", messagePost);
message.Success = true;
}
Hope his helps.
there is two majour problems with my solution:
1) my FacebookAdmintoken was created using the soon to be deprecated offline_status. there currently is no way for the access_token to stay alive otherwise. Facebook claims it does, but it just doesn't work.
2) there is a bug in the facebook API. when you use post('/id/LINKS') you cannot specify the picture (FB chooses a random pic from the site) and using post('/id/FEED') people can see the result, but they cannot SHARE it.
Seriously FB, get your act together!!!!!