Exemplo n.º 1
0
        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();
        }
Exemplo n.º 2
0
        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();
            }
        }
Exemplo n.º 3
0
        /// <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;
        }
        private async void PublishStory()
        {
            var fb = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken);

            var postParams = new
            {
                name        = "Facebook SDK for .NET",
                caption     = "Build great social apps and get more installs.",
                description = "The Facebook SDK for .NET makes it easier and faster to develop Facebook integrated .NET apps.",
                link        = "http://facebooksdk.net/",
                picture     = "http://facebooksdk.net/assets/img/logo75x75.png"
            };

            try
            {
                dynamic fbPostTaskResult = await fb.PostTaskAsync("/me/feed", postParams);

                var result2 = (IDictionary <string, object>)fbPostTaskResult;

                var successMessageDialog = new Windows.UI.Popups.MessageDialog("Posted Open Graph Action, id: " + (string)result2["id"]);
                await successMessageDialog.ShowAsync();
            }
            catch (Exception ex)
            {
                MessageDialogHelper.Show("Exception during post: " + ex.Message);
            }
        }
Exemplo n.º 5
0
        public async Task <ActionResult> FacebookCallback(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = await fb.PostTaskAsync("oauth/access_token",
                                                    new
            {
                client_id     = "<Your application ID>",
                client_secret = "<Your Application password>",
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code
            });

            var accessToken = result.access_token;

            Session["FacebookToken"] = accessToken;
            fb.AccessToken           = accessToken;
            dynamic me = await fb.GetTaskAsync("me?fields=link,first_name,currency,last_name,email,gender,locale,timezone,verified,picture,age_range");

            string _Email = me.email;
            string _Name  = me.first_name + " " + me.last_name;

            using (AreaEntities db = new AreaEntities())
            {
                // If user exists log him.
                var tmp = await db.users.Where(m => m.Email == _Email).FirstOrDefaultAsync();

                if (tmp != null)
                {
                    Session["Username"] = _Name;
                    Session["Email"]    = _Email;
                    db.users.Attach(tmp);
                    tmp.Token_facebook  = accessToken;
                    db.Entry(tmp).State = EntityState.Modified;
                    db.SaveChanges();
                    FormsAuthentication.SetAuthCookie(_Email, false);
                    return(RedirectToAction("Index", "Home"));
                }
                // If user doesn't exists, add it to the database with a default password.
                else
                {
                    user ToAdd = new user()
                    {
                        Email          = _Email,
                        Name           = _Name,
                        Password       = "",
                        Token_facebook = accessToken
                    };
                    db.users.Add(ToAdd);
                    await db.SaveChangesAsync();

                    Session["Username"] = _Name;
                    Session["Email"]    = _Email;
                    FormsAuthentication.SetAuthCookie(_Email, false);
                    return(RedirectToAction("Index", "Home"));
                }
            }
        }
Exemplo n.º 6
0
        private async void PostToWall(string status)
        {
            try
            {
                facebookClient = new Facebook.FacebookClient(App.fbaccesstokenkey);
                var parameters = new Dictionary <string, object>();
                //var parameters1 = new Dictionary<string, object>();

                parameters["message"]     = status;
                parameters["caption"]     = string.Empty;
                parameters["description"] = string.Empty;
                parameters["req_perms"]   = "publish_stream";
                parameters["scope"]       = "publish_stream";
                parameters["type"]        = "normal";
                dynamic fbPostTaskResult = null;
                if (imageStatus)
                {
                    var mediaObject = new FacebookMediaObject
                    {
                        ContentType = "image/jpeg",
                        FileName    = "pokemon.jpg"
                    }.SetValue(byteImage);
                    parameters["source"] = mediaObject;
                    fbPostTaskResult     = await facebookClient.PostTaskAsync("/me/photos", parameters);
                }
                else
                {
                    fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", parameters);
                }
                var result = (IDictionary <string, object>)fbPostTaskResult;

                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Posted Open Graph Action, id: " + (string)result["id"], "Result", MessageBoxButton.OK);
                });
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Exception during post: " + ex.ToString(), "Error", MessageBoxButton.OK);
                });
            }
        }
        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);
        }
        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);
        }
        private async void PublishStory()
        {
            try
            {
                SetProgressIndicator("Publish Status", true);
                try
                {
                    await this.loginButton.RequestNewPermissions("publish_stream");

                    var facebookClient = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);

                    var postParams = new
                    {
                        message     = Text_Status.Text,
                        name        = (DTO_Class.Song_Post.Name == null && DTO_Class.Song_Post.Artist.Name == null) ? "Music Room for Window Phone" : DTO_Class.Song_Post.Name + " -- " + DTO_Class.Song_Post.Artist.Name,
                        caption     = "Application for Window Phone", /* -- DuyNguyenIT Developer"*/
                        description = "Come here with music, let's draw your life! Share from Music Room Window Phone",
                        link        = "http://www.windowsphone.com/vi-vn/store/app/musicroom/8d67625c-9c09-4a0e-b6d4-6fe29aa37f7a",
                        picture     = (DTO_Class.Song_Post.Image == null || DTO_Class.Song_Post.URL == null) ? "http://cdn.marketplaceimages.windowsphone.com/v8/images/575e6ab1-00bb-456c-bc9d-82b794a11db9?imageType=ws_icon_large" : DTO_Class.Song_Post.Image
                    };

                    try
                    {
                        dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);

                        var result = (IDictionary <string, object>)fbPostTaskResult;

                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("Successful! Your status is posted");
                        });
                    }
                    catch (Exception ex)
                    {
                        SetProgressIndicator("", false);
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("Fail post! Have exception is :' " + ex.Message + "' !", "Error", MessageBoxButton.OK);
                        });
                    }
                    SetProgressIndicator("", false);
                }
                catch { SetProgressIndicator("", false); }
            }
            catch { }
        }
