本文整理汇总了C#中Facebook.FacebookClient类的典型用法代码示例。如果您正苦于以下问题:C# FacebookClient类的具体用法?C# FacebookClient怎么用?C# FacebookClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
FacebookClient类属于Facebook命名空间,在下文中一共展示了FacebookClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FrmFacebookPost
public FrmFacebookPost()
{
client = new FacebookClient();
client.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
var error = args.Error as FacebookApiException;
if (error.ErrorCode == 190)
{
Dispatcher.BeginInvoke(() => MessageBox.Show("Authorization Error"));
SaveToken(null);
client.AccessToken = null;
return;
}
Dispatcher.BeginInvoke(() => MessageBox.Show(error.Message));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Message posted successfully");
Browser.Visibility = System.Windows.Visibility.Collapsed;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
StrCommonObject = JsonConvert.SerializeObject(ObjCommon);
NavigationService.Navigate(new Uri("/Pages/FrmProgress.xaml?common=" + StrCommonObject, UriKind.Relative));
});
});
};
if (GetToken() != null)
client.AccessToken = GetToken();
InitializeComponent();
if (!NetworkInterface.GetIsNetworkAvailable())
{
Dispatcher.BeginInvoke(() => { MessageBox.Show("No Internet Connection, Try again later"); });
return;
}
//If we already have an access token, then just post, otherwise move to the login page
if (client.AccessToken == null)
{
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FBApiID;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
parameters["scope"] = ExtendedPermisions;
Browser.Visibility = System.Windows.Visibility.Visible;
string t = client.GetLoginUrl(parameters).AbsoluteUri;
Browser.Navigate(client.GetLoginUrl(parameters));
}
}
示例2: RetriveUserInfo
private async System.Threading.Tasks.Task RetriveUserInfo(AccessTokenData accessToken)
{
var client = new Facebook.FacebookClient(accessToken.AccessToken);
dynamic result = null;
bool failed = false;
try
{
result = await client.GetTaskAsync("me?fields=id,birthday,first_name,last_name,middle_name,gender");
}
catch(Exception e)
{
failed = true;
}
if(failed)
{
MessageDialog dialog = new MessageDialog("Facebook is not responding to our authentication request. Sorry.");
await dialog.ShowAsync();
throw new Exception("Windows phone does not provide an exit function, so we have to crash the app.");
}
string fullName = string.Join(" ", new[] { result.first_name, result.middle_name, result.last_name });
string preferredName = result.last_name;
bool? gender = null;
if (result.gender == "female")
{
gender = true;
}
else if (result.gender == "male")
{
gender = false;
}
DateTime birthdate = DateTime.UtcNow - TimeSpan.FromDays(365 * 30);
if (result.birthday != null)
{
birthdate = DateTime.Parse(result.birthday);
}
var currentUser = new Facebook.Client.GraphUser(result);
long facebookId = long.Parse(result.id);
UserState.ActiveAccount = await Api.Do.AccountFacebook(facebookId);
if (UserState.ActiveAccount == null)
{
Frame.Navigate(typeof(CreatePage), new CreatePage.AutofillInfo
{
SocialId = facebookId,
Authenticator = Authenticator.Facebook,
Birthdate = birthdate,
FullName = fullName,
Gender = gender,
PreferredName = preferredName
});
}
else
{
Frame.Navigate(typeof(MainPage), UserState.CurrentId);
}
}
示例3: ExtendAccesstoken
public StreamItemCollection ExtendAccesstoken()
{
try
{
string accesstoken = "";
string appid = "";
string appsecret = "";
FacebookClient client = new FacebookClient();
dynamic Me = client.Get("oauth/access_token", new
{
client_id = appid,
client_secret = appsecret,
grant_type = "fb_exchange_token",
fb_exchange_token = accesstoken,
redirect_uri ="http://www.example.com",
});
}
catch (Exception exc)
{
throw;
}
return null;
}
示例4: GetSampleWithoutAccessToken
public static void GetSampleWithoutAccessToken()
{
try
{
var fb = new FacebookClient();
var result = (IDictionary<string, object>)fb.Get("/4");
var id = (string)result["id"];
var name = (string)result["name"];
var firstName = (string)result["first_name"];
var lastName = (string)result["last_name"];
Console.WriteLine("Id: {0}", id);
Console.WriteLine("Name: {0}", name);
Console.WriteLine("First Name: {0}", firstName);
Console.WriteLine("Last Name: {0}", lastName);
Console.WriteLine();
// Note: This json result is not the orginal json string as returned by Facebook.
Console.WriteLine("Json: {0}", result.ToString());
}
catch (FacebookApiException ex)
{
// Note: make sure to handle this exception.
throw;
}
}
示例5: AddPost
/// <summary>
/// Posts the messages and Picture to the MQ163 Feeds
/// </summary>
/// <param name="postData">Data to be posted</param>
/// <returns>Returns True: If posted successfully.
/// Exception: If post is unsuccessfull</returns>
internal bool AddPost(IFacebookPostData postData)
{
try
{
string accessToken = GetPageAccessToken();
string albumID = GetAlbumID();
var fb = new FacebookClient();
postData.AccessToken = accessToken;
string path = string.Format("{0}/photos?access_token={1}", albumID, accessToken);
dynamic publishResponse;
if (null != postData.TaggedUserEmail)
publishResponse = client.PostTaskAsync(path, postData.GetPostObject(GetUserID(postData.TaggedUserEmail).Id));
else
publishResponse = client.PostTaskAsync(path, postData.GetPostObject(String.Empty));
while (publishResponse.Status == TaskStatus.WaitingForActivation) ;
if (publishResponse.Status == TaskStatus.RanToCompletion)
return true;
else if (publishResponse.Status == TaskStatus.Faulted)
{
throw (new InvalidOperationException((((Exception)publishResponse.Exception).InnerException).Message, (Exception)publishResponse.Exception));
}
return false;
}
catch (Exception ex)
{
throw ex;
}
}
示例6: procesRequest
protected void procesRequest()
{
if (Request.QueryString["op"] == "twitter")
{
string twtProfileId = Request.QueryString["id"].ToString();
User user = (User)Session["LoggedUser"];
strTwtArray = objtwtStatsHelper.getNewFollowers(user, twtProfileId,15);
strTwtFollowing = objtwtStatsHelper.getNewFollowing(user, twtProfileId,15);
// strTwtAge = objtwtStatsHelper.GetFollowersAgeWise(user);
strIncomingMsg = objtwtStatsHelper.getIncomingMsg(user, twtProfileId,15);
strDmRecieve = objtwtStatsHelper.getDirectMessageRecieve(user, twtProfileId);
strDMSent = objtwtStatsHelper.getDirectMessageSent(user, twtProfileId);
strSentMsg = objtwtStatsHelper.getSentMsg(user, twtProfileId,15);
strRetweet = objtwtStatsHelper.getRetweets(user, twtProfileId,15);
strAgeDiff = objtwtStatsRepo.getAgeDiffCount(twtProfileId, 15);
strEngagement = objtwtStatsHelper.getEngagements(user, twtProfileId, 15);
strInfluence = objtwtStatsHelper.getInfluence(user, twtProfileId, 15);
Response.Write(strTwtArray + "@" + strTwtFollowing + "@" + strIncomingMsg + "@" + strDmRecieve + "@" + strDMSent + "@" + strSentMsg + "@" + strRetweet + "@" + strAgeDiff + "@" + strEngagement + "@" + strInfluence);
}
if (Request.QueryString["op"] == "facebook")
{
string fbProfileId = Request.QueryString["id"].ToString();
User user = (User)Session["LoggedUser"];
// objfbstatsHelper.getAllGroupsOnHome.InnerHtml = fbUser;
strFbAgeArray = objfbstatsHelper.getLikesByGenderAge(fbProfileId, user.Id, 10);
strPageImpression = objfbstatsHelper.getPageImressions(fbProfileId, user.Id, 10);
strLocationArray = objfbstatsHelper.getLocationInsight(fbProfileId, user.Id, 10);
objfbstatsHelper.getPostDetails(fbProfileId, user.Id, 10);
FacebookClient fb = new FacebookClient();
fb.AccessToken = Request.QueryString["access"].ToString();
dynamic pagelikes = fb.Get(fbProfileId);
string strval = pagelikes.likes.ToString() + " Total Likes " + pagelikes.talking_about_count + " People talking about this.";
Response.Write(strFbAgeArray + "_" + strPageImpression + "_" + strLocationArray + "_" + strval);
}
}
示例7: ArePageAdmins
/// <summary>
/// test if the specified users are admins of the fan page
/// </summary>
///
/// <param name="localbusinessId">
/// local business ID
/// </param>
///
/// <param name="userIds">
/// list of users to be tested (JSON formatted array)
/// </param>
///
/// <returns>
/// standard response with dictionary of users and their corresponding
/// role: admin or not
/// </returns>
public virtual JsonResult ArePageAdmins(long localbusinessId,
string userIds)
{
var localBusiness = Repository.Get<LocalBusiness>(localbusinessId);
if (!localBusiness.IsOwner(CurrentUser.Id))
{
return BuildFailureResult(-1,
App_GlobalResources.Errors.accessDenied);
}
var accessToken = localBusiness.FBFanPageAccessToken;
if (string.IsNullOrEmpty(accessToken))
{
return BuildFailureResult(-1,
App_GlobalResources.Errors.facebookAccessTokenNotStored);
}
var fbApp = new FacebookClient(accessToken);
var serializer = new JavaScriptSerializer();
var users = serializer.Deserialize<string[]>(userIds);
var rslt = Dror.Common.Utils.Facebook.AreAdmins(
fbApp,
localBusiness.FanPageId,
users,
Logger);
return BuildSuccessResult(1, rslt);
}
示例8: btnGetFriendsList_Click
private void btnGetFriendsList_Click(object sender, RoutedEventArgs e)
{
FacebookClient client = new FacebookClient(Token());
string fqlFriendsList = "SELECT uid2 FROM friend where uid1=me()";
client.GetCompleted += new EventHandler<FacebookApiEventArgs>(client_GetCompleted);
client.QueryAsync(fqlFriendsList, Token());
}
示例9: MultiQuery
public static void MultiQuery(string accessToken)
{
var query1 = "SELECT uid FROM user WHERE uid=me()";
var query2 = "SELECT profile_url FROM user WHERE uid=me()";
try
{
var fb = new FacebookClient(accessToken);
var result = (IList<object>)fb.Query(query1, query2);
var result0 = ((IDictionary<string, object>)result[0])["fql_result_set"];
var result1 = ((IDictionary<string, object>)result[1])["fql_result_set"];
Console.WriteLine("Query 0 result: {0}", result0);
Console.WriteLine();
Console.WriteLine("Query 1 result: {0}", result1);
Console.WriteLine();
// Note: This json result is not the orginal json string as returned by Facebook.
Console.WriteLine("Json: {0}", result.ToString());
}
catch (FacebookApiException ex)
{
// Note: make sure to handle this exception.
throw;
}
}
示例10: Connect
public ActionResult Connect(string returnUrl)
{
// TODO: Rebuild functionality using CoffeeScript implementation and new C# API
var fb = new FacebookClient();
var loginUri = fb.GetLoginUrl(new { state = returnUrl });
return Redirect(loginUri.AbsoluteUri);
}
示例11: Page_Load
//HTTPMODULE!!
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (User.IsInRole("Triphulcas"))
WelcomeMessage = Resources.Resource1.SnippetTriphulcasWelcomeMessage;
if (!String.IsNullOrEmpty(User.AccessToken))
{
try
{
var client = new FacebookClient(User.AccessToken);
dynamic result = client.Get("me", new { fields = "id" });
pImage.Src = String.Format(Resources.Resource1.FacebookPictureUrl, result.id);
pWelcome.InnerText = WelcomeMessage;
pLogout.Attributes.Remove("hidden");
pLogout.Attributes["style"] = "display:block";
}
catch (FacebookOAuthException)
{
}
}
}
else
{
//ugly, I know.
pWelcome.InnerHtml = String.Format("{0} <a class=\"popup\" href=\"/authentication.aspx\">{1}</a>.",
Resources.Resource1.SnippetShowFaceBeforeLink,
Resources.Resource1.SnippetShowFaceLink);
}
}
示例12: GetClient
public static FacebookClient GetClient(bool reload=false)
{
if (reload)
client = null;
if (client!=null)
{
return client;
}
try
{
client = new FacebookClient(Data.Get("token"));
me = client.Get("me/");
}
catch (WebExceptionWrapper)
{
throw new NoConnection();
}
catch (Exception)
{
return null;
}
return client;
}
示例13: btnUpload_Click
private void btnUpload_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(_filename))
{
MessageBox.Show("Please select the image file first.");
return;
}
var mediaObject = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = Path.GetFileName(_filename)
}
.SetValue(File.ReadAllBytes(_filename));
progressBar1.Value = 0;
var fb = new FacebookClient(_accessToken);
fb.UploadProgressChanged += fb_UploadProgressChanged;
fb.PostCompleted += fb_PostCompleted;
// for cancellation
_fb = fb;
fb.PostAsync("/me/photos", new Dictionary<string, object> { { "source", mediaObject } });
}
示例14: BaseController
protected BaseController(IRepository repository, FacebookClient app,
ILogger logger)
{
Repository = repository;
FacebookApp = app;
Logger = logger;
}
示例15: getFacebookPageLikes
public Dictionary<DateTime, int> getFacebookPageLikes(string PageId, string Accesstoken, int days)
{
//string accesstoken = "CAACEdEose0cBAMQVEgKsHtUogOZCQ9vtBZB6FjsUWuZCVEzVUU01yecHqo1fVpTfQq65tmMUfmlafhmGtzmUY6ZCmZBrEXWMp1sfBLMvtdB7c1HBkSBGxbqT0q0nQY6ZBmtPBhg84IrXy4jBjRdMmP1Mh8hlOC9TRuy86jabDi2ccOyeRXYVZA7vuj4HDYgLhrwlNubCYvkENa6nPuY1PCgkuCv1cS8rXMZD";
try
{
long since = DateTime.Now.AddDays(-days).ToUnixTimestamp();
long until = DateTime.Now.ToUnixTimestamp();
FacebookClient fb = new FacebookClient();
fb.AccessToken = Accesstoken;
//dynamic kasdfj = fb.Get("v2.3/me/permissions");
dynamic kajlsfdj = fb.Get("v2.0/" + PageId + "/insights/page_fans?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString());
string facebookSearchUrl = "https://graph.facebook.com/v2.3/" + PageId + "/insights/page_fans?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + Accesstoken;
string outputface = getFacebookResponse(facebookSearchUrl);
Dictionary<DateTime, int> LikesByDay = new Dictionary<DateTime, int>();
LikesByDay = getFacebookLikesDictonary(outputface);
return LikesByDay;
}
catch (Exception ex)
{
return new Dictionary<DateTime, int>();
}
}