예제 #1
0
        public override void PostScheduleMessage(dynamic data)
        {
            try
            {
                FacebookAccountRepository fbaccrepo = new FacebookAccountRepository();
                //IEnumerable<FacebookAccount> lstfbaccount = fbaccrepo.getUserDetails(data.ProfileId);
                FacebookAccount fbaccount = fbaccrepo.getUserDetails(data.ProfileId);
                //FacebookAccount fbaccount = null;
                //foreach (FacebookAccount item in lstfbaccount)
                //{
                //    fbaccount = item;
                //    break;
                //}

                FacebookClient fbclient = new FacebookClient(fbaccount.AccessToken);
                var args = new Dictionary<string, object>();
                args["message"] = data.ShareMessage;

                //var facebookpost = fbclient.Post("/me/feed", args);
                var facebookpost = "";
                if (fbaccount.Type == "page")
                {
                    facebookpost = fbclient.Post("/" + fbaccount.FbUserId + "/feed", args).ToString();
                }
                else
                {
                    facebookpost = fbclient.Post("/me/feed", args).ToString();
                }


                Console.WriteLine("Message post on facebook for Id :" + fbaccount.FbUserId + " and Message: " + data.ShareMessage);
              
                ScheduledMessageRepository schrepo = new ScheduledMessageRepository();
                ScheduledMessage schmsg = new ScheduledMessage();
                schmsg.Id = data.Id;
                schmsg.ProfileId = data.ProfileId;
                schmsg.ProfileType = "";
                schmsg.Status = true;
                schmsg.UserId = data.UserId;
                schmsg.ShareMessage = data.ShareMessage;
                schmsg.ScheduleTime = data.ScheduleTime;
                schmsg.ClientTime = data.ClientTime;
                schmsg.CreateTime = data.CreateTime;
                schmsg.PicUrl = data.PicUrl;

                schrepo.updateMessage(data.Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
 
        }
예제 #2
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "462931197153588",
                client_secret = "82c4ec01d4516d06889341aed8857e5b",
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=first_name,last_name,id,email");
            string email = me.email;

            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(email, false);

            return RedirectToAction("Index", "Home");
        }
예제 #3
0
        public static string DeletePost(string accessToken, string postId)
        {
            try
            {
                var fb = new FacebookClient(accessToken);

                var parameters = new Dictionary<string, object>
                                     {
                                         { "method", "stream.remove" },
                                         { "post_id", postId }
                                     };

                var result = fb.Post(parameters);

                // Note: This json result is not the orginal json string as returned by Facebook.
                Console.WriteLine("Json: {0}", result.ToString());

                return postId;
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }
예제 #4
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = ConfigurationManager.AppSettings["LoginId"],
                client_secret = ConfigurationManager.AppSettings["LoginSec"],
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var access_token = result.access_token;
            if (!string.IsNullOrEmpty(access_token))
            {
                fb.AccessToken = access_token;
                dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
                string email = me.email;
                string username = me.email;
                string firstname = me.first_name;
                string middlename = me.middle_name;
                string lastname = me.last_name;

                var kh = new KhachHang();
                kh.Email = email;
                kh.TenDangNhap = username;
                kh.MatKhau = "123";
                kh.Ten = lastname + middlename + firstname;
                kh.PerId = 1;
                kh.SoDienThoai = "";
                kh.DiaChi = "";
                Session["LogedName"] = username;
                var check = khachHang.AddUserForFacebook(kh);
            }
            return RedirectToAction("Index", "Home");
        }
예제 #5
0
        public ActionResult Authenticate(String code)
        {
            FacebookClient client = new FacebookClient();

            dynamic temp = client.Post("oauth/access_token", new
            {
                client_id = "603680269694814",
                client_secret = "c45641c9de012c138f1658aa95a6c27d",
                redirect_uri = Url.Action("Authenticate", "User", null, Request.Url.Scheme),
                code = code
            });

            client.AccessToken = temp.access_token;

            dynamic properties = client.Get("me?fields=first_name,last_name,id,email");
            String email = properties.email;

            User user = repository.FindBy(u => u.email == email).SingleOrDefault();

            if (user == null)
                user = CreateNewUser(properties);

            FormsAuthentication.SetAuthCookie(user.email, false);
            return RedirectToAction("Index", "User");
        }
예제 #6
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "1539813469663309",
                client_secret = "0883fd6699f9f387a575e12d28391751",
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so 
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=first_name,last_name,id,email, friends, likes");
            Console.WriteLine(me);
            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(me.email, false);

            return RedirectToAction("Index", "Home");
        }
