public dynamic getConversations()
        {
            try
            {
                if (m_conversations == null)
                {
                    m_conversations = m_fbClient.Get("me/inbox", new
                    {
                        limit  = 200,
                        offset = 50
                    });
                }
            }
            catch (Facebook.FacebookOAuthException)
            {
                Console.Error.WriteLine("Api calls exceeded.  You must wait");
                return(null);
            }


            if (m_apiExceededError)
            {
                m_apiExceededError = false;
                return(null);
            }
            return(m_conversations.data);
        }
Пример #2
0
       // public IEnumerable<string> getFeed()
        public object getFeed()
        {
            try
            {
                var fb = new FacebookClient(AccessToken) { AppId = AppId, AppSecret = AppSecrete };
                List<object> _lisObj = new List<object>();
                List<object> _lisObj2 = new List<object>();
                dynamic results = fb.Get("/55269232341_10154511844402342/comments");
                var a = results[1].next;

                dynamic results2 = fb.Get(a);
                var b = results[1].next;
                foreach (object result in results2.data)
                {
                    _lisObj2.Add(result);
                }
                var c = results2[1].next;


                foreach (object result in results.data)
                {
                     _lisObj.Add(result);
                }
                return _lisObj;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
                return null;
            }
        }
Пример #3
0
        /*
        public FacebookLayer()
        {
            authorizer = new CanvasAuthorizer { Perms = "publish_stream" };
            if (authorizer.Authorize())
            {
                fbClient = new FacebookClient(CurrentSession.AccessToken);
                User = new FacebookUser();
                try
                {
                    var me = (IDictionary<string, object>) fbClient.Get("me");

                    User.FacebookId = (string) me["id"];
                    User.FacebookName = (string) me["first_name"];
                }
                catch
                {
                    isAccessTokenValid = false;
                    return;
                }
                isAccessTokenValid = true;
                IDictionary<string, object> friendsData = (IDictionary<string, object>) fbClient.Get("me/friends");
                facebookData = new FacebookData(User, friendsData);
                SortedFriends = facebookData.SortedFriends;
            }
        }
        */
        public FacebookLayer(CanvasAuthorizer auth)
        {
            this.authorizer = auth;
            if (this.authorizer.Authorize())
            {
                fbClient = new FacebookClient(CurrentSession.AccessToken);
                User = new FacebookUser();
                try
                {
                    var me = (IDictionary<string, object>) fbClient.Get("me");

                    User.FacebookId = (string) me["id"];
                    User.FacebookName = (string) me["first_name"];
                }
                catch
                {
                    isAccessTokenValid = false;
                    return;
                }
                isAccessTokenValid = true;
                IDictionary<string, object> friendsData = (IDictionary<string, object>) fbClient.Get("me/friends");
                facebookData = new FacebookData(User, (IList<object>)friendsData["data"]);

            }
        }
Пример #4
0
        public ActionResult About()
        {
            ViewBag.Friends = new List<FbUser>();
            ViewBag.FriendsCount =0;
            ViewBag.Message = "Your application description page.";

            var claimsIdentity = HttpContext.User.Identity as ClaimsIdentity;
            //var access_token = claimsIdentity.FindAll("name").First().ToString();
            //var access_token = claimsIdentity.FindAll("BLEE");
            //var access_token2 = access_token.First();
            //var access_token3 = access_token2.ToString();

            var claimlist = from claims in HttpContext.GetOwinContext().Authentication.User.Claims
                            select new ExtPropertyViewModel
                            {
                                Issuer = claims.Issuer,
                                Type = claims.Type,
                                Value = claims.Value
                            };
            try
            {
                var access_token = HttpContext.GetOwinContext().Authentication.User.Claims.Where(c => c.Type == "FacebookAccessToken").First().Value;
                ViewBag.Token = access_token;

                var fb = new FacebookClient(access_token);

                //var friendListData = fb.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);
                //}
                //ViewBag.Friends = fbUsers;
                //ViewBag.FriendsCount = fbUsers.Count;

                string ans = fb.Get("me").ToString();
                ViewBag.Me = ans;
                string ans2 = fb.Get("me/permissions").ToString();
                ViewBag.Permissions = ans2;

                string ans4 = fb.Get("me/friends", new { fields = new[] { "name, id" } }).ToString();
                ViewBag.Friends = ans4;

                return View(claimlist.ToList<ExtPropertyViewModel>());
            }
            catch
            {
                return View(new List<ExtPropertyViewModel>());
            }
        }
        public ActionResult FbAuth(string returnUrl)
        {
            var client = new FacebookClient();
            var oauthResult = client.ParseOAuthCallbackUrl(Request.Url);

            // Build the Return URI form the Request Url
            var redirectUri = new UriBuilder(Request.Url);
            redirectUri.Path = Url.Action("FbAuth", "Account");

            dynamic result = client.Get("/oauth/access_token", new
            {
            client_id = ConfigurationManager.AppSettings["FacebookAppId"],
            redirect_uri = redirectUri.Uri.AbsoluteUri,
            client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
            code = oauthResult.Code,
            });

            // Read the auth values
            string accessToken = result.access_token;
            DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires));

            dynamic me = client.Get("/me", new { fields = "first_name,last_name,email", access_token = accessToken });

            // Read the Facebook user values
            long facebookId = Convert.ToInt64(me.id);
            string firstName = me.first_name;
            string lastName = me.last_name;
            string email = me.email;

            // Add the user to our persistent store
            var userService = new UserService();
            userService.AddOrUpdateUser(new User
            {
            Id = facebookId,
            FirstName = firstName,
            LastName = lastName,
            Email = email,
            AccessToken = accessToken,
            Expires = expires
            });

            // Set the Auth Cookie
            FormsAuthentication.SetAuthCookie(email, false);

            // Redirect to the return url if availible
            if (String.IsNullOrEmpty(returnUrl))
            {
            return Redirect("/App");
            }
            else
            {
            return Redirect(returnUrl);
            }
        }
Пример #6
0
        public ActionResult Callback(string code, string state)
        {
            FacebookOAuthResult oauthResult;
            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    FacebookClient fbClient = new FacebookClient(accessToken);
                    dynamic me = fbClient.Get("me?fields=id,name");
                    long facebookId = Convert.ToInt64(me.id);

                    var account = Accounts.Get().Where(Accounts.Columns.ForeignID, Actions.Equal, facebookId).SelectOne();
                    if (account == null)
                    {
                        account = new Account { FBKey = accessToken, Name = me.name, ForeignID = facebookId.ToString() };
                        account.Insert();
                    }
                    else
                    {
                        account.FBKey = accessToken;
                        account.Name = me.name;
                        account.Update();
                    }
                    dynamic pages = fbClient.Get("me/accounts");
                    foreach (var p in pages.data)
                    {
                        FBPage page = FBPages.Get().Where(FBPages.Columns.ForeignID, Actions.Equal, p.id).SelectOne();
                        if (page == null)
                        {
                            page = new FBPage { ForeignID = p.id, Name = p.name, Token = p.access_token };
                            page.Insert();
                        }
                        else
                        {
                            page.Name = p.name;
                            page.Token = p.access_token;
                            page.Update();
                        }
                    }

                    ViewBag.Name = account.Name;
                }
            }

            return View();
        }
    protected void loadFacebookData()
    {
        try
        {
            var client = new FacebookClient(new InfoModule().readFacebookAccessToken(Request["id"]));
            dynamic response = client.Get("me");
            dynamic response2 = client.Get("me?fields=picture");
            dynamic response3 = client.Get("me?fields=books");
            dynamic response4 = client.Get("me?fields=friends,events,sports,statuses.limit(3)");
            Picture.ImageUrl = response2.picture.data.url;
            HyperLink.NavigateUrl = response.link;
            HyperLink.Text = response.link;
            NameLabel.Text = response.name;
            BirthdayLabel.Text = response.birthday;
            GenderLabel.Text = response.gender;
            HometownLabel.Text = response.hometown.name;
            BioLabel.Text = response.bio;
            EmailLabel.Text = response.email;
            ReligionLabel.Text = response.religion;
            WorkLabel.Text = "";
            EducationLabel.Text = "";
            BooksLabel.Text = "";
            EventsLabel.Text = "";
            StatusLabel.Text = "";
            FriendsLabel.Text = response4.friends.summary.total_count.ToString();

            foreach (dynamic workplace in response.work)
            {
                WorkLabel.Text += workplace.employer.name + "<br />";
            }
            foreach (dynamic school in response.education)
            {
                EducationLabel.Text += school.school.name + "<br />";
            }
            foreach (dynamic book in response3.books.data)
            {
                BooksLabel.Text += book.name + "<br />";
            }
            foreach (dynamic events in response4.events.data)
            {
                EventsLabel.Text += events.name + "<br />";
            }
            foreach (dynamic status in response4.statuses.data)
            {
                StatusLabel.Text += status.message + "<br /><br />";
            }
        }
        catch (NullReferenceException e)
        {

        }
    }
