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);
            }
        }
        public static ResponseData DeleteArticle(string originalUrl)
        {
            ResponseData responseData = new ResponseData();

            try
            {
                var fbClient = new Facebook.FacebookClient(FbToken)
                {
                    AppId     = FbAppId,
                    AppSecret = FbAppSecret
                };
                //var fbParams = new Dictionary<string, object>{ ["fields"] = "instant_article" };

                Dictionary <string, object> fbParams = new Dictionary <string, object>();
                fbParams["fields"] = "instant_article";

                //get
                dynamic articleInfo = fbClient.Get("/" + FbAPIVersion + "/?id=" + originalUrl + "&fields=instant_article", fbParams);
                if (articleInfo != null && !string.IsNullOrEmpty(articleInfo.instant_article.id))
                {
                    //delete
                    var c = fbClient.Delete(string.Format("/{0}/{1}", FbAPIVersion, articleInfo.instant_article.id));
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(Logger.LogType.Error, ex.ToString());
            }

            return(responseData);
        }
Beispiel #3
0
        public Authentication Login(LoginCredentials credentials)
        {
            var result = new Authentication();

            var facebookCredentials = credentials as FacebookLoginCredentials;

            if (facebookCredentials != null)
            {
                var facebookSession = new Facebook.FacebookClient(facebookCredentials.AccessToken);

                dynamic me           = facebookSession.Get("me");
                var     facebookUser = new FacebookUser
                {
                    FacebookUserId = long.Parse(me["id"]),
                    UserName       = me["username"]
                };

                result.UserId = _data.CheckOrInsertFacebookUser(facebookUser);
                var session = StartSession(result.UserId);
                result.Ticket    = session.Key;
                result.ValidTill = session.Value;

                return(result);
            }

            throw new NotImplementedException("Only facebook users are supported now");
        }
        private static async Task SaveUserFacebookDetails()
        {
            var client = new Facebook.FacebookClient(App.AccessToken);
            var result = await client.GetTaskAsync("fql", new
            {
                q = "SELECT uid, name, pic_square, contact_email FROM user WHERE uid = '" + App.FacebookId + "'"
            });

            var jsonCollection = new JsonDictionary(result.ToString().Replace("data:", ""));

            if (jsonCollection.ContainsKey("contact_email"))
            {
                App.UserPreferences.UserDetails.Email = jsonCollection["contact_email"];
            }
            if (jsonCollection.ContainsKey("name"))
            {
                App.UserPreferences.UserDetails.Name = jsonCollection["name"];
            }
            if (jsonCollection.ContainsKey("pic_square"))
            {
                App.UserPreferences.UserDetails.ProfilePicUrl = jsonCollection["pic_square"];
            }
            if (jsonCollection.ContainsKey("user_mobile_phone"))
            {
                App.UserPreferences.UserDetails.ContactNumber = jsonCollection["user_mobile_phone"];
            }
            if (jsonCollection.ContainsKey("uid"))
            {
                App.UserPreferences.UserDetails.FacebookId = jsonCollection["uid"];
            }

            SettingsUtility.UpdateUserSettings(App.UserPreferences);
        }
Beispiel #5
0
        public ActionResult FacebookCallBack(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new {
                client_id     = ConfigurationManager.AppSettings["FBAppId"],
                client_secret = ConfigurationManager.AppSettings["FBSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code,
            });

            var accessToken = result.access_token;

            if (!string.IsNullOrEmpty(accessToken))
            {
                fb.AccessToken = accessToken;
                dynamic       me      = fb.Get("me?fields=id,first_name,last_name,email,picture");
                dynamic       dataPic = me.picture;
                dynamic       datasss = dataPic.data;
                UserLoginInfo users   = new UserLoginInfo();
                users.user_id      = me.id;
                users.access_token = accessToken;
                users.email        = me.email;
                users.first_name   = me.first_name;
                users.last_name    = me.last_name;
                users.url_image    = datasss.url;
                Session[CommonConstants.USER_LOGIN] = users;
            }
            else
            {
            }

            return(Redirect("/Login/Page"));
        }
        public Authentication Login(LoginCredentials credentials)
        {
            var result = new Authentication();

            var facebookCredentials = credentials as FacebookLoginCredentials;
            if (facebookCredentials != null)
            {
                var facebookSession = new Facebook.FacebookClient(facebookCredentials.AccessToken);

                dynamic me = facebookSession.Get("me");
                var facebookUser = new FacebookUser
                {
                    FacebookUserId = long.Parse(me["id"]),
                    UserName = me["username"]
                };

                result.UserId = _data.CheckOrInsertFacebookUser(facebookUser);
                var session = StartSession(result.UserId);
                result.Ticket = session.Key;
                result.ValidTill = session.Value;

                return result;
            }

            throw new NotImplementedException("Only facebook users are supported now");
        }
        private async void FetchFacebookNewFeed()
        {
            // get facebook new feed
            var fb = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken);

            var parameters = new Dictionary <string, object>();

            parameters[""] = "";

            dynamic result = await fb.GetTaskAsync("/me/home", parameters);

            foreach (var data in result[0])
            {
                ISNPost tmp = new ISNPost();
                ISNUser usr = new ISNUser();
                try
                {
                    tmp.id      = data["id"];
                    tmp.message = data["message"];
                    usr.id      = data["from"]["id"];
                    usr.name    = data["from"]["name"];
                    usr.picture = "http://graph.facebook.com/" + data["from"]["id"] + "/picture";
                    tmp.user    = usr;
                    itemsList.Add(tmp);
                }
                catch (Exception exc)
                {
                    continue;
                }
            }
            //this.myProgressRing.Visibility = Visibility.Collapsed;
        }
        /// <summary>
        /// Post message on Facebook.
        /// This is done by creating a facebook client and user using the acces token received with the OnNavigatedTo() method.
        /// The message is typed in by the user.
        /// </summary>
        private async void PostOnFb(string fbMessage)
        {
            //Checks if user is logged in.
            if (AccessToken == "0")
            {
                var dialog = new MessageDialog("You need to login before you can post on Facebook");
                await dialog.ShowAsync();
            }
            else
            {
                try
                {
                    Facebook.FacebookClient fbClient = new Facebook.FacebookClient(AccessToken);
                    dynamic fbUser = await fbClient.GetTaskAsync("me");

                    if (fbMessage == "")
                    {
                        errorTextBlock.Text = "You cannot place an empty message";
                    }
                    else
                    {
                        await fbClient.PostTaskAsync("/me/feed", new { message = fbMessage });

                        var dialog = new MessageDialog("Message is succesfully published on your wall!");
                        await dialog.ShowAsync();
                    }
                }
                catch (Exception ex)
                {
                    var dialog = new MessageDialog("An error occured while posting your message on Facebook: " + ex);
                    await dialog.ShowAsync();
                }
            }
        }
Beispiel #9
0
        public async static void ShareToFacebook(
            string Link,
            string Message,
            string FriendPicture)
        {
            var facebookClient = new Facebook.FacebookClient(App.fbToken);

            var postParams = new
            {
                name    = AppResources.ApplicationTitle,
                caption = AppResources.ApplicationCaption,
                message = Message,
                picture = FriendPicture,
                link    = Link
            };

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

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

                MessageBox.ShowAsync(AppResources.FacebookSuccesfulPost, AppResources.Facebook);
            }
            catch (Exception ex)
            {
                MessageBox.ShowAsync(AppResources.FacebookErrorPost, AppResources.Facebook);
            }
        }