예제 #7
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "887117078046213",
                client_secret = "d27adbc1c24cffa0fb4849592a3befd9",
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session for farther use
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email");
            string email = me.email;
            string firstname = me.first_name;
            string middlename = me.middle_name;
            string lastname = me.last_name;
            @Session["LogedUserName"] = me.first_name;
            @Session["LogedUserLastName"] = me.last_name;
            @Session["LogedUserEmail"] = me.email;

            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(email, false);

            return RedirectToAction("CheckExternalLoginRegister", "Login");
        }
예제 #8
0
        public ActionResult Create([Bind(Include = "ID,Title,Writer,WebSite,PostingDate,Content,Image,Video")] Post post, bool ImageCheckBox, bool VideoCheckBox)
        {
            post.Comments = new List<Comment>();

            if (ModelState.IsValid)
            {
                if (!ImageCheckBox)
                    post.Image = string.Empty;
                if (!VideoCheckBox)
                    post.Video = string.Empty;
                db.Posts.Add(post);
                db.SaveChanges();

                if (FanClubController.access_token != "")
                {
                    var client = new FacebookClient(FanClubController.access_token);

                    client.Post("/me/feed/", new { message = string.Format("Title is:{0} And Writer is:{1}", post.Title, post.Writer) });
                }

                return RedirectToAction("Index");
            }

            return View(post);
        }
예제 #9
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "100106430186046",
                client_secret = "7c9ee3c7e3a1362098ad88b7a9227fc8",
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=first_name,last_name,id,email");
            string user = string.Join(" ", me.first_name, me.last_name);

            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(user, false);

            return RedirectToAction("Index", "Home");
        }
예제 #10
0
        public static string PostToMyWall(string accessToken, string message)
        {
            try
            {
                var fb = new FacebookClient(accessToken);

                var parameters = new Dictionary<string, object>
                                     {
                                         { "method", "stream.publish" },
                                         { "message", message }
                                     };

                var result = fb.Post(parameters);
                var postId = (string)result;

                Console.WriteLine("Post Id: {0}", postId);

                // Note: This json result is not the orginal json string as returned by Facebook.
                Console.WriteLine("Json: {0}", result.ToString());

                return postId;
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }
예제 #11
0
        public ActionResult ConnectResponse(string state, string code, string error, string error_reason, string error_description, string access_token, string expires)
        {
            if (string.IsNullOrEmpty(error))
            {
                try
                {
                    var client = new FacebookClient();
                    dynamic result = client.Post("oauth/access_token",
                                              new
                                              {
                                                  client_id = "435662283157258",
                                                  client_secret = "66b1e2c2ba9eed935bce0c8fb4553f28",
                                                  redirect_uri = "http://localhost:23232/Home/ConnectResponse",
                                                  code = code
                                              });

                    Session["AccessToken"] = result.access_token;

                    if (result.ContainsKey("expires"))
                        Session["ExpiresIn"] = DateTime.Now.AddSeconds(result.expires);

                }
                catch
                {
                    // handle errors
                }
            }
            else
            {
                // Declined, check error
            }

            return RedirectToAction("Main");
        }
예제 #12
0
        public RedirectToRouteResult FacebookCallback(string code)
        {
            var fb = new Facebook.FacebookClient();

            try
            {
                dynamic result = fb.Post("oauth/access_token", new
                {
                    client_id     = "",
                    client_secret = "",
                    redirect_uri  = RedirectUri.AbsoluteUri,
                    code          = code
                });

                var accessToken = result.access_token;
                Session["AccessToken"] = accessToken;
                fb.AccessToken         = accessToken;

                dynamic me   = fb.Get("me?fields=first_name,last_name,id,email");
                User    user = new User();
                user.login           = me.first_name.ToString() + "FB";
                user.email           = me.email.ToString();
                user.password        = me.id.ToString();
                user.validationEmail = true;
                UserService.InserNew(user);
            }
            catch { }
            return(RedirectToAction("Index", "Account"));
        }
예제 #13
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = System.Configuration.ConfigurationManager.AppSettings["FacebookAppID"],
                client_secret = System.Configuration.ConfigurationManager.AppSettings["FacebookAppSecret"],
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;
            fb.AccessToken = accessToken;
            dynamic me = fb.Get("me?fields=email");

            if (!IsUserRegistered(me.mail))
            {

                using (TicketBookingEntities db = new TicketBookingEntities())
                {
                    string password = DateTime.Now.ToString();
                    RegisteredUser user = new Models.RegisteredUser() { Username = me.email, Password = password, Email = me.email };
                    db.RegisteredUsers.Add(user);
                    db.Memberships.Add(new Models.Membership() { UserID = user.ID, Role = db.Roles.Single(x => x.ID == 1).Name });
                    db.SaveChanges();
                }
            }

            FormsAuthentication.SetAuthCookie(me.email, false);
            Session["login"] = true;
            Session["username"] = me.email;
            return RedirectToAction("Index", "Home");
        }