Пример #8
0
        static void Main(string[] args)
        {
            JArray ja;
            Console.WriteLine("Starting....");
            string access_token = "Token";
            FacebookClient fbclient = new FacebookClient(access_token);
            dynamic Albumlist = fbclient.Get("/me/albums");

            int count = (int)Albumlist.data.Count;
            for (int i = 0; i < count; i++)
            {
                Console.WriteLine(i + " " + Albumlist.data[i].id + " " + Albumlist.data[i].name);

            }
            
            Console.WriteLine("");
            Console.WriteLine("Enter the Number of the Album to download");
            string input = Console.ReadLine();
            int number;
            Int32.TryParse(input, out number);

            String strrr = "/" + Albumlist.data[number].id + "/photos";
            dynamic pics = fbclient.Get(strrr);
            count = (int)pics.data.Count;
            String ssss = Convert.ToString(pics.data);
            //JObject ob = JObject.Parse(ssss);
            ja = JArray.Parse(ssss);
            WebClient wc = new WebClient();

            int j = 0;
            try
            {
                string folderpath = String.Format(@"{0}\Album", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
                while (ja[j]["images"][0]["source"].ToString() != null)
                {
                    wc.DownloadFile(ja[j]["images"][0]["source"].ToString(), folderpath + "\\" + j.ToString() + ".jpg");
                    Console.WriteLine("Downloading : " + folderpath + "\\" + j.ToString() + ".jpg");
                    j++;
                }
                Console.WriteLine("Download Complete");
            }
            catch (Exception esss)
            {

            }

            Console.WriteLine("Download Complete");
            Console.ReadKey();


        }
Пример #9
0
        public static void DoFacebook()
        {
            FacebookClient facebookClient = new FacebookClient();
            dynamic result = facebookClient.Get("oauth/access_token", new
            {
                client_id = "537452296325126",
                client_secret = "aa2ce963862cc139e64c1339f28bdfdd",
                grant_type = "client_credentials"
            });

            dynamic me = facebookClient.Get("me");
            var id = me.id;
            var name = me.name;
        }
 public static Dictionary<string, string> GetFriends(string access_token)
 {
     FacebookClient client = new FacebookClient(access_token);
     dynamic list = client.Get("me/friends");
     int noOfFriends = (int)list.data.Count;
     Dictionary<string, string> id = new Dictionary<string, string>();
     for (int i = 0; i < noOfFriends; i++)
     {
         id.Add(list.data[i].id, list.data[i].name);
     }
     list = client.Get("me");
     id.Add(list.id, list.name);
     return id;
 }
        public static FacebookUserModel FacebookHandshake(string redirectUri, HttpRequestBase request)
        {
            var model = new FacebookUserModel();
            var client = new FacebookClient();
            var oauthResult = client.ParseOAuthCallbackUrl(request.Url);

            // Build the Return URI form the Request Url

            // Exchange the code for an access token
            dynamic result = client.Get("/oauth/access_token", new
            {
                client_id = SocialMediaConnectConstants.AppId,
                redirect_uri = redirectUri,
                client_secret = SocialMediaConnectConstants.AppSecret,
                code = oauthResult.Code
                ,
            });

            // Read the auth values
            string accessToken = result.access_token;

            //If needed you can add the access token to a cookie for pulling additional inforamtion out of Facebook

            //DateTime expires = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires));

            //HttpCookie myCookie = HttpContext.Current.Request.Cookies["accessToken"] ?? new HttpCookie("accessToken");
            //myCookie.Values["value"] = accessToken;
            //myCookie.Expires = expires;

            //HttpContext.Current.Response.Cookies.Add(myCookie);

            // Get the user's profile information
            dynamic me = client.Get("/me",
                new
            {
                fields = "name,picture,first_name,last_name,email,id,birthday,location,gender",
                access_token = accessToken
            });

            // Read the Facebook user values
            model.UserId = me.id;
            model.FirstName = me.first_name;
            model.LastName = me.last_name;
            model.Email = me.email;
            model.ProfileImageUrl = ExtractImageUrl(me);
            model.Birthday = me.birthday;
            model.Gender = me.gender;
            model.Location = me.location["name"].ToString();
            return model;
        }
Пример #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Specify a name for main folder.
            string folderName = @"c:\Facebook Albums";

            if (string.IsNullOrWhiteSpace(textBox1.Text))
            {
                MessageBox.Show("please give Token  " );
                return;
            }

            var FBtoken = textBox1.Text;
            var fb = new FacebookClient(FBtoken);

            dynamic Albums = fb.Get("me/albums?fields=name");

            foreach (dynamic albumInfo in Albums.data)
            {

                var AlbumName = albumInfo.name;
                var AlbumId = albumInfo.id;

                //MessageBox.Show(" Dowloading album =" +AlbumName );
                string pathString = System.IO.Path.Combine( folderName, AlbumName);

                //creating subfolders in albums name
                System.IO.Directory.CreateDirectory(pathString);

                dynamic Photos = fb.Get(AlbumId+"/photos?fields=name,images");

                int n = 0; // for Image name .Because facebook has more version of one image with same id and name

                foreach (dynamic PhotosInfo in Photos.data)
                {

                    foreach (dynamic Image in PhotosInfo.images)
                    {
                        var PhotoName =n.ToString() + ".png";

                        string ImagePathString = System.IO.Path.Combine(pathString, PhotoName);
                        string ImagesSource = Image.source;

                        ImageDownload(ImagesSource, ImagePathString);
                        n++;
                    }
                }

            }
        }
        private void GetUserProfilePicture()
        {
            // note: avoid using synchronous methods if possible as it will block the thread until the result is received

            try
            {
                var fb = new FacebookClient(_accessToken);

                // Note: the result can either me IDictionary<string,object> or IList<object>
                // json objects with properties can be casted to IDictionary<string,object> or IDictionary<string,dynamic>
                // json arrays can be casted to IList<object> or IList<dynamic>

                // for this particular request we can guarantee that the result is
                // always IDictionary<string,object>.
                var result = (IDictionary<string, object>)fb.Get("me");

                // make sure to cast the object to appropriate type
                var id = (string)result["id"];

                // FacebookClient's Get/Post/Delete methods only supports JSON response results.
                // For non json results, you will need to use different mechanism,

                // here is an example for pictures.
                // available picture types: square (50x50), small (50xvariable height), large (about 200x variable height) (all size in pixels)
                // for more info visit http://developers.facebook.com/docs/reference/api
                string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}", id, "square");

                picProfile.LoadAsync(profilePictureUrl);
            }
            catch (FacebookApiException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #14
0
        public UserSettings(FacebookUserSetting setting)
        {
            _setting = setting;
            //get user
            InitializeComponent();

            var fb = new FacebookClient(setting.AccessToken);

            var picSettings = new List<FacebookPictureSetting>();

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

            foreach (var friend in friends.data)
            {
                picSettings.Add(new FacebookPictureSetting(new FacebookUser(friend.name, friend.id), false));
            }

            picSettings.Sort((x, y) => string.Compare(x.User.Name, y.User.Name));
            picSettings.Insert(0, new FacebookPictureSetting(new FacebookUser(setting.User.Name, setting.User.Id), false));

            var selectedPics = picSettings.Where(x => setting.PictureSettings.Any(y => y.User.Id == x.User.Id));

            foreach (var sp in selectedPics)
            {
                sp.Selected = true;
            }

            lsUsers.ItemsSource = picSettings;
        }
Пример #15
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");
        }
