本文整理汇总了C#中Facebook.FacebookClient.PostTaskAsync方法的典型用法代码示例。如果您正苦于以下问题:C# FacebookClient.PostTaskAsync方法的具体用法?C# FacebookClient.PostTaskAsync怎么用?C# FacebookClient.PostTaskAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Facebook.FacebookClient
的用法示例。
在下文中一共展示了FacebookClient.PostTaskAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: updateStatus
private async void updateStatus(object sender, TappedRoutedEventArgs e)
{
PostButton.IsEnabled = false;
App.Progress.IsActive = true;
App.Progress.Visibility = Windows.UI.Xaml.Visibility.Visible;
FacebookClient _fb = new FacebookClient(session.accessToken);
dynamic parameters = new ExpandoObject();
parameters.access_token = session.accessToken;
string postText = "";
StatusText.Document.GetText(Windows.UI.Text.TextGetOptions.None, out postText);
parameters.message = postText.Replace("\r", "");
dynamic result = null;
try
{
result = await _fb.PostTaskAsync("me/feed", parameters);
}
catch (FacebookOAuthException ex)
{
Debug.WriteLine("Problem: " + ex.StackTrace);
App.Progress.IsActive = false;
App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
return;
}
App.Progress.IsActive = false;
App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
statusBtn.closePostStatus();
}
示例2: AddPost
/// <summary>
/// Posts on to Facebook Page
/// </summary>
/// <param name="postData">Data to be posted</param>
/// <returns>Returns True: If posted successfully.
/// Exception: If post is unsuccessfull</returns>
public bool AddPost(IFacebookPostData postData)
{
#region initialize objects and Url
string accessToken = GetPageAccessToken();
postData.AccessToken = accessToken;
string path = string.Format("{0}/photos?access_token={1}", "MQ163", accessToken);
dynamic publishResponse;
FacebookClient fb = new FacebookClient();
fb.AccessToken = this.AccessToken;
#endregion
publishResponse = fb.PostTaskAsync(path, postData.GetPostObject());
// Wait for activation
while (publishResponse.Status == TaskStatus.WaitingForActivation) ;
// Check if it succeded or failed
if (publishResponse.Status == TaskStatus.RanToCompletion)
{
string photoId = publishResponse.Result["post_id"];//post_id
if (null != postData.TaggedUserEmail)
{
bool result = TagPhoto(photoId, GetUserID(postData.TaggedUserEmail).Id);
}
return true;
}
else if (publishResponse.Status == TaskStatus.Faulted)
{
//CommonEventsHelper.WriteToEventLog(string.Format("Error posting message - {0}", (publishResponse.Exception as Exception).Message), System.Diagnostics.EventLogEntryType.Error);
throw (new InvalidOperationException((((Exception)publishResponse.Exception).InnerException).Message, (Exception)publishResponse.Exception));
}
return false;
}
示例3: PostToWall
public async Task<bool> PostToWall(string message, string userToken)
{
var fb = new FacebookClient(userToken);
var postou = false;
await fb.PostTaskAsync("me/feed", new { message = message, link = "http://google.com.br"}).ContinueWith(async(t) =>
{
if (t.IsFaulted)
{
Toast.MakeText(Forms.Context, "Erro ao postar", ToastLength.Short).Show();
}
else
postou = true;
});
return await Task.FromResult(postou);
}
示例4: PostToWall
public async Task<bool> PostToWall(string message, string userToken)
{
var fb = new FacebookClient(userToken);
var postou = false;
await fb.PostTaskAsync("me/feed", new { message = message, link = "http://google.com.br"}).ContinueWith(async(t) =>
{
if (t.IsFaulted)
{
var _error = new UIAlertView("Erro", "Erro ao postar, tente novamente!", null, "Ok", null);
_error.Show();
}
else
postou = true;
});
return await Task.FromResult(postou);
}
示例5: SendWelcomeMessageAsync
public async Task SendWelcomeMessageAsync(DomainUser user, TokenData data)
{
string facebookMessage = _settings.FacebookRegistrationMessage;
if (String.IsNullOrEmpty(facebookMessage))
{
return;
}
if (data == null || string.IsNullOrEmpty(data.Token))
{
throw new ArgumentNullException("data");
}
JObject message = JObject.Parse(facebookMessage);
var fb = new FacebookClient(data.Token);
var post = new
{
caption = (string)message["caption"],
message = (string)message["message"],
name = (string)message["name"],
description = (string)message["description"],
picture = (string)message["picture"],
link = (string)message["link"]
};
try
{
await fb.PostTaskAsync("me/feed", post);
}
catch (FacebookOAuthException e)
{
//Permission error
if (e.ErrorCode != 200)
{
throw new BadRequestException(e);
}
}
catch (WebExceptionWrapper e)
{
throw new BadGatewayException(e);
}
}
示例6: button1_Click
private void button1_Click(object sender, EventArgs e)
{
try
{
DateTime dt = DateTime.Now;
string filename = String.Format("{0:HH.mm.ss}", dt) + ".jpg";
var fb = new FacebookClient(ThisAddIn.GetAccessToken());
fb.PostCompleted += fb_PostCompleted;
fb.PostTaskAsync("me/photos",new
{
message = richTextBox1.Text,
file = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = filename
}.SetValue(ImageToBuffer(image, System.Drawing.Imaging.ImageFormat.Jpeg))
});
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
示例7: SetRsvp
public void SetRsvp(string name, ActivityItemsViewModel act)
{
if (App.ViewModel.UserPreference.AccessKey == null || act.FacebookId == null || act.FacebookId.Equals("") || !App.ViewModel.HasConnection)
return;
var fb = new FacebookClient { AccessToken = App.ViewModel.UserPreference.AccessKey, AppId = App.ViewModel.Appid };
fb.GetCompleted += (o, e) =>
{
if (e.Error != null)
{
Deployment.Current.Dispatcher.BeginInvoke(
() => MessageBox.Show(
"Er gebeurde een fout tijdens het versturen van data naar Facebook"));
}
act.RsvpStatus = GetRsvp(act).ToString();
};
var query = string.Format("https://graph.facebook.com/{0}/{1}", act.FacebookId, name);
fb.PostTaskAsync(query, null);
}
示例8: UploadPhoto
private void UploadPhoto()
{
if (!File.Exists(_filename))
{
lblStatus.Text = GlobalSetting.LangPack.Items["frmFacebook._StatusInvalid"];
return;
}
var mediaObject = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = Path.GetFileName(_filename)
}.SetValue(File.ReadAllBytes(_filename));
lblPercent.Text = "0 %";
picStatus.Visible = true;
lblStatus.Text = GlobalSetting.LangPack.Items["frmFacebook._StatusUploading"];
var fb = new FacebookClient(GlobalSetting.FacebookAccessToken);
fb.UploadProgressChanged += fb_UploadProgressChanged;
fb.PostCompleted += fb_PostCompleted;
// for cancellation
_fb = fb;
fb.PostTaskAsync("/me/photos", new Dictionary<string, object>
{
{ "source", mediaObject },
{ "message", txtMessage.Text.Trim() }
});
}
示例9: API
/// <summary>
/// For platforms that do not support dynamic cast it to either IDictionary<string, object> if json object or IList<object> if array.
/// For primitive types cast it to bool, string, dobule or long depending on the type.
/// Reference: http://facebooksdk.net/docs/making-asynchronous-requests/#1
/// </summary>
public static void API(
string endpoint,
HttpMethod method,
FacebookDelegate callback,
object parameters = null)
{
#if NETFX_CORE
Task.Run(async () =>
{
FacebookClient fb = new FacebookClient(_fbSessionClient.CurrentAccessTokenData.AccessToken);
FBResult fbResult = null;
try
{
object apiCall;
if (method == HttpMethod.GET)
{
apiCall = await fb.GetTaskAsync(endpoint, parameters);
}
else if (method == HttpMethod.POST)
{
apiCall = await fb.PostTaskAsync(endpoint, parameters);
}
else
{
apiCall = await fb.DeleteTaskAsync(endpoint);
}
if (apiCall != null)
{
fbResult = new FBResult();
fbResult.Text = apiCall.ToString();
fbResult.Json = apiCall as JsonObject;
}
}
catch (Exception ex)
{
fbResult = new FBResult();
fbResult.Error = ex.Message;
}
if (callback != null)
{
Dispatcher.InvokeOnAppThread(() => { callback(fbResult); });
}
});
#else
throw new PlatformNotSupportedException("");
#endif
}
示例10: UpdateStatusButton_OnClick
/// <summary>
/// Handles the OnClick event of the UpdateStatusButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private async void UpdateStatusButton_OnClick(object sender, RoutedEventArgs e)
{
var session = SessionStorage.Load();
if (null == session)
{
return;
}
this.ProgressText = "Updating status...";
this.ProgressIsVisible = true;
this.UpdateStatusButton.IsEnabled = false;
try
{
var fb = new FacebookClient(session.AccessToken);
await fb.PostTaskAsync(string.Format("me/feed?message={0}", this.UpdateStatusBox.Text), null);
await this.GetUserStatus(fb);
this.UpdateStatusBox.Text = string.Empty;
}
catch (FacebookOAuthException exception)
{
MessageBox.Show("Error fetching user data: " + exception.Message);
}
this.ProgressText = string.Empty;
this.ProgressIsVisible = false;
this.UpdateStatusButton.IsEnabled = true;
}
示例11: Post_Click
async private void Post_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
await this.loginButton.RequestNewPermissions("publish_actions");
var facebookClient = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);
var postParams = new {
message = Joke.Text
};
try
{
// me/feed posts to logged in user's feed
dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);
var result = (IDictionary<string, object>)fbPostTaskResult;
var successMessageDialog = new Windows.UI.Popups.MessageDialog("Posted Open Graph Action, id: " + (string)result["id"]);
await successMessageDialog.ShowAsync();
}
catch (Exception ex)
{
var exceptionMessageDialog = new Windows.UI.Popups.MessageDialog("Exception during post: " + ex.Message);
exceptionMessageDialog.ShowAsync();
}
}
示例12: SendNotification
public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback)
{
FacebookNotification msg = notification as FacebookNotification;
FacebookMessageTransportResponse result = new FacebookMessageTransportResponse();
result.Message = msg;
FacebookClient v_FacebookClient = new FacebookClient();
if (!string.IsNullOrEmpty(this.FacebookSettings.AppAccessToken))
{
v_FacebookClient.AccessToken = this.FacebookSettings.AppAccessToken;
}
else
{
v_FacebookClient.AccessToken = this.GetAppAccessToken();
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
switch (msg.NotificationType)
{
case FacebookNotificationType.ApplicationRequest:
parameters["message"] = msg.Message;
parameters["title"] = msg.Title;
break;
case FacebookNotificationType.Wall:
parameters["message"] = msg.Message;
break;
case FacebookNotificationType.Notification:
default:
parameters["href"] = msg.CallbackUrl;
parameters["template"] = msg.Message;
parameters["ref"] = msg.Category;
break;
}
// Prepare object in call back
FacebookAsyncParameters v_FacebookAsyncParameters = new FacebookAsyncParameters()
{
Callback = callback,
WebRequest = null,
WebResponse = null,
Message = msg,
AppAccessToken = FacebookSettings.AppAccessToken,
AppId = FacebookSettings.AppId,
AppSecret = FacebookSettings.AppSecret
};
CancellationToken v_CancellationToken = new CancellationToken();
v_FacebookClient.PostCompleted += FacebookClient_PostCompleted;
IDictionary<string, object> v_FacebookClientResult = v_FacebookClient.PostTaskAsync
(string.Format("{0}/{1}", msg.RegistrationIds[0], msg.CommandNotification)
, parameters
, v_FacebookAsyncParameters
, v_CancellationToken) as IDictionary<string, object>;
//var postData = msg.GetJson();
//var webReq = (HttpWebRequest)WebRequest.Create(FacebookSettings.FacebookUrl);
////webReq.ContentLength = postData.Length;
//webReq.Method = "POST";
//webReq.ContentType = "application/json";
////webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8 can be used for plaintext bodies
//webReq.UserAgent = "PushSharp (version: 1.0)";
//webReq.Headers.Add("Authorization: key=" + FacebookSettings.SenderAuthToken);
//webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new FacebookAsyncParameters()
//{
// Callback = callback,
// WebRequest = webReq,
// WebResponse = null,
// Message = msg,
// SenderAuthToken = FacebookSettings.SenderAuthToken,
// SenderId = FacebookSettings.SenderID,
// ApplicationId = FacebookSettings.ApplicationIdPackageName
//});
}
示例13: PublishEvent
// See https://developers.facebook.com/docs/graph-api/reference/user/events
public async Task<string> PublishEvent(IdentityUser user, FacebookEvent ev)
{
var accessToken = GetAccessToken(user);
var client = new FacebookClient(accessToken);
var eventdata = new Dictionary<string, object>();
eventdata.AddIfNotNull("name", ev.Name);
eventdata.AddIfNotNull("description", ev.Description);
eventdata.AddIfNotNull("start_time", "2014-04-30"); // Use DateTimeConverter To.... here
eventdata.AddIfNotNull("location", "Lincoln, NE");
eventdata.AddIfNotNull("privacy_type", "OPEN");
var result = await client.PostTaskAsync(string.Format("me/events"), eventdata);
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
var id = JsonConvert.DeserializeObject<FacebookIdentity>(result.ToString(), settings);
Log.InfoFormat("Published a Facebook event. UserId={0} CreatedId={1} Name={2}", user.Id, id.Id, ev.Name);
return id.Id;
}
示例14: PublishImage
public async Task<string> PublishImage(IdentityUser user, string contentId, FacebookPictureItem item)
{
var accessToken = GetAccessToken(user);
var client = new FacebookClient(accessToken);
var feedData = new Dictionary<string, object>();
feedData["message"] = item.Message;
feedData["url"] = item.Url;
var result = await client.PostTaskAsync(string.Format("{0}/photos", contentId), feedData);
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
var id = JsonConvert.DeserializeObject<FacebookIdentity>(result.ToString(), settings);
Log.InfoFormat("Published picture to a Facebook feed. ContentId={0} CreatedId={1} Message={2} Url={3} UserId={4}", contentId, id.Id, item.Message, item.Url, user.Id);
return id.Id;
}
示例15: PublishFeedItem
public async Task<string> PublishFeedItem(IdentityUser user, string contentId, FacebookFeedItem item)
{
var accessToken = GetAccessToken(user);
var client = new FacebookClient(accessToken);
var feedData = new Dictionary<string, object>();
feedData["message"] = item.Message;
if (!string.IsNullOrEmpty(item.Link))
{
feedData["link"] = item.Link;
}
var result = await client.PostTaskAsync(string.Format("{0}/feed", contentId), feedData);
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
var id = JsonConvert.DeserializeObject<FacebookIdentity>(result.ToString(), settings);
Log.InfoFormat("Published status to a Facebook feed. ContentId={0} CreatedId={1} Message={2} Link={3} UserId={4}", contentId, id.Id, item.Message, item.Link, user.Id);
return id.Id;
}