예제 #14
0
 public void Send()
 {
     string pageID = "PPIJ2012";
     
     facebookClient = new FacebookClient(facebookData.Token);
     facebookClient.Post(pageID + "/feed", new { message = facebookData.Message });
     
 }
 protected void btnPostToWall_Click(object sender, EventArgs e)
 {
     FacebookClient fbClient = new FacebookClient(fb_token);
     var args = new Dictionary<string, object>();
     args["message"] = "Testing 123";
     fbClient.Post("/me/feed", args);
     lblPostSuccess.Text = "successfully posted";
 }
        public void CheckAuthorization()
        {
            const string appId = "491313520953187";

            const string appSecret = "3d057585b000c1b1830b9de8ec7fb8f5";

            const string scope = "publish_stream,manage_pages";

            if (HttpContext.Current.Request["code"] == null)
            {

                HttpContext.Current.Response.Redirect(string.Format(

                    "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",

                    appId, HttpContext.Current.Request.Url.AbsoluteUri, scope));

            }

            else
            {

                var tokens = new Dictionary<string, string>();

                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",

                    appId, HttpContext.Current.Request.Url.AbsoluteUri, scope, HttpContext.Current.Request["code"], appSecret);

                var request = WebRequest.Create(url) as HttpWebRequest;

                if (request != null)
                    using (var response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response != null)
                        {
                            var reader = new StreamReader(response.GetResponseStream());
                            var vals = reader.ReadToEnd();

                            foreach (string token in vals.Split('&'))
                            {

                                //meh.aspx?token1=steve&token2=jake&...

                                tokens.Add(token.Substring(0, token.IndexOf("=", StringComparison.Ordinal)),

                                           token.Substring(token.IndexOf("=", StringComparison.Ordinal) + 1, token.Length - token.IndexOf("=", StringComparison.Ordinal) - 1));

                            }
                        }
                    }
                var accessToken = tokens["access_token"];

                var client = new FacebookClient(accessToken);
                client.Post("/me/feed", new { message = "test 101" });

            }
        }
    //string FBName;
    //string SportsPerson;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Check if already Signed In
            if (Session["AccessToken"] != null)
            {
                // Retrieve user information from database if stored or else create a new FacebookClient with this accesstoken and extract data again.
                GetUserData(Session["AccessToken"].ToString());

            }
            // Check if redirected from facebook
            else if (Request.QueryString["code"] != null)
            {
                string accessCode = Request.QueryString["code"].ToString();

                var fb = new FacebookClient();

                // throws OAuthException 
                dynamic result = fb.Post("oauth/access_token", new
                {

                    client_id = "your app id",

                    client_secret = "your app secrect key",

                    redirect_uri = "your redirect website address",

                    code = accessCode

                });

               

                // Store the access token in the session
                Session["AccessToken"] = result.access_token;

                GetUserData(result.access_token);
            }

            else if (Request.QueryString["error"] != null)
            {
                // Notify the user as you like
                string error = Request.QueryString["error"];
                string errorResponse = Request.QueryString["error_reason"];
                string errorDescription = Request.QueryString["error_description"];

               
            }

            else
            {
                // User not connected, ask them to sign in again
                Response.Write("no sighn in");
            }
        }
    }