Пример #16
0
        /*void fbPostCompleted(object sender, FacebookApiEventArgs e)
         * {
         *  string r;
         *
         *  if (e.Error == null)
         *      r = "ok";
         *  else
         *      r = String.Format("failed: {0}", e.Error.Message);
         *
         *  Helper.LogHelper.StatsLog(null, "fbUploadPhotoAjax() [async] ", r, null, null);
         * }*/

        public ActionResult fbGetUser(string id)
        {
            var     client = new Facebook.FacebookClient();
            dynamic me     = client.Get(id);

            return(Json(me, JsonRequestBehavior.AllowGet));
        }
 private void GetDp(FBDialog fbd)
 {
     try
     {
         client             = new FacebookClient();
         client.AccessToken = fbd.access_token;
         dynamic me = client.Get("me?fields=picture.width(300),email,name,gender,birthday");
         if (me != null)
         {
             btnLogin.Visibility   = Visibility.Collapsed;
             txtPost.Visibility    = Visibility.Visible;
             btnPost.Visibility    = Visibility.Visible;
             lblPost.Visibility    = Visibility.Visible;
             rectDetail.Visibility = Visibility.Visible;
             Uri         uri       = new Uri(Convert.ToString(me.picture.data.url), UriKind.Absolute);
             ImageSource imgSource = new BitmapImage(uri);
             dpImage.Source    = imgSource;
             lblName.Content   = "Hello " + me[2] + " !!";
             lblEmail.Content  = "You logged in with email id :" + me[1];
             lblGender.Content = "Gender: " + me[3];
             string birthday = "Birthday : " + me[4];
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Problem while connecting to Facebook, please try again..");
         btnLogin.Visibility = Visibility.Collapsed;
     }
 }
        public static dynamic GetFeed(string access_token)
        {
            List<JToken> response = new List<JToken>();
            FacebookClient client = new FacebookClient(access_token);
            try
            {
                string nextpage = "me/feed?limit=200";

                while(true)
                {
                    var json = JObject.Parse(client.Get(nextpage).ToString());
                    var array = json["data"];
                    if (array == null)
                    {
                        break;
                    }
                    dynamic paging = json["paging"];
                    response.Add(array);
                    nextpage = paging.next.ToString();
                }
            }
            catch (RuntimeBinderException rbe)
            {
                Debug.WriteLine(rbe.TargetSite.Name + ": " + "Facebook API limit reached!");
            }
            return response;
        }
Пример #19
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");
        }
        public StreamItemCollection GetStreamItemCollection()
        {
            try
            {
                ExtendAccesstoken();

                string accesstoken = "";

                string appid = "";
                string appsecret = "";

                FacebookClient client = new FacebookClient();
                dynamic Me = client.Get(@"me/home");

                string aboutMe = Me.about;

            }
            catch (Exception exc)
            {

                throw;
            }

            return null;
        }
        public StreamItemCollection ExtendAccesstoken()
        {
            try
            {
                string accesstoken = "";

                string appid = "";
                string appsecret = "";

                FacebookClient client = new FacebookClient();
                dynamic Me = client.Get("oauth/access_token", new
                {
                    client_id = appid,
                    client_secret = appsecret,
                    grant_type = "fb_exchange_token",
                    fb_exchange_token = accesstoken,
                    redirect_uri ="http://www.example.com",
                });

            }
            catch (Exception exc)
            {

                throw;
            }

            return null;
        }
        public void AgregarAlojamiento(modAlojamiento alojamiento)
        {
            bool permiteAcceso = false;
            Boolean debug = Boolean.Parse(ConfigurationManager.AppSettings["debug"]);

            permiteAcceso = debug;

            if (Session["AccessToken"] != null)
            {
                var accessToken = Session["AccessToken"].ToString();
                var client = new FacebookClient(accessToken);
                dynamic result = client.Get("me", new { fields = "id" });

                if (result.id == "100002979715059")
                {
                    permiteAcceso = true;
                }
            }

            if (permiteAcceso)
            {
                alojamiento.Latitud = Double.Parse(Request.Params["Latitud"], CultureInfo.InvariantCulture);
                alojamiento.Longitud = Double.Parse(Request.Params["Longitud"], CultureInfo.InvariantCulture);

                alojamiento.CenterLat = Double.Parse(Request.Params["CenterLat"], CultureInfo.InvariantCulture);
                alojamiento.CenterLong = Double.Parse(Request.Params["CenterLong"], CultureInfo.InvariantCulture);

                var serv = new AlojamientoService();
                serv.AgregarAlojamiento(alojamiento);
               }
        }
Пример #23
0
        private void faceBookParsing( String parseData )
        {
            //https://www.facebook.com/connect/login_success.html#access_token=CAAL5FWAo8hgBAOU7VTTuS1g25xvG1Mf47UVVpZC6qRMbYtZBCZAo2Hooax4nhHh2kuBdE8C527f6lQKJphp0KpSgSt5uABlHhG9T1cTIjinSJWZBHIbOVKi5eeCXtbDIZAlZASow9Hw5Bml1lBKB0TMjTbDPn4wLwcTqwiu39tUYyKzR9c62fVmxF2FVXA0egZD&expires_in=6471"

            parseData = parseData.Replace("https://www.facebook.com/connect/login_success.html#access_token=", "");
            int endIndex = parseData.IndexOf('&');

            accessToken = parseData.Substring(0, endIndex);
            Console.WriteLine("accessToken:" + accessToken);

            var fb = new FacebookClient(accessToken);

            dynamic result = fb.Get("/me");
            var name = result.name;
            var id = result.id;

            MessageBox.Show("name:" + name + " id:" + id);
            Console.WriteLine("name:" + name + " id:" + id);
            //string curDir = Directory.GetCurrentDirectory();
            //this.webBrowser1.Url = new Uri(serverRootPath);

            // 총 2개의 POST 데이터 만들기
            string strPostData = string.Format("name={0}&id={1}&token={2}", name, id, accessToken);
            byte[] postData = Encoding.Default.GetBytes(strPostData);
            this.webBrowser1.Navigate(serverRootPath, null, postData, "Content-Type: application/x-www-form-urlencoded");
        }