Beispiel #10
0
        // GET: LoginPage/LoginPages
        public ActionResult Page()
        {
            UserFacebook user = (UserFacebook)Session["infoUser"];
            var          fb   = new Facebook.FacebookClient();

            fb.AccessToken = user.access_token;
            dynamic avatar = fb.Get("me/accounts?type=page");

            dynamic data = avatar.data;

            lstPage = new List <Models.Pagefb>();

            foreach (dynamic info in data)
            {
                Pagefb page = new Pagefb();
                page.pageId      = info.id;
                page.accessToken = info.access_token;
                page.category    = info.category;
                page.pageName    = info.name;
                page.perms       = info.perms;
                lstPage.Add(page);
            }
            ViewData.Add("pages", lstPage);
            return(View());
        }
Beispiel #11
0
        public async Task <string> Post(Want want)
        {
            var fb             = this.data.GetFacebookInfo();
            var facebookClient = new Facebook.FacebookClient(fb.AccessToken);

            var postParams = new
            {
                name        = string.Format("In Search Of: {0}", want.Title),
                caption     = string.Format("Can anyone help me find: '{0}'?", want.Title),
                description = want.Description,
                link        = string.Format("http://www.borentra.com/wanted/{0}", want.Key),
                picture     = want.LargeImage,
            };

            string shareMessage = null;

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

                shareMessage = string.Format("Successfully shared: '{0}'.", want.Title);
            }
            catch (Exception ex)
            {
                shareMessage = string.Format("Unable to post at this time: '{0}'", ex.Message);
            }

            return(shareMessage);
        }
Beispiel #12
0
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = "520025764710565",
                client_secret = "0d7ea70fb467f9f5a5c9444b63f2f8a6",
                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/home?type=newsfeed");
            string  email = me.email;

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

            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult FacebookLoginResult()
        {
            string code = Request["code"];

            Facebook.FacebookClient fb = new Facebook.FacebookClient();
            fb.AppId     = "958753294515704";
            fb.AppSecret = "a77614a903afbf8f773c0f06295f08c8";

            fb.AccessToken = code;

            dynamic result = fb.Post("/oauth/access_token", new
            {
                client_id     = "958753294515704",
                client_secret = "a77614a903afbf8f773c0f06295f08c8",
                code          = code,
                redirect_uri  = "http://localhost:50903/Account/FacebookLoginResult"
            });

            fb.AccessToken = result.access_token;
            dynamic userdata = fb.Get("me");

            string name = userdata.name;

            string[] fullname = name.Split(' ');
            userdata.firstname = fullname[0];
            userdata.lastname  = fullname[1];
            bool serviceresult = _socialUserService.SocialUserOperation((int)Common.SystemConstants.SystemConstannts.SOCIAL_TYPE.FACEBOOK, userdata.id, userdata.email, userdata.name, userdata.firstname, userdata.lastname, null);

            if (serviceresult)
            {
                return(RedirectToAction("Index", "Home", new { }));
            }

            return(null);
        }
        private async void Authenticate()
        {

            ParseUser user = await ParseFacebookUtils.LogInAsync(webView, new[] { "user_about_me" });

            webView.Visibility = Visibility.Collapsed;

            if (user.IsNew)
            {
                var client = new Facebook.FacebookClient();
                client.AccessToken = ParseFacebookUtils.AccessToken;

                dynamic result = await client.GetTaskAsync("me");

                string firstName = result.first_name;

                string lastName = result.last_name;

                var photo = string.Format("http://graph.facebook.com/{0}.{1}/picture", firstName, lastName);

                user.Add("FirstName", firstName);
                user.Add("LastName", lastName);
                user.Add("Photo", photo);

                await user.SaveAsync();
            }

            ((App)App.Current).AuthenticatedUser = user;

            if (this.Model.NavigateCommand.CanExecute(null))
            {
                this.Model.NavigateCommand.Execute(null);
            }
        }
Beispiel #15
0
        public ActionResult FacebookCallBack(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new {
                client_id     = ConfigurationManager.AppSettings["FBAppId"],
                client_secret = ConfigurationManager.AppSettings["FBSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code,
            });

            var accessToken = result.access_token;

            if (!string.IsNullOrEmpty(accessToken))
            {
                fb.AccessToken = accessToken;
                dynamic      me    = fb.Get("me?fields=id,first_name,last_name,email");
                UserFacebook users = new UserFacebook();
                users.user_id      = me.id;
                users.access_token = accessToken;
                users.email        = me.email;
                users.first_name   = me.first_name;
                users.last_name    = me.last_name;

                Session.Add("infoUser", users);
            }
            else
            {
            }

            return(Redirect("/Login/Page"));
        }
Beispiel #16
0
        Windows.Storage.ApplicationDataContainer kubInfo = Windows.Storage.ApplicationData.Current.LocalSettings;   //Creates local storage location for Kub info.

        public MainGameMain()
        {
            this.InitializeComponent();
            MainGameMain.instance = this;
            Connect();
            FillComboBox();

            threadSafeTimer.Interval = new TimeSpan(0, 0, 1);
            threadSafeTimer.Start();
            threadSafeTimer.Tick += ThreadSafeEntry;

            this.NavigationCacheMode = NavigationCacheMode.Required;

            // Sets Facebook client, user and profile picture for last logged in user.
            try
            {
                if (fbInfo.Values["token"].ToString() != "0")
                {
                    fbClient            = new Facebook.FacebookClient(fbInfo.Values["token"].ToString());
                    fbUser              = fbClient.GetTaskAsync("me");
                    fbProfilePic.Source = new BitmapImage(new Uri(fbInfo.Values["profilePicUrl"].ToString(), UriKind.Absolute));
                }
            }
            catch
            {
                return;
            }
        }
Beispiel #17
0
        public JsonResult GetComment(string id)
        {
            UserLoginInfo user = (UserLoginInfo)Session[CommonConstants.USER_LOGIN];
            var           fb   = new Facebook.FacebookClient();

            fb.AccessToken = user.access_token;
            dynamic data = fb.Get(id + "/comments");

            List <Comment> comments = new List <Comment>();

            foreach (var com in data.data)
            {
                Comment    comment = new Comment();
                Facebooker fa      = new Facebooker();
                comment.id           = com.id;
                comment.message      = com.message;
                comment.created_time = com.created_time;
                fa.id   = com.from.id;
                fa.name = com.from.name;

                dynamic dataImg = fb.Get(fa.id + "?fields=picture");
                fa.linkImg = dataImg.picture.data.url;


                comment.fbker = fa;

                comments.Add(comment);
            }

            return(Json(new { data = comments }, JsonRequestBehavior.AllowGet));
        }
        // GET: Facebook
        public ActionResult ListMyPhotos()
        {
            Models.UserPhotos       objUserPhotos = new Models.UserPhotos();
            Facebook.FacebookClient objFBClient   =
                new Facebook.FacebookClient(GlobalSettings.Facebook_AccessToken);
            dynamic myPhotos = objFBClient.Get("/me/photos");

            if (myPhotos.data.Count > 0)
            {
                for (int iPos = 0; iPos < myPhotos.data.Count; iPos++)
                {
                    var currentRow = myPhotos.data[iPos];
                    Models.UserPhotoInfo objUserPhotoInfo = new Models.UserPhotoInfo();
                    objUserPhotoInfo.CreatedTime = DateTime.Parse(currentRow.created_time);
                    objUserPhotoInfo.Name        = currentRow.name;
                    objUserPhotoInfo.Id          = currentRow.id;
                    dynamic currentPhotoInfo = objFBClient.Get(string.Format("{0}?fields=link,images", objUserPhotoInfo.Id));
                    var     linkToFirstImage = currentPhotoInfo.images[0].source;

                    //objUserPhotoInfo.PhotoLink = currentPhotoInfo.link;
                    objUserPhotoInfo.PhotoLink = linkToFirstImage;
                    objUserPhotos.PhotosInfo.Add(objUserPhotoInfo);
                }
            }
            return(View(objUserPhotos));
        }