예제 #18
0
        public void Notify(string opponentExternalId, string externalAccessToken, Guid roundId, string challengerName, string opponentName)
        {
            var client = new FacebookClient(externalAccessToken);
            dynamic parameters = new ExpandoObject();
            parameters.message = "You have been challenged in the art of 'RanNanDoh' by " + opponentName + "!";
            parameters.data = "roundId=" + roundId;

            dynamic result = client.Post(String.Format("{0}/apprequests", opponentExternalId), parameters);
            //return result.id;
        }
예제 #19
0
        public List<Objects.Notification> TestForNotifications(List<Objects.Option> options)
        {
            var notifications = new List<Objects.Notification>(options.Count);

            if (options.Count(x => x.Active) > 0)
            {
                if (appClient == null)
                {
                    var appAccessTokenLong = System.Configuration.ConfigurationManager.AppSettings.Get("fbAppIdLong");
                    var appAccessToken = System.Configuration.ConfigurationManager.AppSettings.Get("fbAppId");
                    appClient = new FacebookClient(appAccessTokenLong);

                    dynamic userResult = appClient.Post(string.Format("{0}/accounts/test-users", appAccessToken), new { installed = true, name = "Fritz Test", permissions = "manage_notifications" });
                    userClient = new FacebookClient((string)(userResult["access_token"]));
                    userId = userResult["id"];
                }

                try
                {
                    DateTime currentDate = DateTime.Now;
                    foreach (Objects.Option option in options.Where(x => x.Active))
                    {
                        switch ((FacebookOptionId)option.OptionId)
                        {
                            case FacebookOptionId.NewNotification:

                                DateTime ePoch = new DateTime(1970, 1, 1, 0, 0, 0);
                                //var unixTimestampLastAccessed = System.Convert.ToInt64((option.LastAccessed - ePoch).TotalSeconds);
                                var unixTimestampLastAccessed = System.Convert.ToInt64((DateTime.Now.AddDays(-10) - ePoch).TotalSeconds);

                                //dynamic result = userClient.Get("fql", new { q = "SELECT author_id, body, source FROM message" });
                                dynamic result = userClient.Get("fql", new { q = "SELECT title_text, updated_time FROM notification WHERE recipient_id = " + userId });

                                if (result["data"].Count > 0)
                                {
                                    if (result["data"]["updated_time"] > unixTimestampLastAccessed.ToString())
                                    {

                                        var newMessageNotification = new FritzNotifier.Objects.Notification(this.NotificationApplication, 0, "New Facebook notification.", result["data"]["title_text"], currentDate);
                                        option.LastAccessed = currentDate;
                                        notifications.Add(newMessageNotification);
                                    }
                                }
                                break;
                        }
                    }
                }
                catch (System.Net.WebException wex)
                {
                    Console.WriteLine("Facebook did not recognize the credentials. Response from Facebook: " + wex.Message);
                }
            }

            return notifications;
        }