Пример #24
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");
        }
Пример #25
0
        public Dictionary<DateTime, int> getFacebookPageLikes(string PageId, string Accesstoken, int days)
        {


            //string accesstoken = "CAACEdEose0cBAMQVEgKsHtUogOZCQ9vtBZB6FjsUWuZCVEzVUU01yecHqo1fVpTfQq65tmMUfmlafhmGtzmUY6ZCmZBrEXWMp1sfBLMvtdB7c1HBkSBGxbqT0q0nQY6ZBmtPBhg84IrXy4jBjRdMmP1Mh8hlOC9TRuy86jabDi2ccOyeRXYVZA7vuj4HDYgLhrwlNubCYvkENa6nPuY1PCgkuCv1cS8rXMZD";
            try
            {
                long since = DateTime.Now.AddDays(-days).ToUnixTimestamp();
                long until = DateTime.Now.ToUnixTimestamp();
                FacebookClient fb = new FacebookClient();
                fb.AccessToken = Accesstoken;
                //dynamic kasdfj = fb.Get("v2.3/me/permissions");
                dynamic kajlsfdj = fb.Get("v2.0/" + PageId + "/insights/page_fans?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString());
                string facebookSearchUrl = "https://graph.facebook.com/v2.3/" + PageId + "/insights/page_fans?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + Accesstoken;
                string outputface = getFacebookResponse(facebookSearchUrl);
                Dictionary<DateTime, int> LikesByDay = new Dictionary<DateTime, int>();
                LikesByDay = getFacebookLikesDictonary(outputface);

                return LikesByDay;
            }
            catch (Exception ex)
            {
                return new Dictionary<DateTime, int>();
            }

        }
 public User Authenticate(string facebookAccessToken)
 {
     GameNickEntities entities = new GameNickEntities();
     FacebookClient fbclient = new FacebookClient(facebookAccessToken);
     dynamic me = fbclient.Get("me");
     long myId = (long)Convert.ToUInt64(me.id.ToString());
     var exists = from users in entities.Users
                  where users.FacebookID == myId
                  select users;
     if (exists.Count() > 0)
     {
         exists.First().Name = me.name;
         exists.First().FacebookAccessToken = facebookAccessToken;
         exists.First().GameNickAccessToken = Guid.NewGuid();
         entities.SaveChanges();
         User _me = exists.First();
         _me.Status.Load();
         _me.GameNicks.Load();
         return _me;
     }
     // ReSharper disable RedundantIfElseBlock
     else
     // ReSharper restore RedundantIfElseBlock
     {
         User user = User.CreateUser(myId, 0);
         user.Name = me.name;
         // check that the ID is updated to a new unique value when it's added
         entities.AddToUsers(user);
         entities.SaveChanges();
         // todo: update the userID before returing it
         return entities.Users.First(u => u.FacebookID == myId);//user;
     }
 }
Пример #27
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"));
        }
Пример #28
0
    //HTTPMODULE!!
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            if (User.IsInRole("Triphulcas"))
                WelcomeMessage = Resources.Resource1.SnippetTriphulcasWelcomeMessage;

            if (!String.IsNullOrEmpty(User.AccessToken))
                {
                    try
                    {                        
                        var client = new FacebookClient(User.AccessToken);
                        dynamic result = client.Get("me", new { fields = "id" });
                        pImage.Src = String.Format(Resources.Resource1.FacebookPictureUrl, result.id);
                        pWelcome.InnerText = WelcomeMessage;
                        pLogout.Attributes.Remove("hidden");
                        pLogout.Attributes["style"] = "display:block";
                    }
                    catch (FacebookOAuthException)
                    {
                    }
                }            
        }
        
        else
        {
            //ugly, I know.
            pWelcome.InnerHtml = String.Format("{0} <a class=\"popup\" href=\"/authentication.aspx\">{1}</a>.", 
                Resources.Resource1.SnippetShowFaceBeforeLink, 
                Resources.Resource1.SnippetShowFaceLink);
        }
    }
        public ActionResult Agregar()
        {
            bool permiteAcceso = false;
            Boolean debug = Boolean.Parse(ConfigurationManager.AppSettings["debug"]);

            permiteAcceso = debug;

            if (Session["AccessToken"] != null)
            {
                var accessToken = Session["AccessToken"].ToString();
                var client = new FacebookClient(accessToken);
                dynamic result = client.Get("me", new { fields = "id" });

                if (result.id == "100002979715059")
                {
                    permiteAcceso = true;
                }
            }

            if (permiteAcceso)
            {
                var servAlojamientos = new AlojamientoService();

                var ListTipos = new List<ParDeValores>();
                //ListTipos.Add(new ParDeValores() { id = -1, descripcion = "Seleccione uno" });
                ListTipos.AddRange(servAlojamientos.GetTiposAlojamiento().Select(x => new ParDeValores() { id = x.ID, descripcion = x.Descripcion }));

                ViewBag.ListTipos = ListTipos;

                return View();
            }
            return new EmptyResult();
        }