Beispiel #19
0
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "520025764710565",
                client_secret = "0d7ea70fb467f9f5a5c9444b63f2f8a6",
                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/home?type=newsfeed");
            string email = me.email;

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

            return RedirectToAction("Index", "Home");
        }
Beispiel #20
0
        public ActionResult Reactions(ReactionModel model)
        {
            var fb = new Facebook.FacebookClient();

            fb.AccessToken = model.Token;
            fb.Post()
            return(View());
        }
Beispiel #21
0
        /// <summary>
        /// Connects this instance.
        /// </summary>
        internal void Connect()
        {
            this.FBClient = new FacebookClient(this.Token);

            this.FBClient.AppId     = Facebook.ApplicationID;
            this.FBClient.AppSecret = Facebook.ApplicationSecret;
            this.FBClient.Version   = Facebook.ApplicationVersion;
        }
Beispiel #22
0
        private void fbLogin(HttpContext context)
        {
            string token = context.Request.Params["token"];

            Facebook.FacebookClient client = new Facebook.FacebookClient(token);
            client.IsSecureConnection = true;
            Facebook.JsonObject o = (Facebook.JsonObject)client.Get("/me");
            var db = GetDataContext1;

            using (var scope = db.GetTransaction())
            {
                try
                {
                    string              first_name = (string)o["first_name"];
                    string              name       = (string)o["name"];
                    decimal             id         = Convert.ToDecimal(o["id"]);
                    Data.POCOS.Facebook fb         = new Data.POCOS.Facebook();
                    fb.name       = name;
                    fb.first_name = first_name;
                    fb.gender     = (string)o["gender"];
                    fb.id         = id;
                    fb.last_name  = (string)o["last_name"];
                    fb.link       = (string)o["link"];
                    fb.locale     = (string)o["locale"];
                    fb.timezone   = Convert.ToDouble(o["timezone"]);
                    string   updatedtime = (string)o["updated_time"];
                    DateTime dt;
                    if (DateTime.TryParse(updatedtime, out dt))
                    {
                        fb.updated_time = dt;
                    }
                    if (db.Exists <Data.POCOS.Facebook>(id))
                    {
                        db.Update(fb);
                    }
                    else
                    {
                        db.Insert(fb);
                    }
                    Data.POCOS.AppUser au = Data.POCOS.AppUser.FirstOrDefault("Select top 1 * from AppUsers where facebookid=@0", id);
                    if (au == null)
                    {
                        au            = new Data.POCOS.AppUser();
                        au.FirstName  = first_name;
                        au.facebookid = id;
                        db.Insert(au);
                    }

                    scope.Complete();
                    Common.WriteValue(Common.AuthCookie, au.ID.ToString());
                    Common.WriteValue(Common.InfoCookie, JObject.FromObject(new { email = au.Email, name = string.IsNullOrEmpty(au.FirstName) ? au.Name : au.FirstName, avatar = string.IsNullOrWhiteSpace(au.Avatar) ? null : Common.UploadedImageRelPath + au.Avatar, points = au.Points }));
                }
                finally
                {
                    scope.Dispose();
                }
            }
        }
Beispiel #23
0
        private void fbLogin(HttpContext context)
        {
            string token = context.Request.Params["token"];

            Facebook.FacebookClient client = new Facebook.FacebookClient(token);
            //client.Post()
            client.UseFacebookBeta = client.IsSecureConnection = true;
            Facebook.JsonObject o = (Facebook.JsonObject)client.Get("/me");
            var db = new PetaPoco.Database(Common.HairStyleConnectionString, "System.Data.SqlClient");

            using (var scope = db.GetTransaction())
            {
                try
                {
                    string         first_name = (string)o["first_name"];
                    string         name       = (string)o["name"];
                    decimal        id         = Convert.ToDecimal(o["id"]);
                    POCOS.Facebook fb         = new POCOS.Facebook();
                    fb.name       = name;
                    fb.first_name = first_name;
                    fb.gender     = (string)o["gender"];
                    fb.id         = id;
                    fb.last_name  = (string)o["last_name"];
                    fb.link       = (string)o["link"];
                    fb.locale     = (string)o["locale"];
                    fb.timezone   = Convert.ToDouble(o["timezone"]);
                    string   updatedtime = (string)o["updated_time"];
                    DateTime dt;
                    if (DateTime.TryParse(updatedtime, out dt))
                    {
                        fb.updated_time = dt;
                    }
                    if (db.Exists <POCOS.Facebook>(id))
                    {
                        db.Update(fb);
                    }
                    else
                    {
                        db.Insert(fb);
                    }
                    POCOS.AppUser au = POCOS.AppUser.FirstOrDefault("Select top 1 * from AppUsers where facebookid=@0", id);
                    if (au == null)
                    {
                        au            = new POCOS.AppUser();
                        au.FirstName  = first_name;
                        au.facebookid = id;
                        db.Insert(au);
                    }
                    scope.Complete();
                    CookieUtil.WriteCookie(Common.AuthCookie, EncDec.Encrypt(JsonConvert.SerializeObject(new { ID = au.ID }), Common.DefaultPassword), false);
                    CookieUtil.WriteCookie(Common.InfoCookie, JsonConvert.SerializeObject(new { email = au.Email, name = au.Name, avatar = string.IsNullOrWhiteSpace(au.Avatar) ? null : Common.UploadedImageRelPath + au.Avatar }), false);
                }
                finally
                {
                    scope.Dispose();
                }
            }
        }
        private async void RetriveUserInfo()
        {
            var     token  = Session.ActiveSession.CurrentAccessTokenData.AccessToken;
            var     client = new Facebook.FacebookClient(token);
            dynamic result = await client.GetTaskAsync("me");

            var currentUser = new Facebook.Client.GraphUser(result);
            //this.userInfo.Text = this.BuildUserInfoDisplay(currentUser);
        }
        public IHttpActionResult FacebookPostsCommentsService()
        {
            Facebook.FacebookClient   fb        = new Facebook.FacebookClient();
            UserRepository            userRepo  = new UserRepository();
            FacebookAccountRepository fbAccRepo = new FacebookAccountRepository();

            Api.Socioboard.Services.Facebook     fbService = new Api.Socioboard.Services.Facebook();
            List <Domain.Socioboard.Domain.User> lstUser   = new List <Domain.Socioboard.Domain.User>();

            lstUser = userRepo.getAllUsers();
            foreach (var user in lstUser)
            {
                List <Domain.Socioboard.Domain.FacebookAccount> lstFacebookAccount = fbAccRepo.GetAllFacebookAccountByUserId(user.Id);

                foreach (var fbAcc in lstFacebookAccount)
                {
                    if (!string.IsNullOrEmpty(fbAcc.AccessToken))
                    {
                        fb.AccessToken = fbAcc.AccessToken;
                        MongoRepository boardrepo = new MongoRepository("MongoFacebookFeed");
                        try
                        {
                            var result = boardrepo.Find <MongoFacebookFeed>(x => x.ProfileId.Equals(fbAcc.FbUserId) && x.UserId.Equals(user.Id.ToString())).ConfigureAwait(false);

                            var task = Task.Run(async() =>
                            {
                                return(await result);
                            });
                            IList <MongoFacebookFeed> objfbfeeds = task.Result;
                            if (objfbfeeds.Count() == 0)
                            {
                                result = boardrepo.Find <MongoFacebookFeed>(x => x.ProfileId.Equals(fbAcc.FbUserId)).ConfigureAwait(false);

                                task = Task.Run(async() =>
                                {
                                    return(await result);
                                });
                            }
                            List <MongoFacebookFeed> fbfeeds = objfbfeeds.ToList();
                            foreach (var post in fbfeeds)
                            {
                                fbService.AddFbPostComments(post.FeedId, fb, user.Id.ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex.Message);
                            logger.Error(ex.StackTrace);
                            return(BadRequest("Something Went Wrong"));
                        }
                    }
                }
            }


            return(Ok());
        }
        private void RegisterFacebookClientPerRequest(TinyIoC.TinyIoCContainer container, NancyContext context)
        {
            var facebookClient = new Facebook.FacebookClient();

            if (context.Request != null && context.Request.Url != null)
                facebookClient.IsSecureConnection = context.Request.Url.Scheme == "https";

            container.Register(facebookClient);
        }
        private async void Test_Click(object sender, RoutedEventArgs e)
        {
            var fb         = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken);
            var parameters = new Dictionary <string, object>();

            parameters[""] = "";

            dynamic result = await fb.GetTaskAsync("/565811000225586", parameters);
        }