Exemplo n.º 10
0
        /// <summary>
        ///  Function that will try to reserve a person in an event.
        /// </summary>
        /// <param name="eID"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        async public Task <bool> RSVPEvent(string eID, String status)
        {
            var fb         = new Facebook.FacebookClient(App.AccessToken);
            var parameters = new Dictionary <string, object>();

            parameters["access_token"] = App.AccessToken;
            bool result;

            try
            {
                result = (bool)await fb.PostTaskAsync(String.Format(@"/{0}/{1}", eID, status), parameters);
            }
            catch (Facebook.FacebookOAuthException)
            {
                result = false;
            }
            return(result);
        }
Exemplo n.º 11
0
        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);
            }
        }
Exemplo n.º 12
0
        private async void PublishStory()
        {
            SetProgressIndicator("Publish Status", true);
            try
            {
                await this.loginButton.RequestNewPermissions("publish_stream");

                var facebookClient = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);

                var postParams = new
                {
                    message     = Text_Status.Text,
                    name        = (DTO_Class.Song_Post.Name == null && DTO_Class.Song_Post.Artist.Name == null)? "Ứng dụng Music Room for Window Phone": DTO_Class.Song_Post.Name + " -- " + DTO_Class.Song_Post.Artist.Name,
                    caption     = "Application for Window Phone", /* -- Nguyễn Duy Nguyên Developer"*/
                    description = "Âm nhạc thăng hoa, dâng tràn cảm xúc! Được chia sẽ từ Ứng dụng Music Room Window Phone",
                    link        = (DTO_Class.Song_Post.URL == null) ? "http://facebooksdk.net/": DTO_Class.Song_Post.URL,
                    picture     = (DTO_Class.Song_Post.Image == null || DTO_Class.Song_Post.URL == null) ? "http://facebooksdk.net/assets/img/logo75x75.png" : DTO_Class.Song_Post.Image
                };

                try
                {
                    dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);

                    var result = (IDictionary <string, object>)fbPostTaskResult;

                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Successful! Your status is posted");
                    });
                }
                catch (Exception ex)
                {
                    SetProgressIndicator("", false);
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Fail post! Have exception is :' " + ex.Message + "' !", "Error", MessageBoxButton.OK);
                    });
                }
                SetProgressIndicator("", false);
            }
            catch { SetProgressIndicator("", false); }
        }
Exemplo n.º 13
0
 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());
     }
 }
        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();
            }
         }
Exemplo n.º 15
0
        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;
        }
Exemplo n.º 16
0
        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;
        }
Exemplo n.º 17
0
        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);
        }
Exemplo n.º 18
0
        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() }
            });
        }
Exemplo n.º 19
0
        // 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;
        }
        /// <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
        }
Exemplo n.º 21
0
        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
            //});
        }
Exemplo n.º 22
0
        private void onMessageSentCompletion(object sender, FacebookApiEventArgs e)
        {
            try
            {
                var a = App.Current as App;
                if (e.Error == null)
                {
                    var result = (IDictionary<string, object>)e.GetResultData();
                    var model = new List<Place>();
                    foreach (var place in (JsonArray)result["data"])
                        model.Add(new Place()
                        {
                            Id = (string)(((JsonObject)place)["id"]),
                            Name = (string)(((JsonObject)place)["name"])
                        });

                    FacebookClient fb = new FacebookClient(_facebookToken);

                    var param = new Dictionary<string, object> { { "message", "I am in danger at :" },
                                                            { "place", model.FirstOrDefault().Id },
                                                            {"acess_token",_facebookToken},
                                                            {"privacy", new Dictionary<string, object>{{"value", "ALL_FRIENDS"}}}};
                    // Posting status on facebook
                    fb.PostTaskAsync("me/feed", param, new System.Threading.CancellationToken());

                    // Calling  method to send sms
                    SMSUtils smsmUtil = new SMSUtils();
                    smsmUtil.SendText(GetSavedNumbers(), "I am in danger at :" + model.FirstOrDefault().Name);

                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Error ocurred in sending messages " + e.Error.Message);
                    });
                }
            }
            catch (System.Net.WebException ex)
            {
                MessageBox.Show("Internet connection is not working : " + ex.Message);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error while posting status in facebook : " + ex.Message);
            }
        }
Exemplo n.º 23
0
 private void OnCorruptionSubmitted(Corruption corruption)
 {
     FacebookClient client = new FacebookClient(StringSource.FaceBookAccessToken);
     client.PostTaskAsync(StringSource.FaceBookPage, new { message = corruption.Description });
 }
        /// <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;
        }