Пример #30
0
        public static void GetSampleWithoutAccessToken()
        {
            try
            {
                var fb = new FacebookClient();

                var result = (IDictionary<string, object>)fb.Get("/4");

                var id = (string)result["id"];
                var name = (string)result["name"];
                var firstName = (string)result["first_name"];
                var lastName = (string)result["last_name"];

                Console.WriteLine("Id: {0}", id);
                Console.WriteLine("Name: {0}", name);
                Console.WriteLine("First Name: {0}", firstName);
                Console.WriteLine("Last Name: {0}", lastName);
                Console.WriteLine();

                // Note: This json result is not the orginal json string as returned by Facebook.
                Console.WriteLine("Json: {0}", result.ToString());
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }
Пример #31
0
        public static FacebookClient GetClient(bool reload=false)
        {
            if (reload)
               client = null;
               if (client!=null)
               {
               return client;
               }

               try
               {
               client = new FacebookClient(Data.Get("token"));

               me = client.Get("me/");

               }
               catch (WebExceptionWrapper)
               {
               throw new NoConnection();
               }
               catch (Exception)
               {

               return null;
               }

               return client;
        }
Пример #32
0
        public JsonResult Create(string facebookToken)
        {
            var client = new FacebookClient(facebookToken);
            dynamic user = client.Get("me");

            string userId = user.id;
            var siteUser = DocumentSession.Query<User>()
                                          .SingleOrDefault(x => x.Id == userId);

            if(siteUser == null)
            {
                var newUser = new User
                                  {
                                      Name = user.name,
                                      Roles = { Role.User }
                                  };

                DocumentSession.Store(newUser, user.id);
                siteUser = newUser;
            }

            FormsAuthentication.SetAuthCookie(siteUser.Id, false);

              return Json(new { user.id, user.name });
        }
Пример #33
0
 protected void procesRequest()
 {
     if (Request.QueryString["op"] == "twitter")
     {
         string twtProfileId = Request.QueryString["id"].ToString();
         User user = (User)Session["LoggedUser"];
         strTwtArray = objtwtStatsHelper.getNewFollowers(user, twtProfileId,15);
         strTwtFollowing = objtwtStatsHelper.getNewFollowing(user, twtProfileId,15);
         // strTwtAge = objtwtStatsHelper.GetFollowersAgeWise(user);
         strIncomingMsg = objtwtStatsHelper.getIncomingMsg(user, twtProfileId,15);
         strDmRecieve = objtwtStatsHelper.getDirectMessageRecieve(user, twtProfileId);
         strDMSent = objtwtStatsHelper.getDirectMessageSent(user, twtProfileId);
         strSentMsg = objtwtStatsHelper.getSentMsg(user, twtProfileId,15);
         strRetweet = objtwtStatsHelper.getRetweets(user, twtProfileId,15);
         strAgeDiff = objtwtStatsRepo.getAgeDiffCount(twtProfileId, 15);
         strEngagement = objtwtStatsHelper.getEngagements(user, twtProfileId, 15);
         strInfluence = objtwtStatsHelper.getInfluence(user, twtProfileId, 15);
         Response.Write(strTwtArray + "@" + strTwtFollowing + "@" + strIncomingMsg + "@" + strDmRecieve + "@" + strDMSent + "@" + strSentMsg + "@" + strRetweet + "@" + strAgeDiff + "@" + strEngagement + "@" + strInfluence);
     }
     if (Request.QueryString["op"] == "facebook")
     {
         string fbProfileId = Request.QueryString["id"].ToString();
         User user = (User)Session["LoggedUser"];
        // objfbstatsHelper.getAllGroupsOnHome.InnerHtml = fbUser;
         strFbAgeArray = objfbstatsHelper.getLikesByGenderAge(fbProfileId, user.Id, 10);
         strPageImpression = objfbstatsHelper.getPageImressions(fbProfileId, user.Id, 10);
         strLocationArray = objfbstatsHelper.getLocationInsight(fbProfileId, user.Id, 10);
         objfbstatsHelper.getPostDetails(fbProfileId, user.Id, 10);
         FacebookClient fb = new FacebookClient();
         fb.AccessToken = Request.QueryString["access"].ToString();
         dynamic pagelikes = fb.Get(fbProfileId);
         string strval = pagelikes.likes.ToString() + " Total Likes " + pagelikes.talking_about_count + " People talking about this.";
         Response.Write(strFbAgeArray + "_" + strPageImpression + "_" + strLocationArray + "_" + strval);
     }
 }
Пример #34
0
        private object GetFriendsCount()
        {
            var fb = new FacebookClient(txtAccessToken.Text);
            //var fb = new FacebookClient();
            for (int i = 0; i < 100; i++) {
                dynamic result1 = fb.Get(i);
                string id = result1.id;
                string firstName = result1.first_name;
                var lastName = result1.last_name;
            }
            var query = string.Format("SELECT friend_count, name FROM user WHERE uid = me()");
            // var query1 = string.Format("SELECT uid,name,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0})", "me()");
            fb.GetAsync("fql", new { q = query });
            object returnVal = 0;
            fb.GetCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                  //  Dispatcher.BeginInvoke();// () => MessageBox.Show(e.Error.Message));
                    return;
                }

                var result = (IDictionary<string, object>)e.GetResultData();
                var data = (IList<object>)result["data"];
                foreach (var comment in data.Cast<IDictionary<string, object>>())
                {
                    returnVal = comment["friend_count"];
                    // Dispatcher.BeginInvoke(() => MessageBox.Show(returnVal.ToString()));
                }

            };

            return returnVal;
        }
Пример #35
0
        /// <summary>
        /// Gets the picture info.
        /// </summary>
        /// <param name="pUserId">The user id.</param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException">pUserId cannot be null</exception>
        public dynamic GetPictureInfo(string pUserId)
        {
            if (pUserId == null)
            {
                throw new ApplicationException("pUserId cannot be null");
            }

            var fb = new Facebook.FacebookClient(this.GetAppAccessToken());

            return(fb.Get(string.Concat(pUserId, "/picture")));
        }
Пример #36
0
        private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            // whenever the browser navigates to a new url, try parsing the url.
            // the url may be the result of OAuth 2.0 authentication.
            var fb = new Facebook.FacebookClient();
            FacebookOAuthResult oauthResult;

            if (fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication
                if (oauthResult.IsSuccess)
                {
                    Settings1.Default.FacebookToken = oauthResult.AccessToken;
                    fb.AccessToken = Settings1.Default.FacebookToken;

                    //now retrieve all connected accounts and if there are more than one then display combobox allows user to choose which account he want to use
                    JsonObject fbAccounts = (JsonObject)fb.Get("/me/accounts");

                    ListItem <string> item = new ListItem <string>(Strings.FacebookLoginWindow_DefaultAccount, oauthResult.AccessToken);
                    cmbFacebookAccounts.Items.Add(item);

                    foreach (dynamic account in (IEnumerable)fbAccounts["data"])
                    {
                        item = new ListItem <string>(account["name"], account["access_token"]);
                        cmbFacebookAccounts.Items.Add(item);
                    }
                    if (cmbFacebookAccounts.Items.Count == 1)
                    {
                        DialogResult = true;
                        Close();
                    }
                    else
                    {
                        cmbFacebookAccounts.SelectedIndex = 0;
                        webBrowser.Visibility             = Visibility.Collapsed;
                        pnlChooseAccount.Visibility       = Visibility.Visible;
                    }
                }
                else
                {
                    //var errorDescription = oauthResult.ErrorDescription;
                    //var errorReason = oauthResult.ErrorReason;
                    DialogResult = false;
                    Close();
                }
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
            }
        }
Пример #37
0
        private void button1_Click(object sender, EventArgs e)
        {
            var fb = new FacebookClient("CAACEdEose0cBABXcorjdMKZBaZA0qaJnsX3k9uzckRZANEVQKJPmYFcRwoGydvnaeCR2IoAfCUAR8mdEMX3TyY44JCC1zZAY5lTbD24eSGKB6ICoZC61XsxpZCl2yPt5kfLZAlZBlhkvdr0VRiHmZCsi6KL3yyZCJloQfD4LBbAWNPqi4ohUzPrkZCfHGlIA4bOKD9loFpxAimqGKYUYCUbdqf0H4xTvWhZA4jkrfSGmG6ZBLZBQZDZD");

            dynamic result = fb.Get("139041419482037/feed?fields=id,full_picture,likes{link,name,profile_type,id,picture},comments,link,shares,updated_time,created_time,message,message_tags,properties,place,with_tags,subscribed");



            dynamic id        = result.id;
            dynamic firstName = result.first_name;
            dynamic lastName  = result.last_name;
            dynamic link      = result.link;
            dynamic locale    = result.locale;
        }
        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);
                }
            }
        }
Пример #39
0
        /// <summary>
        /// Extracts the user id from access token.
        /// </summary>
        /// <param name="accessToken">
        /// The access token.
        /// </param>
        /// <returns>
        /// Returns the user id if successful otherwise null.
        /// </returns>
        internal static string ParseUserIdFromAccessToken(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException("accessToken");
            }

            /*
             * access_token:
             *   1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc
             *                                               |_______|
             *                                                   |
             *                                                user id
             */
            var accessTokenParts = accessToken.Split('|');

            if (accessTokenParts.Length == 3)
            {
                var idPart = accessTokenParts[1];
                if (!string.IsNullOrEmpty(idPart))
                {
                    var index = idPart.LastIndexOf('-');
                    if (index >= 0)
                    {
                        string id = idPart.Substring(index + 1);
                        if (!string.IsNullOrEmpty(id))
                        {
                            return(id);
                        }
                    }
                }
            }
            else
            {
                // we have an encrypted access token
                try
                {
                    var fb     = new FacebookClient(accessToken);
                    var result = (IDictionary <string, object>)fb.Get("/me?fields=id");
                    return((string)result["id"]);
                }
                catch (FacebookOAuthException)
                {
                    return(null);
                }
            }

            return(null);
        }