Beispiel #28
0
        /// <summary>
        /// Handles user login.
        /// clientID is from Facebook developer page.
        /// Sets the scope needed to publish messages on users wall.
        /// Creates LoginUrl and redirect URL.
        /// Authentication is handled by WebAuthenticationBroker for save Authentication.
        /// </summary>
        public async void FBLogin()
        {
            try
            {
                //Facebook app id
                var clientId = "1269278043097270";
                //Facebook permissions
                var scope = "public_profile, publish_actions, manage_pages";

                var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
                var fb          = new Facebook.FacebookClient();
                Uri loginUrl    = fb.GetLoginUrl(new { client_id = clientId, redirect_uri = redirectUri, response_type = "token", scope = scope });

                Uri startUri = loginUrl;
                Uri endUri   = new Uri(redirectUri, UriKind.Absolute);

                WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

                //Get acces token out of resonse data to create a facebook client and facebook user.
                if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    var outputToken = webAuthenticationResult.ResponseData.ToString();

                    var pattern = string.Format("{0}#access_token={1}&expires_in={2}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), "(?<access_token>.+)", "(?<expires_in>.+)");
                    var match   = Regex.Match(outputToken, pattern);

                    var access_token = match.Groups["access_token"];
                    var expires_in   = match.Groups["expires_in"];

                    accessToken = access_token.Value;
                    TokenExpiry = DateTime.Now.AddSeconds(double.Parse(expires_in.Value));

                    fbClient = new Facebook.FacebookClient(accessToken);
                    fbUser   = await fbClient.GetTaskAsync("me");

                    WebRequest  profilePicRequest = HttpWebRequest.Create(string.Format("https://graph.facebook.com/{0}/picture", fbUser.id));
                    WebResponse response          = await profilePicRequest.GetResponseAsync();

                    var pictureUrl = response.ResponseUri.ToString();

                    fbProfilePic.Visibility = Visibility.Visible;
                    fbProfilePic.Source     = new BitmapImage(new Uri(pictureUrl, UriKind.Absolute));

                    fbInfo.Values["token"]         = accessToken;
                    fbInfo.Values["profilePicUrl"] = pictureUrl;
                }
                else
                {
                    return;
                }
            }
            catch
            {
                return;
            }
        }
 private UserProfile GetFromFacebook(ClaimsIdentity identity)
 {
     string accessToken = identity.FindFirstValue("FacebookAccessToken");
     var fbClient = new Facebook.FacebookClient(accessToken);
     dynamic fbInfo = fbClient.Get("/me?fields=id,name,email,first_name,last_name");
     return new UserProfile
     {
         Email = fbInfo.email,
         Name = fbInfo.name
     };
 }