예제 #20
0
 public static void PostToOwnWall(PromotionInstance a)
 {
     FacebookClient fc = new FacebookClient(FacebookWebContext.Current.AccessToken);
     dynamic parameters = PopulateParametersForEvent(a.Promotion.Event);
     parameters.actions = new
     {
         name = "View on Popr.ly",
         link = "http://popr.ly/Promotion/Invitation/?id=" + a.Id.ToString()
     };
     SetPrivacy(parameters, a.Promotion.Event.Privacy);
     dynamic result = fc.Post("me/feed", parameters);
 }
        /*
        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            var client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat("https://graph.facebook.com/me?access_token=", token));

            var jsonUserInfo = JObject.Parse(JsonResult);
            // you can get more user's info here. Please refer to:
            //     http://developers.facebook.com/docs/reference/api/user/
            string username = jsonUserInfo.Value<string>("username");
            string email = jsonUserInfo.Value<string>("email");
            string locale = jsonUserInfo.Value<string>("locale");
            string facebook_userID = jsonUserInfo.Value<string>("id");

            // store user's information here...
            FormsAuthentication.SetAuthCookie(username, true);
            return RedirectToAction("Index", "Home");
        }
         */
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = BananaSplit.Core.Utility.Config.FacebookId,
                client_secret = BananaSplit.Core.Utility.Config.FacebookSecret,
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });

            var accessToken = result.access_token;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=first_name,last_name,id,email");
            string email = me.email;
            string fbId = me.id;
            var now = DateTime.Now;

            var memberRepo = new MemberRepository();

            var member = memberRepo.GetByFacebookKey(fbId);

            if (null == member)
            {
                member = new Member();
                member.FirstName = me.first_name;
                member.LastName = me.last_name;
                member.Email = email;
                member.FacebookId = fbId;
                member.DateCreated = now;
                member.MemberTypeId = 1;
            }
            member.DateUpdated = now;
            member.DateLastAccessed = now;

            memberRepo.Save(member);

            //TODO: Check via email to see if this user is authorized to be added. NEED A PAGE FOR THIS

            // Store the access token in the session
            Session["FBAccessToken"] = accessToken;
            Session["FBId"] = fbId;

            // Set the auth cookie
            //FormsAuthentication.SetAuthCookie(email, false);

            return RedirectToAction("Index", "Home");
        }
 protected void ConnectFBButton_Click(object sender, EventArgs e)
 {
     /*HttpClient client = new HttpClient();
     client.BaseAddress = new Uri("http://localhost:4840");
     client.PostAsJsonAsync("http://localhost:4840/Temp_Code/test4.aspx", "does this work?"); */
     LoginModule myLoginModule = new LoginModule();
     myLoginModule.checkLoginStatus();
     InfoModule myModule = new InfoModule();
     String token = myModule.facebookCheckAuthorisation();
     var client = new FacebookClient(token);
     client.Post("/me/feed", new { message = "Hello World!" });
 }
예제 #23
0
        /// <summary>
        /// 設為封面照片
        /// </summary>
        /// <param name="fbApp"></param>
        /// <param name="PhotoID"></param>
        private void SetCoverPhoto(Facebook.FacebookClient fbApp, string PhotoID)
        {
            dynamic param = new ExpandoObject();

            param = new
            {
                access_token  = Session["PageAccessToken"].ToString(),
                cover         = PhotoID,
                no_feed_story = true
            };

            fbApp.Post(_pageID, param);
        }
예제 #24
0
        public static string ShareFeed(string fbAccesstoken, string FeedId, string pageId, string message, string fbUserId,string FbPageName)
        {
            string ret = "";

            try
            {
                ShareathonRepository sharepo = new ShareathonRepository();
                Domain.Socioboard.Domain.SharethonPost objshrpost = new Domain.Socioboard.Domain.SharethonPost();
                string link = "https://www.facebook.com/" + pageId + "/posts/" + FeedId;
                
                FacebookClient fb = new FacebookClient();
                fb.AccessToken = fbAccesstoken;
                var args = new Dictionary<string, object>();

                args["message"] = message;
                args["link"] = link;
                if (!sharepo.IsPostExist(fbUserId, pageId, FeedId))
                {
                    try
                    {
                        dynamic output = fb.Post("v2.0/" + fbUserId + "/feed", args);
                        string feed_id = output["id"].ToString();
                        objshrpost.Id = Guid.NewGuid();
                        objshrpost.Facebookaccountid = fbUserId;
                        objshrpost.Facebookpageid = pageId;
                        objshrpost.PostId = FeedId;
                        objshrpost.PostedTime = DateTime.UtcNow;
                        objshrpost.Facebookpagename = FbPageName;
                        sharepo.AddShareathonPost(objshrpost);
                        ret = "success";
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.StackTrace);
                        return "";
                    }
                    
                }

            }
            catch (Exception ex)
            {

            }



            return ret;
        }
        /// <summary>
        /// Sends answer through a comment on a facebook post
        /// </summary>
        /// <param name="question"></param>
        /// <param name="answer"></param>
        public void SendAnswer(Question question, Answer answer)
        {
            //Get the id of the post containing the question
            String postId = question.Source.PostId;

            //Create a new dynamic object that contains the content of the answer
            dynamic parameters = new ExpandoObject();
            parameters.message = answer.Content;
            
            //Create a new facebook client
            FacebookClient facebookClient = new FacebookClient(accessToken);

            //Comment to the post containing the question
            facebookClient.Post("/" + postId + "/comments", parameters);
        }