Пример #40
0
        private FacebookClient PreparePhoto()
        {
            // 選擇的粉絲專頁
            //_pageID = ddlPageID.SelectedValue;
            //_pageID = "1474910372779635";
            // 照片檔名
            //_fileName = tbFileName.Text;

            printMessage("Image name :" + _fileName);

            Facebook.FacebookClient fb = new Facebook.FacebookClient(Session["accessToken"].ToString());

            printMessage("# access token again :" + Session["accessToken"].ToString());

            IDictionary <string, object> dic = (IDictionary <string, object>)fb.Get("/me/accounts");

            // 列出所有我管理的粉絲專頁
            IList <object> dicy = (IList <object>)dic["data"];
            IDictionary <string, object> page = null;

            for (int i = 0; i <= dicy.Count - 1; i++)
            {
                page = (IDictionary <string, object>)dicy[i];

                // 如果是這次要上傳的粉絲專頁 ID
                if (page["id"].ToString() == _pageID)
                {
                    // 取得粉絲專頁的 access_token,才能針對粉絲專頁做 graph api 動作
                    //CAAJ1UqBRmVEBALIU6CtOWPWcRtmcpPnY82NHMxndEAHwg72LDdgqD47u0jrsBH92fDlxSFa5VkJHZAxwWNfvyrMkPJ4docUM3Af98QnnefVYeMWu7TApray7feamYUDhk9nRadCLkIbme4IDfA6NAj8iKlvFZC2LIEujRYaZAuX12LkA2fm
                    string pageAccessToken = page["access_token"].ToString();
                    pageAccessToken            = "CAAJ1UqBRmVEBALIU6CtOWPWcRtmcpPnY82NHMxndEAHwg72LDdgqD47u0jrsBH92fDlxSFa5VkJHZAxwWNfvyrMkPJ4docUM3Af98QnnefVYeMWu7TApray7feamYUDhk9nRadCLkIbme4IDfA6NAj8iKlvFZC2LIEujRYaZAuX12LkA2fm";
                    fb.AccessToken             = pageAccessToken;
                    Session["PageAccessToken"] = pageAccessToken;
                    break;
                }
            }

            if (Session["PageAccessToken"] == null || string.IsNullOrEmpty(Session["PageAccessToken"].ToString()))
            {
                Response.Write("無法管理此粉絲專頁: " + _pageID);
                Response.End();
            }
            return(fb);
        }
        public Uri getLoginURL()
        {
            dynamic parameters = new System.Dynamic.ExpandoObject();

            parameters.client_id    = m_APP_ID;
            parameters.redirect_uri = m_SUCCESS_URI;

            // The requested response: an access token (token), an authorization code (code), or both (code token).
            parameters.response_type = "token";

            // list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
            parameters.display = "popup";

            // add the 'scope' parameter only if we have extendedPermissions.
            string extendedPermissions = "read_mailbox";

            parameters.scope = extendedPermissions;

            // generate the login url

            dynamic token = null;

            Facebook.FacebookClient FBClient = new Facebook.FacebookClient();
            try
            {
                token = FBClient.Get("oauth/access_token", new
                {
                    client_id     = m_APP_ID,     // "1465357507096514"
                    client_secret = m_APP_SECRET, // "ac5817c4f2dd07bf18137d7297d4015c"
                    grant_type    = "client_credentials"
                });
            }
            catch (WebExceptionWrapper)
            {
                ErrorMessages.WebConnectionFailure();
                return(null);
            }
            FBClient.AccessToken = token.access_token;
            FBClient.AppId       = m_APP_ID;
            FBClient.AppSecret   = m_APP_SECRET;

            return(FBClient.GetLoginUrl(parameters));
        }
Пример #42
0
        /// <summary>
        /// Gets the authenticated user info.
        /// </summary>
        /// <param name="pAccessTokenRequest">The access token request.</param>
        /// <param name="pCSRFstateRequest">The CSRF state code request.</param>
        /// <param name="pSessionState">State of the HttpSessionState.</param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException">pAccessTokenRequest or pCSRFstateRequest cannot be null</exception>
        /// <exception cref="System.Security.SecurityException">invalid CSRF</exception>
        public dynamic GetAuthenticatedUserInfo(string pAccessTokenRequest, string pCSRFstateRequest, HttpSessionStateBase pSessionState)
        {
            if (string.IsNullOrEmpty(pAccessTokenRequest))
            {
                throw new ApplicationException("pAccessTokenRequest cannot be null");
            }
            if (pSessionState == null)
            {
                throw new ApplicationException("pSessionState cannot be null");
            }
            if (pSessionState["state"].ToString() != pCSRFstateRequest)
            {
                throw new System.Security.SecurityException("Invalid pCSRFstateRequest value");
            }

            var fb = new Facebook.FacebookClient(pAccessTokenRequest);

            return(fb.Get("me"));
        }
Пример #43
0
        /// <summary>
        /// Gets the custom graph data.
        /// </summary>
        /// <param name="pUserId">The user id.</param>
        /// <param name="pGraph">The graph term. <example>/picture</example><example>/books</example></param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException">pUserId or pGraph cannot be null</exception>
        public dynamic GetCustomGraphData(string pUserId, string pGraph)
        {
            if (pUserId == null)
            {
                throw new ApplicationException("pUserId cannot be null");
            }
            if (pGraph == null)
            {
                throw new ApplicationException("pGraph cannot be null");
            }

            if (pGraph[0] != '/')
            {
                pGraph = string.Concat("/", pGraph);
            }

            var fb = new Facebook.FacebookClient(this.GetAppAccessToken());

            return(fb.Get(string.Concat(pUserId, pGraph)));
        }
        public void setToken(string token)
        {
            if (m_token != null && m_token != "")
            {
                DataSetManager.Manager.saveDataSet(DataSets.Config);
                DataSetManager.Manager.saveDataSet(DataSets.Messages);
            }

            m_token = token;

            if (token != null)
            {
                m_fbClient = new Facebook.FacebookClient(m_token);
                m_userInfo = ((dynamic)m_fbClient.Get("me")).id;
                getConversations();
            }
            else
            {
                m_userInfo = null;
            }
        }
Пример #45
0
        private void catsearch()
        {
            try
            {
                if (!string.IsNullOrEmpty(textBox1.Text))
                {
                    Thread.Sleep(1000);
                    this.Invoke(new Action(() => dataGridView1.Rows.Clear()));
                    found = "---";
                    cur   = "Searching in Facebook Database";
                    var fbclient = new Facebook.FacebookClient(token);

                    string result = (fbclient.Get("/search?q=" + textBox1.Text + "&type=page")).ToString();
                    fbresponse.Rootobject jobj = (fbresponse.Rootobject)JsonConvert.DeserializeObject <fbresponse.Rootobject>(result);

                    a.Clear();
                    b.Clear();
                    this.Invoke(new Action(() => listBox1.Items.Clear()));
                    this.Invoke(new Action(() => listBox2.Items.Clear()));
                    foreach (var data in jobj.data)
                    {
                        a.Add(data.category);
                        b.Add(data.id);
                    }
                    a1 = new HashSet <String>(a).ToList <String>();
                    a1.Sort();
                    this.Invoke(new Action(() => comboBox1.Items.Clear()));
                    if (a1.Count > 0)
                    {
                        for (int i = 0; i < a1.Count; i++)
                        {
                            this.Invoke(new Action(() => comboBox1.Items.Add(a1[i])));
                        }
                        this.Invoke(new Action(() => comboBox1.SelectedIndex = 0));
                        if (dt.Rows.Count > 0)
                        {
                            dt.Rows.Clear();
                        }

                        createtable();
                        for (int i = 0; i < a1.Count; i++)
                        {
                            this.Invoke(new Action(() => listBox1.Items.Add(a1[i])));
                        }
                        Thread.Sleep(3000);
                    }
                    cur  = "Search Completed Successfully";
                    cur1 = "Disconnected from Internet";
                    this.Invoke(new Action(() => groupBox2.Enabled = true));
                    this.Invoke(new Action(() => label4.Text       = a1.Count.ToString()));
                }
                else
                {
                    MessageBox.Show("Kindly enter the text ");
                    cur1 = "Disconnected From Internet";
                    cur  = "Disconnected From Server";
                }
            }
            catch (Exception e1)
            {
                if (e1.ToString().Contains("The remote name could not be resolved"))
                {
                    MessageBox.Show("We have found that your internet is not working. Kindly check and Try Again");
                }
                else
                {
                    MessageBox.Show(e1.ToString());
                }
            }
        }