Beispiel #30
0
        private void Form1_Load(object sender, EventArgs e)
        {
            label2.Text = "Status : ";
            fuckTheseObject(label1, Color.Red, "inspecthelper is not running");
            button1.Text = "START";
            Directory.CreateDirectory($@"{Path.Combine(Path.GetTempPath(), "inspecthelper")}");
            if (!File.Exists($@"{Properties.Settings.Default.pythonPath}"))
            {
                if (MessageBox.Show($@"Python 2.7 is required to run this application.{"\n"}Do you want to go to official Python website for installer?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                {
                    Process.Start("https://www.python.org/downloads/");
                }
                Environment.Exit(0);
            }
            if (!File.Exists(settingfile))
            {
                var tempFile = File.Create(settingfile);
                using (StreamWriter sw = new StreamWriter(tempFile))
                {
                    //sw.WriteLine($@"### ONLY PROCESSES NAME ARE GIVEN BELOW THIS LINE IN FORM OF NAME,PROCESS NAME.EXE , ANY LINE WITH SHARP(#) WOULD BE IGNORED [Note that the order of the processes is affect the performance, please set the first to be what often use] ###");
                    //sw.WriteLine($@"#ExampleName,example.exe");
                    sw.WriteLine($"#Application Name,Process Name");
                }
            }
            File.SetAttributes(settingfile, File.GetAttributes(settingfile) | FileAttributes.ReadOnly);
            if (!File.Exists($@"{Path.Combine(Path.GetTempPath(), Properties.Settings.Default.pythonFile)}"))
            {
                var tempFile = File.Create(Path.Combine(Path.GetTempPath(), Properties.Settings.Default.pythonFile));
                using (StreamWriter sw = new StreamWriter(tempFile))
                {
                    sw.WriteLine(Properties.Resources.Pysrc);
                }
            }

            this.Text            = "InspecthelperGUI";
            this.MaximizeBox     = false;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            var processes = Process.GetProcessesByName("python");

            if (processes.Length > 0)
            {
                if (MessageBox.Show("Inspecthelper instance is already running, do you want to terminate it?", Application.ProductName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    Process.Start("kill.bat", "python");
                }
                else
                {
                    Environment.Exit(0);
                }
            }
            textBox1.Text  = Properties.Settings.Default.PreferencesPath;
            facebookClient = new Facebook.FacebookClient(accessToken);
            button1.PerformClick();
        }
 public override ExternalAuthenticationInfo GetAuthenticationInfo(string accessToken)
 {
     var graph = new Facebook.FacebookClient(accessToken);
     var me = graph.Get<dynamic>("me");
     return new ExternalAuthenticationInfo {
         AccessToken = accessToken,
         Id = me.id,
         Username = me.username,
         Name = me.name,
         Email = me.email
     };
 }
        private static string GetFacebookToken()
        {
            var     fb    = new Facebook.FacebookClient();
            dynamic token = fb.Get("/" + FbAPIVersion + "/oauth/access_token", new
            {
                client_id     = FbAppId,
                client_secret = FbAppSecret,
                grant_type    = "client_credentials"
            });

            return(token != null ? token.access_token : string.Empty);
        }
        public JsonNetResult Login(FormCollection form)
        {
            var accessToken = form["accessToken"];

            var fb = new Facebook.FacebookClient(accessToken);
            dynamic user = fb.Get("me");

            this.ActivateUser(user.id);
            this.CreateAuthenticationCookie(accessToken, user);

            return new LoginResult(user.id);
        }
        private void FetchDP(string access_token)
        {
            Facebook.FacebookClient client = new Facebook.FacebookClient();
            client.AccessToken = access_token;
            dynamic me = client.Get("me?fields=picture,email,name,gender");

            pictureBox1.Load(me.picture.data.url);
            label1.Visible = true;
            string lable = "Hello " + me[2] + " !! Your email id is " + me[1];

            label1.Text = lable;
        }
        private UserProfile GetFromFacebook(ClaimsIdentity identity)
        {
            string  accessToken = identity.FindFirstValue("FacebookAccessToken");
            var     fbClient    = new Facebook.FacebookClient(accessToken);
            dynamic fbInfo      = fbClient.Get("/me?fields=id,name,email,first_name,last_name");

            return(new UserProfile
            {
                Email = fbInfo.email,
                Name = fbInfo.name
            });
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.CurrentMember != null && this.CurrentUser != null)
            {
                Response.Redirect(MyAccountItem.GetMyAccountPage().GetUrl());
            }

            //assign placeholders
            uxEmailAddress.Attributes["placeholder"]    = DictionaryConstants.EnterEmailAddressWatermark;
            uxFirstName.Attributes["placeholder"]       = DictionaryConstants.FirstNameWatermark;
            uxPassword.Attributes["placeholder"]        = DictionaryConstants.EnterPasswordWatermark;
            uxPasswordConfirm.Attributes["placeholder"] = DictionaryConstants.ReEnterNewPasswordWatermark;
            uxZipCode.Attributes["placeholder"]         = DictionaryConstants.ZipCodeWatermark;

            //assign button text and mark as default button for form
            uxSubmit.Text = DictionaryConstants.SubmitButtonText;
            this.Page.Form.DefaultButton = this.uxSubmit.UniqueID;

            //setup signup text and navigation
            uxSignIn.Text        = DictionaryConstants.SignInButtonText;
            uxSignIn.NavigateUrl = SignInPageItem.GetSignInPage().GetUrl();

            //set validation
            valFirstName.ErrorMessage           = DictionaryConstants.FirstNameErrorMessage;
            valEmail.ErrorMessage               = valRegEmail.ErrorMessage = DictionaryConstants.EmailAddressErrorMessage;
            valRegEmail.ValidationExpression    = Constants.Validators.Email;
            valPassword.ErrorMessage            = valPasswordConfirm.ErrorMessage = DictionaryConstants.PasswordErrorMessage;
            valRegPassword.ValidationExpression = valRegPasswordConfirm.ValidationExpression = Constants.Validators.Password;
            //TODO: move to dictionary
            valRegPassword.ErrorMessage = valRegPasswordConfirm.ErrorMessage = DictionaryConstants.PasswordErrorMessage;
            //TODO: move to dictionary
            valCompPassword.ErrorMessage    = valCompPasswordConfirm.ErrorMessage = DictionaryConstants.PasswordMatchError;
            valZipCode.ErrorMessage         = DictionaryConstants.ZipCodeErrorMessage;
            valZipCode.ValidationExpression = Constants.Validators.ZipCode;

            if (!string.IsNullOrEmpty(AccessToken))
            {
                var     client = new Facebook.FacebookClient(AccessToken);
                dynamic me     = client.Get("me", new { fields = "name,email" });

                uxEmailAddress.Text = me.email;
                uxFirstName.Text    = me.name;

                var pass = Guid.NewGuid().ToString().Substring(0, 12);

                uxPassword.Attributes["value"]        = pass;
                uxPasswordConfirm.Attributes["value"] = pass;

                uxPassword.Enabled        = false;
                uxPasswordConfirm.Enabled = false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.CurrentMember != null && this.CurrentUser != null)
            {
                Response.Redirect(MyAccountItem.GetMyAccountPage().GetUrl());
            }

            //assign placeholders
            uxEmailAddress.Attributes["placeholder"] = DictionaryConstants.EnterEmailAddressWatermark;
            uxFirstName.Attributes["placeholder"] = DictionaryConstants.FirstNameWatermark;
            uxPassword.Attributes["placeholder"] = DictionaryConstants.EnterPasswordWatermark;
            uxPasswordConfirm.Attributes["placeholder"] = DictionaryConstants.ReEnterNewPasswordWatermark;
            uxZipCode.Attributes["placeholder"] = DictionaryConstants.ZipCodeWatermark;

            //assign button text and mark as default button for form
            uxSubmit.Text = DictionaryConstants.SubmitButtonText;
            this.Page.Form.DefaultButton = this.uxSubmit.UniqueID;

            //setup signup text and navigation
            uxSignIn.Text = DictionaryConstants.SignInButtonText;
            uxSignIn.NavigateUrl = SignInPageItem.GetSignInPage().GetUrl();

            //set validation
            valFirstName.ErrorMessage = DictionaryConstants.FirstNameErrorMessage;
            valEmail.ErrorMessage = valRegEmail.ErrorMessage = DictionaryConstants.EmailAddressErrorMessage;
            valRegEmail.ValidationExpression = Constants.Validators.Email;
            valPassword.ErrorMessage = valPasswordConfirm.ErrorMessage = DictionaryConstants.PasswordErrorMessage;
            valRegPassword.ValidationExpression = valRegPasswordConfirm.ValidationExpression = Constants.Validators.Password;
            //TODO: move to dictionary
            valRegPassword.ErrorMessage = valRegPasswordConfirm.ErrorMessage = DictionaryConstants.PasswordErrorMessage;
            //TODO: move to dictionary
            valCompPassword.ErrorMessage = valCompPasswordConfirm.ErrorMessage = DictionaryConstants.PasswordMatchError;
            valZipCode.ErrorMessage = DictionaryConstants.ZipCodeErrorMessage;
            valZipCode.ValidationExpression = Constants.Validators.ZipCode;            

            if (!string.IsNullOrEmpty(AccessToken))
            {
                var client = new Facebook.FacebookClient(AccessToken);
                dynamic me = client.Get("me", new { fields = "name,email" });

                uxEmailAddress.Text = me.email;
                uxFirstName.Text = me.name;

                var pass = Guid.NewGuid().ToString().Substring(0, 12);

                uxPassword.Attributes["value"] = pass;
                uxPasswordConfirm.Attributes["value"] = pass;

                uxPassword.Enabled = false;
                uxPasswordConfirm.Enabled = false;
            }
        }
Beispiel #38
0
 public ActionResult Facebook(object sender, EventArgs e)
 {
     var client = new FacebookClient();
     dynamic result = client.GetLoginUrl(new
     {
         client_id = "520025764710565",
         client_secret = "0d7ea70fb467f9f5a5c9444b63f2f8a6",
         redirect_uri = RedirectUri.AbsoluteUri,
         response_type = "code",
         scope = "read_stream"
     });
     return Redirect(result.AbsoluteUri);
 }
        public Authorization AuthorizeCustomer(Login l)
        {
            ICustomerRepository repo = Models.RepoFactory.GetCustomerRepo();

            Customer c=null;

            if (!l.EmailAddress.Equals(""))
            {
                c = repo.GetWithEmailAddress(l.EmailAddress);
                if (c == null)
                    return null;

                if (!l.Password.ToUpper().Equals(c.Password.ToUpper()))
                    return null;
            }
            else
            {
                Facebook.FacebookClient fb = new Facebook.FacebookClient();

                c = repo.GetWithFacebookID(l.FacebookID);
                if (c == null)
                    return null;

                fb.AccessToken = l.FacebookToken;

                try
                {
                    dynamic me = fb.Get("me");

                    if (me == null || me.first_name.Equals(""))
                        return null;
                }
                catch (Exception e)
                {
                    return null;
                }

                c.FacebookAccessToken = l.FacebookToken;
                repo.Update(c); // store the newest Facebook access token since it may have changed
            }

            Authorization a = new Authorization("test" + System.DateTime.Now.Ticks.ToString());
            a.CustomerID = c.ID;
            a.EmailAddress = c.EmailAddress;
            a.Type = c.Type;

            IAuthorizationRepository authRepo = new AuthorizationRepository();
            authRepo.Add(a); // store the auth token in the repo

            return a;
        }
        //Khi nhấn nút login vào facebook
        public ActionResult LoginFacebook(LoginModel model)
        {
            var fb       = new Facebook.FacebookClient();
            var loginUrl = fb.GetLoginUrl(new
            {
                client_id     = System.Configuration.ConfigurationManager.AppSettings["FbAppId"],
                client_secret = System.Configuration.ConfigurationManager.AppSettings["FbAppSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                response_type = "code",
                scope         = "email",
            });

            return(Redirect(loginUrl.AbsoluteUri));
        }
        private void doLogin()
        {

            //blow out any existing member when someone tries to sign in
            try
            {
                //Reset session backed my groups from Whats Happening Now
                Session["_selectedGroups"] = null;
               
                //lets make sure to reset all user&member info before we start inflating it
                this.FlushCurrentMemberUser();

                var membershipManager = new MembershipManager();

                var currentMember = new Member();

                if (!string.IsNullOrEmpty(AccessToken))
                {
                    var client = new Facebook.FacebookClient(AccessToken);
                    dynamic me = client.Get("me", new { fields = "email" });

                    currentMember = membershipManager.GetMember(me.email);
                }
                else
                {
                    currentMember = membershipManager.AuthenticateUser(uxEmailAddress.Text, uxPassword.Text);
                }

                if (currentMember != null)
                {
                    this.CurrentMember = currentMember;
                    this.CurrentUser = membershipManager.GetUser(currentMember.MemberId, true);

                    this.ProfileRedirect(Constants.UserPermission.AgreedToTerms, null, true);

                    //Redirect used here for profile??
                    this.ReturnRedirect();

                    var item = Sitecore.Context.Database.GetItem(Constants.Pages.MyAccount);
                    // if you get this far, clear the redirect session URL 

                    Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(item));
                }
            }
            catch (Exception ex)
            {
                uxError.Text = ex.Message;
            }
        }
 private static string PostFacebookWall(string accessToken, string message)
 {
     var responsePost = "";
     try
     {
         //create the facebook account object
         var objFacebookClient = new Facebook.FacebookClient(accessToken);
         var parameters = new Dictionary<string, object>();
         parameters["message"] = message;
         responsePost = objFacebookClient.Post("feed", parameters).ToString();
     }
     catch (Exception ex)
     {
         responsePost = "Facebook Posting Error Message: " + ex.Message;
     }
     return responsePost;
 }
Beispiel #43
0
        private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            var fb = new Facebook.FacebookClient(App.AccessToken);
            var result = await fb.GetTaskAsync("fql",
                new
                {
                    //q = "SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 25)"
                    //q = "SELECT aid FROM album WHERE (owner=1383951117)"
                    q = "SELECT src_big,src_small,target_id FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject='') OR pid IN (SELECT pid FROM photo WHERE aid IN (SELECT aid FROM album WHERE (owner='1383951117') AND type!='profile')) and place_id in (SELECT page_id FROM place WHERE distance(latitude, longitude, '41.878700', '-87.636620') < '50000')"
                });
            //System.Threading.Thread.Sleep(4000);
            System.Diagnostics.Debug.WriteLine("Result: " + result.ToString());
            JObject ob = JObject.Parse(result.ToString());
            JArray data = (JArray)ob["data"];
            int i;
            List<Uri> small=new List<Uri>();       
            List<Uri> big = new List<Uri>();
            for(i=0;i<data.Count;i++)
            {
                JObject a=(JObject)data[i];
                JValue b = (JValue)a["src_big"];
                big.Add(new Uri(b.Value.ToString()));
                b = (JValue)a["src_small"];
                small.Add(new Uri(b.Value.ToString()));
            }

            my_popup_cs.IsOpen = false;

            var GroupedURLs = new List<ImageViewModel>();
            for (int j = 0; j < small.Count; j++)
            {
                var objImageViewModel = new ImageViewModel();
                if (small.ElementAtOrDefault(j) != null)
                {
                    objImageViewModel.First = big[j];
                    objImageViewModel.big = big[j];
                }

                GroupedURLs.Add(objImageViewModel);
            }

            ic.ItemsSource = GroupedURLs;
        }
        public void FacebookUserFeedAPI(string UserId, string FacebookId)
        {
            try
            {
                Guid userid = Guid.Parse(UserId);
                FacebookHelper fbhelper = new FacebookHelper();
                FacebookAccountRepository fbAccRepo = new FacebookAccountRepository();
                FacebookAccount fbAccount = fbAccRepo.getFacebookAccountDetailsById(FacebookId, userid);
                Facebook.FacebookClient fb = new Facebook.FacebookClient(fbAccount.AccessToken);
                var feeds = fb.Get("/me/feed");
                dynamic profile = fb.Get("me");
                fbhelper.getFacebookUserFeeds(feeds, profile);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Beispiel #45
0
        /// <summary>
        /// Gets the user's Facebook ID from their fb cookie.
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        private static long GetUserID(IWebSocketConnection socket)
        {
            try
            {
                // cookie key includes app id
                var fbCookieValue = socket.ConnectionInfo.Cookies["fbsr_" + System.Configuration.ConfigurationManager.AppSettings["fbAppId"]];
                Facebook.FacebookClient x = new Facebook.FacebookClient();

                // parse the cookie using the app secret
                dynamic y = x.ParseSignedRequest(System.Configuration.ConfigurationManager.AppSettings["fbAppSecret"], fbCookieValue);

                return long.Parse(y.user_id);
            }
            catch
            {
                // user id 1 = autoplay. this is temporary...
                return 1;
            }
        }
Beispiel #46
0
        public static User GetOrCreateUser(E3RadioEntities db, long userId)
        {
            var u = db.Users.SingleOrDefault(us => us.UserID == userId);
            if (u == null)
            {
                u = new e3Radio.Data.User();

                // get the dude's info from book of face
                var fb = new Facebook.FacebookClient();
                dynamic me = fb.Get("/" + userId);
                u.UserID = userId;
                u.Username = me.username ?? me.name;
                u.Name = me.name;
                u.FacebookLink = me.link;
                u.DateCreated = DateTime.Now;

                db.Users.Add(u);
                db.SaveChanges();
            }
            return u;
        }
Beispiel #47
0
        private void fbLogin(HttpContext context)
        {
            string token = context.Request.Params["token"];
            Facebook.FacebookClient client = new Facebook.FacebookClient(token);
            //client.Post()
            client.UseFacebookBeta = client.IsSecureConnection = true;
            Facebook.JsonObject o = (Facebook.JsonObject)client.Get("/me");
            var db = new PetaPoco.Database(Common.HairStyleConnectionString, "System.Data.SqlClient");
            using (var scope = db.GetTransaction())
            {

                try
                {
                    string first_name = (string)o["first_name"];
                    string name = (string)o["name"];
                    decimal id = Convert.ToDecimal(o["id"]);
                    POCOS.Facebook fb = new POCOS.Facebook();
                    fb.name = name;
                    fb.first_name = first_name;
                    fb.gender = (string)o["gender"];
                    fb.id = id;
                    fb.last_name = (string)o["last_name"];
                    fb.link = (string)o["link"];
                    fb.locale = (string)o["locale"];
                    fb.timezone = Convert.ToDouble(o["timezone"]);
                    string updatedtime = (string)o["updated_time"];
                    DateTime dt;
                    if (DateTime.TryParse(updatedtime, out dt))
                        fb.updated_time = dt;
                    if (db.Exists<POCOS.Facebook>(id))
                        db.Update(fb);
                    else
                        db.Insert(fb);
                    POCOS.AppUser au = POCOS.AppUser.FirstOrDefault("Select top 1 * from AppUsers where facebookid=@0", id);
                    if (au == null)
                    {
                        au = new POCOS.AppUser();
                        au.FirstName = first_name;
                        au.facebookid = id;
                        db.Insert(au);
                    }
                    scope.Complete();
                    CookieUtil.WriteCookie(Common.AuthCookie, EncDec.Encrypt(JsonConvert.SerializeObject(new { ID = au.ID }), Common.DefaultPassword), false);
                    CookieUtil.WriteCookie(Common.InfoCookie, JsonConvert.SerializeObject(new { email = au.Email, name = au.Name, avatar = string.IsNullOrWhiteSpace(au.Avatar) ? null : Common.UploadedImageRelPath + au.Avatar }), false);
                }
                finally
                {
                    scope.Dispose();
                }
            }
        }
Beispiel #48
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {
                return false;
            }

            string accessToken = null;
            FacebookUser me = null;

            try {
                // Check session for access token
                if (httpContext.Session["access_token"] != null){
                    accessToken = httpContext.Session["access_token"].ToString();
                } else {
                    // Check identity for access token
                        //Get the current claims principal
                        var identity = (ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal;
                        var claims = identity.Claims;
                        // Access claims
                        foreach (Claim claim in claims)
                        {
                            if (claim.Type == "FacebookAccessToken")
                            {
                                accessToken = claim.Value;
                            }
                        }
                }

                if (accessToken == null)
                {
                    return false;
                }
                // End access token section

                // Check session for Me
                if ((FacebookUser)httpContext.Session["me"] != null){
                    me = (FacebookUser)httpContext.Session["me"];
                } else {
                    // Get new Facebook data with access token
                    Facebook.FacebookClient facebook = new Facebook.FacebookClient(accessToken.ToString());
                    dynamic RawMe = facebook.Get("me?fields=name,picture.type(square)");
                    dynamic RawFriends = facebook.Get("me/friends?fields=name,picture.type(square),installed");

                    // Use Raw Data to populate helpful objects
                    me = new FacebookUser(RawMe, RawFriends.data);

                    // Put Me in session
                    httpContext.Session["me"] = me;
                }
                // End Me section
            }
            catch (Exception e) {
                return false;
            }

            if (me != null)
            {
                me = null;
                return true;
            }
            else
            {
                return false;
            }
        }
Beispiel #49
0
        public ActionResult MyHomePage()
        {
            if (Session["AccessToken"] != null)
            {
                var fb = new Facebook.FacebookClient();
                string accessToken = Session["AccessToken"] as string;
                var logoutUrl = fb.GetLogoutUrl(new { access_token = accessToken, next = "http://*****:*****@Session["LogedUserName"] = null;
            @Session["LogedUserGenre"] = null;
            @Session["LogedUserId"] = null;
            @Session["LogedUserLastName"] = null;
            @Session["LogedUserEmail"] = null;
            List<Movie> movieList = new List<Movie>();
            try
            {
                movieList = movieManager.GetAllMovies();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }
            return View(movieList);
        }
Beispiel #50
0
        void share(int sid, string name, string caption, string description, string url, string picture)
        {
			try{
				Deployment.Current.Dispatcher.BeginInvoke(async () =>
				{
					bool shared_ok = false;
					try
					{
						var fb = new Facebook.FacebookClient(session.AccessToken);
						var postParams = new
						{
							name = name,
							caption = caption,
							description = description,
							link = url,
							picture = picture
						};

						dynamic fbPostTaskResult = await fb.PostTaskAsync("/me/feed", postParams);
						var result = (IDictionary<string, object>)fbPostTaskResult;

						shared_ok = true;
					}
					catch (Exception)
					{
						
					}
					ADFacebookWP8Impl.sendShareResult(sid, shared_ok);
				});
			} catch (Exception e){}
        }
Beispiel #51
0
        async System.Threading.Tasks.Task updateMyInfo()
        {
            try
            {
                var client = new Facebook.FacebookClient(session.AccessToken);
                dynamic result = await client.GetTaskAsync("me");
                var currentUser = new Facebook.Client.GraphUser(result);

                ADFacebookWP8Impl.myInfo(currentUser.Id, currentUser.LastName, currentUser.FirstName);
            }
            catch (Exception)
            { }
        }
Beispiel #52
0
        async System.Threading.Tasks.Task updateFriendsInfo()
        {

            try
            {
                var fb = new Facebook.FacebookClient(session.AccessToken);
                string query = "select uid, first_name, last_name from user where uid in (select uid2 from friend where uid1 = me()) and is_app_user";

                var result = await fb.GetTaskAsync("fql",
                    new
                    {
                        q = query
                    });

                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result.ToString()));

                RootObject obj = new RootObject();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());

                obj = ser.ReadObject(ms) as RootObject;

                List<string> ids = new List<string>();
                List<string> last_names = new List<string>();
                List<string> first_names = new List<string>();

                foreach (User u in obj.data)
                {
                    ids.Add(u.uid);
                    last_names.Add(u.last_name);
                    first_names.Add(u.first_name);
                    //System.Diagnostics.Debug.WriteLine("UID: " + u.uid + u.first_name + u.last_name);
                }

                ADFacebookWP8Impl.friendsInfo(ids.ToArray(), last_names.ToArray(), first_names.ToArray());
                //System.Diagnostics.Debug.WriteLine("Result: " + result);
            }
            catch (Exception)
            {
                System.Diagnostics.Debug.WriteLine("updateFriendsInfo failed ");
            }

        }
Beispiel #53
0
        private void fbLogin(HttpContext context)
        {
            string token = context.Request.Params["token"];
            Facebook.FacebookClient client = new Facebook.FacebookClient(token);
            client.IsSecureConnection = true;
            Facebook.JsonObject o = (Facebook.JsonObject)client.Get("/me");
            var db = GetDataContext1;
            using (var scope = db.GetTransaction())
            {

                try
                {
                    string first_name = (string)o["first_name"];
                    string name = (string)o["name"];
                    decimal id = Convert.ToDecimal(o["id"]);
                    Data.POCOS.Facebook fb = new Data.POCOS.Facebook();
                    fb.name = name;
                    fb.first_name = first_name;
                    fb.gender = (string)o["gender"];
                    fb.id = id;
                    fb.last_name = (string)o["last_name"];
                    fb.link = (string)o["link"];
                    fb.locale = (string)o["locale"];
                    fb.timezone = Convert.ToDouble(o["timezone"]);
                    string updatedtime = (string)o["updated_time"];
                    DateTime dt;
                    if (DateTime.TryParse(updatedtime, out dt))
                        fb.updated_time = dt;
                    if (db.Exists<Data.POCOS.Facebook>(id))
                        db.Update(fb);
                    else
                        db.Insert(fb);
                    Data.POCOS.AppUser au = Data.POCOS.AppUser.FirstOrDefault("Select top 1 * from AppUsers where facebookid=@0", id);
                    if (au == null)
                    {
                        au = new Data.POCOS.AppUser();
                        au.FirstName = first_name;
                        au.facebookid = id;
                        db.Insert(au);
                    }

                    scope.Complete();
                    Common.WriteValue(Common.AuthCookie, au.ID.ToString());
                    Common.WriteValue(Common.InfoCookie, JObject.FromObject(new { email = au.Email, name = string.IsNullOrEmpty(au.FirstName) ? au.Name : au.FirstName, avatar = string.IsNullOrWhiteSpace(au.Avatar) ? null : Common.UploadedImageRelPath + au.Avatar, points = au.Points }));
                }
                finally
                {
                    scope.Dispose();
                }
            }
        }
Beispiel #54
0
        public static string GetAppAccessToken(Facebook.FacebookClient fbClient = null)
        {
            // TODO: Cache in DB via site settings rather than fetching every time?
            if (fbClient == null)
            {
                fbClient = new Facebook.FacebookClient();
            }

            string appId = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppId);
            string appSecret = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppSecret);
            object appAccessTokenParams = new { client_id = appId, client_secret = appSecret, grant_type = "client_credentials" };
            dynamic appAccessTokenObject = fbClient.Get("/oauth/access_token", appAccessTokenParams);
            string appAccessToken = appAccessTokenObject.access_token;

            return appAccessToken;
        }