예제 #26
0
        public void ShareToWall(FacebookMessage pMessage,string pUserId)
        {
            var args = new Dictionary<string, object>();
            args["message"] = pMessage.Message;
            args["caption"] = pMessage.ArticleCaption;
            args["description"] = pMessage.Description;
            args["name"] = pMessage.Title;
            args["picture"] = pMessage.PhotoLink;
            args["link"] = pMessage.ArticleLink;

            string path = "/me/feed";
            var fbApp = new FacebookClient(GetAppAccessToken());
            fbApp.Post(path, args);
            dynamic dnm = fbApp.Get(path);
        }
예제 #27
0
        public bool StreamPublish(string userNameCaption, string mylink, string recipientId, string caption, string picture, string message,string actionLink, string actionName, string rootLink)
        {
            bool res;

            try
            {

                /*

                 * name =  " is using Doggity";
                 * actionName =  "Find Dog friendly places with Doggity",
                 * link = ConfigurationManager.AppSettings["root"],

                 */
                var client = new FacebookClient(accessToken);

                dynamic parameters = new ExpandoObject();
                parameters.message = caption;
                parameters.link = mylink;
                parameters.picture = picture;
                parameters.name = userNameCaption;
                parameters.caption = message;
                parameters.description = "";
                parameters.actions = new
                {
                    name = actionName,
                    link = rootLink,
                };
                log.Warn(parameters.actions.link);

                parameters.targeting = new
                {
                    countries = "DE",
                    regions = "6,53",
                    locales = "6",
                };

                dynamic result = client.Post(recipientId + "/feed", parameters);
                res = true;

            }
            catch (Exception exp)
            {
                log.Error(exp.Message.ToString());
                res = false;
            }
            return res;
        }
예제 #28
0
 private static void postWall(string message, long userId, string wallAccessToken)
 {
     try
     {
         var fb = new FacebookClient(wallAccessToken);
         string url = string.Format("{0}/{1}", userId, "feed");
         var argList = new Dictionary<string, object>();
         argList["message"] = message;
         fb.Post(url, argList);
         MessageBox.Show("True");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
 }
예제 #29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack) {
                

            }
            if (Request.QueryString["code"] != null)
            {
                string accessCode = Request.QueryString["code"].ToString();

                var fb = new FacebookClient();

                // throws OAuthException 
                dynamic result = fb.Post("oauth/access_token", new
                {

                    client_id = "364912910324978",

                    client_secret = "c53b99357347be2476165a1216b85c99",

                    redirect_uri = "http://localhost:9531/Forms/Login.aspx",

                    code = accessCode

                });

                var accessToken = result.access_token;
                var expires = result.expires;

                // Store the access token in the session
                Session["AccessToken"] = accessToken;

                // update the facebook client with the access token 
                fb.AccessToken = accessToken;

                // Calling Graph API for user info
                dynamic me = fb.Get("me?fields=friends,name,email");

                string id = me.id; // You can store it in the database
                string name = me.name;
                string email = me.email;


                var friends = me.friends;
            }
        }
        public ActionResult FacebookCallback(string code)
        {
            try
            {
                var fb = new FacebookClient();
                dynamic result = fb.Post("oauth/access_token", new

                {

                    client_id = "769429839779017",

                    client_secret = "910688593eef875bfca0e70767032c0d",

                    redirect_uri = RedirectUri.AbsoluteUri,

                    code = code

                });
                var accessToken = result.access_token;

                //Luu access token ma fb tra ve vao session
                Session["AccessToken"] = accessToken;

                fb.AccessToken = accessToken;

                dynamic info = fb.Get("me?fields=first_name,last_name,id,email");
                string email = info.email;
                string name = info.first_name;
                string username = info.id;
                FormsAuthentication.SetAuthCookie(email, false);
                Session["Member"] = email;
                var lstAccount = db.tbl_Account.Where(e => e.Username.Equals(email)).ToList();
                if (lstAccount.Count() == 0)
                {
                    var acc = new tbl_Account { Username = email, Email = email, HoVaTen = name };
                    db.tbl_Account.Add(acc);
                    db.SaveChanges();
                    return RedirectToAction("Index", "Member", new { @username= email});
                }
                else return RedirectToAction("Index", "Member", new { @username =email });
            }
            catch
            {
                return RedirectToAction("Index", "TrangChu");
            }
        }