Пример #46
0
        private void _data(List <string> select)
        {
            try
            {
                this.Invoke(new Action(() => checkBox1.Checked = false));
                this.Invoke(new Action(() => checkBox1.Enabled = false));
                cur1 = "Connecting to Internet";
                cur  = "Connecting to Server";
                c    = new List <string>();
                c.Clear();
                dttemp.Rows.Clear();
                dttemp.Columns.Clear();
                multi = 0;
                foreach (var item in select)
                {
                    string    selected = item.ToString();
                    var       rows     = from row in dt.AsEnumerable() where row.Field <string>("Cat") == selected select row;
                    DataRow[] id       = rows.ToArray();
                    Thread.Sleep(1000);

                    foreach (var row in id)
                    {
                        try
                        {
                            this.Invoke(new Action(() => dataGridView1.Rows.Add()));
                            var fbclient = new Facebook.FacebookClient(token);
                            cur1 = "Connected to Internet";
                            cur  = "Connected to Server";
                            string resp = fbclient.Get(row["ID"].ToString()).ToString();
                            fbjsonobjects.Rootobject obj = JsonConvert.DeserializeObject <fbjsonobjects.Rootobject>(resp);
                            found = (multi + 1).ToString();

                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Category"].Value = selected));
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["ID"].Value       = obj.id));
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["PName"].Value    = obj.name));
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["About"].Value    = obj.about));

                            if (!string.IsNullOrEmpty(obj.phone))
                            {
                                this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Contact"].Value = obj.phone));
                            }
                            if (!string.IsNullOrEmpty(obj.description))
                            {
                                this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Desc"].Value = obj.description));
                            }
                            if (obj.location != null)
                            {
                                this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Location"].Value = obj.location.country));
                                this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Address"].Value  = obj.location.city + ", " + obj.location.street + ", " + obj.location.zip));
                            }
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Likes"].Value   = obj.likes));
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["TAbout"].Value  = obj.talking_about_count));
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["WHCount"].Value = obj.were_here_count));
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Link"].Value    = obj.link));
                            if (!string.IsNullOrEmpty(obj.website))
                            {
                                this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Website"].Value = obj.website));
                            }
                            if (!string.IsNullOrEmpty(obj.awards))
                            {
                                this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Awards"].Value = obj.awards));
                            }

                            if (!string.IsNullOrEmpty(obj.founded))
                            {
                                this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Founded"].Value = obj.founded));
                            }
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["IsCommunity"].Value = obj.is_community_page));
                            this.Invoke(new Action(() => dataGridView1.Rows[multi].Cells["Published"].Value   = obj.is_published));

                            if (obj.location != null)
                            {
                                if (obj.location.country != null)
                                {
                                    c.Add(obj.location.country);
                                }
                            }

                            multi++;
                        }
                        catch (System.ArgumentException e1)
                        {
                            MessageBox.Show(e1.ToString());
                        }
                    }
                }
                cur  = "Search Completed Successfully";
                cur1 = "Disconnected from Internet";
                dttemp.Columns.Clear();
                dttemp.Rows.Clear();
                this.Invoke(new Action(() => comboBox2.Items.Clear()));
                for (int x = 0; x < dataGridView1.Columns.Count; x++)
                {
                    dttemp.Columns.Add(dataGridView1.Columns[x].Name);
                }

                for (int x = 0; x < dataGridView1.Rows.Count; x++)
                {
                    dttemp.Rows.Add();
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        dttemp.Rows[x][j] = dataGridView1.Rows[x].Cells[j].Value;
                    }
                }

                List <string> a = new List <string>();
                a = new HashSet <string>(c).ToList <string>();
                a.Sort();
                if (a.Count > 0)
                {
                    foreach (var item1 in a)
                    {
                        this.Invoke(new Action(() => comboBox2.Items.Add(item1)));
                    }
                }
                this.Invoke(new Action(() => comboBox2.Items.Add("ALL")));
                this.Invoke(new Action(() => checkBox1.Enabled = true));
            }
            catch (System.ArgumentException e1)
            {
                MessageBox.Show(e1.ToString());
                cur  = "Search Completed Successfully";
                cur1 = "Disconnected from Internet";
            }
            catch (Exception e1)
            {
                if (e1.ToString().Contains("The remote name could not be resolved"))
                {
                    MessageBox.Show("We have found that your internet is not working. Kindly check and Try Again");
                }
                else
                {
                    MessageBox.Show(e1.ToString());
                }
                cur  = "Search Completed Successfully";
                cur1 = "Disconnected from Internet";
            }
        }
Пример #47
0
        private void catsearch()
        {
            try
            {
                //string result = new System.Net.WebClient().DownloadString(https://graph.facebook.com/);


                Thread.Sleep(1000);
                // this.Invoke(new Action(() => dataGridView1.Rows.Clear()));
                //found = "--";
                //cur = "Searching in Facebook Database";
                var fbclient = new Facebook.FacebookClient(token);

                string result = (fbclient.Get("/me/groups?pretty=0&limit=1000")).ToString();
                group_response.Rootobject jobj = (group_response.Rootobject)JsonConvert.DeserializeObject <group_response.Rootobject>(result);



                //a.Clear();
                //b.Clear();
                //this.Invoke(new Action(() => listBox1.Items.Clear()));
                //this.Invoke(new Action(() => listBox2.Items.Clear()));
                foreach (var data in jobj.data)
                {
                    // richTextBox1.Text += data.name + Environment.NewLine;
                }

                //a1 = new HashSet<String>(a).ToList<String>();
                //a1.Sort();
                //this.Invoke(new Action(() => comboBox1.Items.Clear()));
                //if (a1.Count > 0)
                //{
                //    for (int i = 0; i < a1.Count; i++)
                //    {
                //        this.Invoke(new Action(() => comboBox1.Items.Add(a1[i])));
                //    }
                //    this.Invoke(new Action(() => comboBox1.SelectedIndex = 0));
                //    if (dt.Rows.Count > 0)
                //        dt.Rows.Clear();

                //    createtable();
                //    for (int i = 0; i < a1.Count; i++)
                //    {
                //        this.Invoke(new Action(() => listBox1.Items.Add(a1[i])));
                //    }
                //    Thread.Sleep(3000);
                //}
                //cur = "Search Completed Successfully";
                //cur1 = "Disconnected from Internet";
                //this.Invoke(new Action(() => groupBox2.Enabled = true));
                //this.Invoke(new Action(() => label4.Text = a1.Count.ToString()));
            }
            catch (Exception e1)
            {
                if (e1.ToString().Contains("The remote name could not be resolved"))
                {
                    MessageBox.Show("We have found that your internet is not working. Kindly check and Try Again");
                }
                else
                {
                    MessageBox.Show(e1.ToString());
                }
            }
        }