Beispiel #55
0
 private async void OnQueryButtonClick(object sender, RoutedEventArgs e)
 {
     var fb = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);
     var result = await fb.GetTaskAsync("fql",
         new
         {
        public async Task<ActionResult> FacebookInfo()
        {
            var claimsforUser = UserManager.GetClaims(User.Identity.GetUserId());
            var access_token = claimsforUser.FirstOrDefault(x => x.Type == "FacebookAccessToken").Value;
            var fb = new Facebook.FacebookClient(access_token);

            dynamic myInfo = fb.Get("/me");

            //Ex. dynamic myFeed = fb.Get("/me/feed");

            dynamic myPicture = fb.Get(string.Format("/me/picture?redirect=0&height=200&type=normal&width=200", myInfo["id"]));

            //Add the facebook info to the viewmodel and return
            var meInfo = new FacebookMeInfo()
            {
                Name = string.Format("{0} {1}", myInfo["first_name"], myInfo["last_name"]),
                Locale = myInfo["locale"],
                UpdatedTime = myInfo["updated_time"],
                PictureUrl = myPicture["data"]["url"]
            };

            return View(meInfo);
        }
        public IHttpActionResult FacebookPostsCommentsService()
        {
            Facebook.FacebookClient fb = new Facebook.FacebookClient();
            UserRepository userRepo = new UserRepository();
            FacebookAccountRepository fbAccRepo = new FacebookAccountRepository();
            Api.Socioboard.Services.Facebook fbService = new Api.Socioboard.Services.Facebook();
            List<Domain.Socioboard.Domain.User> lstUser = new List<Domain.Socioboard.Domain.User>();
            lstUser = userRepo.getAllUsers();
            foreach (var user in lstUser)
            {
                List<Domain.Socioboard.Domain.FacebookAccount> lstFacebookAccount = fbAccRepo.GetAllFacebookAccountByUserId(user.Id);

                foreach (var fbAcc in lstFacebookAccount)
                {
                    if (!string.IsNullOrEmpty(fbAcc.AccessToken))
                    {
                        fb.AccessToken = fbAcc.AccessToken;
                        MongoRepository boardrepo = new MongoRepository("MongoFacebookFeed");
                        try
                        {

                            var result = boardrepo.Find<MongoFacebookFeed>(x => x.ProfileId.Equals(fbAcc.FbUserId) && x.UserId.Equals(user.Id.ToString())).ConfigureAwait(false);

                            var task = Task.Run(async () =>
                            {
                                return await result;
                            });
                            IList<MongoFacebookFeed> objfbfeeds = task.Result;
                            if (objfbfeeds.Count() == 0)
                            {

                                result = boardrepo.Find<MongoFacebookFeed>(x => x.ProfileId.Equals(fbAcc.FbUserId)).ConfigureAwait(false);

                                task = Task.Run(async () =>
                                {
                                    return await result;
                                });
                            }
                            List<MongoFacebookFeed> fbfeeds = objfbfeeds.ToList();
                            foreach (var post in fbfeeds)
                            {
                                fbService.AddFbPostComments(post.FeedId, fb, user.Id.ToString());
                            }

                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex.Message);
                            logger.Error(ex.StackTrace);
                            return BadRequest("Something Went Wrong");
                        }
                    }



                }



            }


            return Ok();
        }
Beispiel #58
0
        public ActionResult Login(FormCollection f)
        {
            var accessToken = f["accessToken"];

            //get name and id from facebookClient
            var client = new Facebook.FacebookClient(accessToken);
            dynamic result = client.Get("me", new { fields = "first_name, last_name, id, username" });

            //access the user model
            UserModel um = new UserModel();

            //check if user exists, if exists: login, if not exists: create
            User u = new User();
            u.Firstname = result.first_name;
            u.Lastname = result.last_name;
            u.FK_Role = 1;
            u.FB_UserId = result.id;
            u.FB_UserName = result.username;

            //important! fb id is now int 64,
            //but cannot convert dynamic result to int, so we use string (for now)
            Boolean exists = um.userExists(u.FB_UserId);
            if (!exists)
            {
                //user does not exist yet, create and log in
                try
                {
                    u = um.saveUser(u);
                    //if the user's id has been set: success
                    if (u.User_Id == 0)
                    {
                        throw new Exception("User wasn't saved into database");
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    ViewBag.status = "error";
                    return View();
                }
            }
            else{
                //login the user
                try
                {
                    u = um.logIn(u);
                    //if the user's id has been set: success
                    if (u.User_Id == 0)
                    {
                        throw new Exception("User couldn't be logged in");
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    ViewBag.status = "error";
                    return View();
                }
            }

            //set the facebook id in the session: set that the user is logged in
            Session["firstname"] = u.Firstname;
            Session["lastname"] = u.Lastname;
            Session["fbUserId"] = result.id;
            Session["userId"] = u.User_Id;
            Session["fbUserId"] = result.id;
            Session["userLevel"] = u.FK_Role;
            ViewBag.status = "loggedIn";

            return View();
        }
        public ActionResult Facebook(string id)
        {
            var fb = new Facebook.FacebookClient();

            RedirectUri = id == "login" ? 
                new UriBuilder() { Query = null, Fragment = null, Host = Request.Url.Host,Path = Url.Action("FacebookCallbackLogin"), Port = Request.Url.Port}.Uri
                    : new UriBuilder() { Query = null, Fragment = null, Host = Request.Url.Host, Path = Url.Action("FacebookCallback"), Port = Request.Url.Port }.Uri;

            var loginUrl = fb.GetLoginUrl(
                new
                {
                    client_id = "510735142346763",
                    client_secret = "c4df6a6934bc013daa1560bd063921b0",
                    redirect_uri = RedirectUri.AbsoluteUri,
                    response_type = "code",
                    scope = "email"
                });

            return Redirect(loginUrl.AbsoluteUri);
        }
        public ActionResult FacebookCallbackLogin(string code)
        {
            try
            {
                var fb = new Facebook.FacebookClient();
                dynamic result = fb.Post("oauth/access_token", new
                {
                    client_id = "510735142346763",
                    client_secret = "c4df6a6934bc013daa1560bd063921b0",
                    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,gender,username");

                GetSingleMemberResponse model = _member.GetSingleByFacebookId(me.id);

                if (model.Code == "-1" && model.Code.Contains("No member"))
                {
                    MemberEditResponse data = _member.CreateMember(me.first_name, me.last_name, me.email, me.username, me.username, null,
                                                me.gender == "male", null, null, null, me.locale, me.id);

                    if (data.Code == "-1" && data.Message.Contains("Username"))
                        data = _member.CreateMember(me.first_name, me.last_name, me.email, me.username, null, null,
                                                   me.gender == "male", null, null, null, me.locale, me.id);
                    else if (data.Code == "-1")
                    {
                        return RedirectToAction("SignUp");
                    }
                    if (data.Code == "-1")
                    {
                        return RedirectToAction("SignUp");
                    }
                }

                SessionManager.IsLoggedIn = true;
                SessionManager.UserLogged = new UserProfile
                {
                    FacebookId = model.Member.MemberFacebookId,
                    FirstName = model.Member.MemberFirstName,
                    LastName = model.Member.MemberLastName,
                    UserName = model.Member.MemberUserName,
                    UserId = model.Member.MemberId
                };

                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Index", "Home");
            }
        }