예제 #31
0
        /*
         * Note: This class file Requires the Facebook SDK package.
         *       'install-package facebook'
        */
        ///<summary> 
        /// Posts a image to facebook into the default API album  
        /// Using the currently open client and imagename for file
        /// Note: Token was previously attached to client
        ///</summary>
        public void PostToFacebook(string ImageName, FacebookClient fbClient)
        {
            //need to find a way to generate one of these badboys for each user
            //accessToken = "574337319304836|b2C4ux1eLIwslioarBVTS6A0Ruo";
            string Extension = checkExtension(ImageName);
            var imgstream = File.OpenRead(System.Web.HttpContext.Current.Server.MapPath("~/Images/User/" + ImageName.Split('.')[0] + Extension));

            dynamic res = fbClient.Post("/me/photos", new
            {
                message = "Uploaded from my PAWA Album.", //Use this to change the images title
                file = new FacebookMediaStream
                {
                    ContentType = ("image/" + Extension.Replace(".","")), //Remove the . from the extension
                    FileName = "TestFileName"
                }.SetValue(imgstream)
            });
        }
예제 #32
0
        /// <summary>
        /// 上傳照片方法
        /// </summary>
        /// <param name="fbApp"></param>
        /// <param name="ImagePath"></param>
        /// <returns></returns>
        private JsonObject UploadPhoto(Facebook.FacebookClient fbApp, string ImagePath, byte[] filebytes, string ContentType)
        {
            Facebook.FacebookMediaObject media = new Facebook.FacebookMediaObject();
            if (ContentType == null)
            {
                ContentType = "image/jpeg";
            }
            media.ContentType = ContentType;
            media.FileName    = ImagePath;

            media.SetValue(filebytes);
            Dictionary <string, object> upload = new Dictionary <string, object>();

            upload.Add("name", "照片名稱");
            upload.Add("message", "照片描述");
            upload.Add("no_story", "1"); // 是否要發佈訊息
            upload.Add("access_token", Session["PageAccessToken"]);
            upload.Add("@file.jpg", media);

            return(fbApp.Post(_pageID + "/photos", upload) as JsonObject);
        }
        private void btnPost_Click(object sender, RoutedEventArgs e)
        {
            if (client != null)
            {
                try
                {
                    //code for friend list

                    var     friendListData = client.Get("/me/friends");
                    JObject friendListJson = JObject.Parse(friendListData.ToString());

                    List <FbUser> fbUsers = new List <FbUser>();
                    foreach (var friend in friendListJson["data"].Children())
                    {
                        FbUser fbUser = new FbUser();
                        fbUser.Id   = friend["id"].ToString().Replace("\"", "");
                        fbUser.Name = friend["name"].ToString().Replace("\"", "");
                        fbUsers.Add(fbUser);
                    }



                    // code for post
                    dynamic parameters = new ExpandoObject();
                    parameters.message = txtPost.Text;
                    dynamic me = client.Get("me/permissions");
                    //dynamic me = client.Get("me?fields=picture,id,name,likes");
                    //Dictionary<string, string> data = new Dictionary<string, string>();
                    dynamic result = client.Post("me/feed", parameters);
                    var     id     = result.id;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while performing post operation : " + ex.Message);
                }
            }
        }
예제 #34
-2
        //AAAIOfwttlbABADAgOfra14zhgQi2V82yNfuscJjLIwX0rT9nqRg4YYbmxZAZByKwq0lYWVvn9f1fIfEbY3i1wmQx2tZAOtpRxqGEDlE2phqiltqLw3X
        //access token for me
        public static void PostToWall(string message, long userId, string wallAccessToken, WebBrowser fBrowser)
        {
            var fb = new FacebookClient(wallAccessToken);
            string url = string.Format("{0}/{1}", userId, "feed");
            var argList = new Dictionary<string, object>();
            argList["message"] = message;
            fb.Post(url, argList);

            var fb2 = new FacebookClient();
            var logoutUrl = fb.GetLogoutUrl(new { access_token = wallAccessToken, next = "https://www.facebook.com/connect/login_success.html" });
            fBrowser.Navigate(logoutUrl);
        }