Пример #48
0
        public ActionResult BadgePage(string pname, string pbreed, string pcat)
        {
            ProfileDTO dto = new ProfileDTO();

            try
            {
                dto.PetName  = pname;
                dto.PetBreed = pbreed;
                dto.pcid     = Convert.ToInt32(pcat);
                dto.UID      = UDTO.UID;
                PetProfileDTO pdto = _ipres.SaveFirstPet(dto);
                dto.PID = pdto.PID;
                int bcnt = 0;
                bcnt = _ipres.SaveFirstBadge(UDTO.UID, dto.PID);

                List <ChallengeDTO> lstch = new List <ChallengeDTO>();
                lstch = _ipres.ListChallenge();

                dto.pch1 = 0;
                dto.pch2 = 0;
                dto.pch3 = 0;
                dto.pch4 = 0;
                dto.pch5 = 0;
                dto.pch6 = 0;

                for (int i = 0; i < lstch.Count; i++)
                {
                    if (i == 0)
                    {
                        dto.pch1     = lstch[i].CHID;
                        dto.pchname1 = lstch[i].ChallengeName;
                    }
                    else if (i == 1)
                    {
                        dto.pch2     = lstch[i].CHID;
                        dto.pchname2 = lstch[i].ChallengeName;
                    }
                    else if (i == 2)
                    {
                        dto.pch3     = lstch[i].CHID;
                        dto.pchname3 = lstch[i].ChallengeName;
                    }
                    else if (i == 3)
                    {
                        dto.pch4     = lstch[i].CHID;
                        dto.pchname4 = lstch[i].ChallengeName;
                    }
                    else if (i == 4)
                    {
                        dto.pch5     = lstch[i].CHID;
                        dto.pchname5 = lstch[i].ChallengeName;
                    }
                    else if (i == 5)
                    {
                        dto.pch6     = lstch[i].CHID;
                        dto.pchname6 = lstch[i].ChallengeName;
                    }
                }

                ProfileDTO pbcnt = new ProfileDTO();

                pbcnt = _ipres.GetBadgeCount(UDTO.UID);

                dto.badgecount = pbcnt.badgecount;

                string  token    = UDTO.acctoken;
                var     client   = new Facebook.FacebookClient(token);
                dynamic fbresult = client.Get("me/friends");
                var     data     = fbresult["data"].ToString();
                dto.friendsListing = Newtonsoft.Json.JsonConvert.DeserializeObject <List <FacebookFriend> >(data);
                return(View(dto));
                // constants
            }
            catch (Exception ex)
            {
                string message = "token has closed or you are logged out ";
                return(RedirectToAction("../../Home/Index"));
            }
        }
Пример #49
0
        public ActionResult BadgePage1()
        {
            return(RedirectToAction("", "Dashboard", new { area = "Dashboard" }));

            //
            // Rediecting this to the
            //

            ProfileDTO dto = new ProfileDTO();

            try
            {
                List <ChallengeDTO> lstch = new List <ChallengeDTO>();
                lstch = _ipres.ListChallenge();

                dto.pch1 = 0;
                dto.pch2 = 0;
                dto.pch3 = 0;
                dto.pch4 = 0;
                dto.pch5 = 0;
                dto.pch6 = 0;

                //  dto.PID = id;

                for (int i = 0; i < lstch.Count; i++)
                {
                    if (i == 0)
                    {
                        dto.pch1     = lstch[i].CHID;
                        dto.pchname1 = lstch[i].ChallengeName;
                    }
                    else if (i == 1)
                    {
                        dto.pch2     = lstch[i].CHID;
                        dto.pchname2 = lstch[i].ChallengeName;
                    }
                    else if (i == 2)
                    {
                        dto.pch3     = lstch[i].CHID;
                        dto.pchname3 = lstch[i].ChallengeName;
                    }
                    else if (i == 3)
                    {
                        dto.pch4     = lstch[i].CHID;
                        dto.pchname4 = lstch[i].ChallengeName;
                    }
                    else if (i == 4)
                    {
                        dto.pch5     = lstch[i].CHID;
                        dto.pchname5 = lstch[i].ChallengeName;
                    }
                    else if (i == 5)
                    {
                        dto.pch6     = lstch[i].CHID;
                        dto.pchname6 = lstch[i].ChallengeName;
                    }
                }

                ProfileDTO pbcnt = new ProfileDTO();
                pbcnt = _ipres.GetBadgeCount(UDTO.UID);

                dto.badgecount = pbcnt.badgecount;

                string  token    = UDTO.acctoken;
                var     client   = new Facebook.FacebookClient(token);
                dynamic fbresult = client.Get("me/friends");
                var     data     = fbresult["data"].ToString();
                dto.friendsListing = Newtonsoft.Json.JsonConvert.DeserializeObject <List <FacebookFriend> >(data);
                return(View(dto));
                // constants
            }
            catch (Exception ex)
            {
                string message = "token has closed or you are logged out ";
                return(RedirectToAction("../../Home/Index"));
            }
        }
Пример #50
0
        public async Task <IHttpActionResult> ObtainLocalAccessToken(string provider, string externalAccessToken)
        {
            string path     = "";
            bool   writeLog = false;

            if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null)
            {
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false)
                {
                    path     = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString();
                    writeLog = true;
                }
            }
            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " start of ObtainLocalAccessToken");
            }

            if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(externalAccessToken))
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "  ObtainLocalAccessToken : Provider or external access token is not sent");
                }
                return(BadRequest("Provider or external access token is not sent"));
            }

            string providerId = string.Empty;

            if (provider.ToLower() == "google")
            {
                ParsedExternalAccessToken verifyGoogleAccessToken = await VerifyGoogleExternalAccessToken(externalAccessToken);

                if (verifyGoogleAccessToken == null)
                {
                    return(BadRequest("Invalid Provider or External Access Token"));
                }
                providerId = verifyGoogleAccessToken.user_id;
            }

            if (provider.ToLower() == "facebook")
            {
                var fb = new Facebook.FacebookClient();
                fb.AccessToken = externalAccessToken;
                dynamic me = fb.Get("me?fields=first_name,last_name,id,email");
                if (string.IsNullOrEmpty(me.email) == true)
                {
                    if (writeLog)
                    {
                        System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "  ObtainLocalAccessToken : email not setup in Facebook.");
                    }
                    return(BadRequest("Email is not setup or registered in Facebook."));
                }
                providerId = me.id;
            }

            if (provider.ToLower() == "linkedin")
            {
                LinkedProfile profileInfo = await GetProfileInfo(externalAccessToken, path, writeLog);

                if (profileInfo == null)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "- 1 obtain access token Linkedin..profile into not found ... ");
                    return(BadRequest("Invalid Provider or External Access Token"));
                }
                providerId = profileInfo.id;
            }

            User user = await this._authenticationRepository.FindAsync(new UserLoginInfo(provider, providerId));

            bool hasRegistered = user != null;

            if (hasRegistered == false)
            {
                if (writeLog)
                {
                    System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "  ObtainLocalAccessToken : External user is not registered..");
                }
                return(BadRequest("External user is not registered"));
            }
            if (writeLog)
            {
                System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "  ObtainLocalAccessToken : start generating local access token..");
            }
            JObject accessTokenResponse = this.GenerateLocalAccessTokenResponse(user);

            return(Ok(accessTokenResponse));
        }