protected void Page_Load(object sender, EventArgs e)
        {
            AuthenticationService fbAuthentication = new AuthenticationService();
            Me fbMe;
            string fbAccessToken = "";

            if (!fbAuthentication.TryAuthenticate(out fbMe, out fbAccessToken))
            {
                fbAuthentication.Authenticate(Context, out fbMe, out fbAccessToken);
                if (fbMe == null)
                {
                    string message = "Cannot authenticate with facebook";
                    Logger.Instance.Write(LogLevel.Warning, message, new object[] { fbAccessToken });
                    liMessage.Text = message;
                    return;
                }
            }

            _fbAccessToken = fbAccessToken;

            //FriendService friendService = new FriendService(_accessToken);
            //List<Friend> friends = friendService.Get();

            if (!IsPostBack)
            {
                AccountService accountService = new AccountService(fbAccessToken);
                List<Facebook.Account> accounts = accountService.GetAccounts();
                ddlAccounts.DataSource = accounts;
                ddlAccounts.DataTextField = "Name";
                ddlAccounts.DataValueField = "Id";
                ddlAccounts.DataBind();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            AuthenticationService authentication = new AuthenticationService();
            Me me;
            string accessToken = "";

            authentication.Authenticate(Context, out me, out accessToken);

            if (me == null)
            {
                Logger.Instance.Write(LogLevel.Warning, "Cannot authenticate with facebook", new object[] { accessToken });
            }
        }
        //private static IOAuth1ServiceProvider<ITwitter> twitterProvider = null;
        //public static bool TwitterAuth(HttpContext context, out OAuthToken accessToken, out string oauthVerifier, out TwitterProfile me)
        //{
        //    //TrackProtect.Twitter.AuthenticationService authentication = new TrackProtect.Twitter.AuthenticationService();
        //    accessToken = null;
        //    oauthVerifier = null;
        //    me = null;
        //    //OAuthToken requestToken;
        //    //if (!authentication.TryAuthentication(out requestToken, out oauthVerifier))
        //    //{
        //    //    authentication.Authenticate(context);
        //    //    return false;
        //    //}
        //    //authentication.Authorize(context, out me, out accessToken, out oauthVerifier);
        //    return true;
        //}
        //public static bool TwitterAuthorize(out TwitterProfile profile)
        //{
        //    profile = null;
        //    string key = GetConfiguration("twitter.app_id");
        //    string secret = GetConfiguration("twitter.app_secret");
        //    string twitterTarget = "/social/twitter.aspx";
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append(HttpContext.Current.Request.Url.Scheme);
        //    sb.Append("://");
        //    sb.Append(HttpContext.Current.Request.Url.Authority);
        //    sb.Append(twitterTarget);
        //    twitterTarget = sb.ToString();
        //    twitterProvider = new TwitterServiceProvider(key, secret);
        //    NameValueCollection par = new NameValueCollection();
        //    par.Add("force_login", "true");
        //    OAuthToken requestToken = twitterProvider.OAuthOperations.FetchRequestTokenAsync(twitterTarget, par).Result;
        //    using (Database db = new MySqlDatabase())
        //    {
        //        ClientInfo ci = db.GetClientInfo(Util.UserId);
        //        db.UpdateSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.value", requestToken.Value);
        //        db.UpdateSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.secret", requestToken.Secret);
        //    }
        //    //OAuthToken accessToken = twitterProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, new NameValueCollection());
        //    //ITwitter twitter = twitterProvider.GetApi(accessToken.Value, accessToken.Secret);
        //    //TwitterProfile prof = twitter.UserOperations.GetUserProfileAsync().Result;
        //    return true;
        //}
        //public static void TwitterPublish(string text)
        //{
        //    OAuthToken requestToken = TwitterGetRequestToken();
        //    if (requestToken == null)
        //    {
        //        //TODO: TwitterAuthorize();
        //        requestToken = TwitterGetRequestToken();
        //    }
        //    if (requestToken == null)
        //        return; // Can't authorize, can't tweet
        //    string key = GetConfiguration("twitter.app_id");
        //    string secret = GetConfiguration("twitter.app_secret");
        //    twitterProvider = new TwitterServiceProvider(key, secret);
        //    HttpContext.Current.Session["TwitterRequestToken"] = requestToken;
        //    HttpContext.Current.Session["TwitterTweet"] = text;
        //    HttpContext.Current.Response.Redirect(twitterProvider.OAuthOperations.BuildAuthenticateUrl(requestToken.Value, null));
        //}
        //public static void TwitterCallback()
        //{
        //    string oauth_verifier;
        //    using (Database db = new MySqlDatabase())
        //    {
        //        ClientInfo ci = db.GetClientInfo(Util.UserId);
        //        oauth_verifier = db.GetSocialCredential(ci.ClientId, SocialConnector.Twitter, "oauth_verifier");
        //    }
        //    if (string.IsNullOrEmpty(oauth_verifier))
        //        return;
        //    string key = GetConfiguration("twitter.app_id");
        //    string secret = GetConfiguration("twitter.app_secret");
        //    twitterProvider = new TwitterServiceProvider(key, secret);
        //    OAuthToken requestToken = HttpContext.Current.Session["TwitterRequestToken"] as OAuthToken;
        //    AuthorizedRequestToken authorizedRequestToken = new AuthorizedRequestToken(requestToken, oauth_verifier);
        //    OAuthToken token = twitterProvider.OAuthOperations.ExchangeForAccessTokenAsync(authorizedRequestToken, null).Result;
        //    HttpContext.Current.Session["TwitterAccessToken"] = token;
        //    ITwitter twitterClient = twitterProvider.GetApi(token.Value, token.Secret);
        //    //TwitterProfile profile = twitterClient.UserOperations.GetUserProfileAsync().Result;
        //    string tweet = HttpContext.Current.Session["TwitterTweet"] as string;
        //    twitterClient.TimelineOperations.UpdateStatusAsync(tweet);
        //}
        //public static void TwitterComplete()
        //{
        //}
        //private static OAuthToken TwitterGetRequestToken()
        //{
        //    string tokenValue = null, tokenSecret = null;
        //    using (Database db = new MySqlDatabase())
        //    {
        //        ClientInfo ci = db.GetClientInfo(Util.UserId);
        //        tokenValue = db.GetSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.value");
        //        tokenSecret = db.GetSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.secret");
        //    }
        //    if (string.IsNullOrEmpty(tokenValue) || string.IsNullOrEmpty(tokenSecret))
        //        return null;
        //    return new OAuthToken(tokenValue, tokenSecret);
        //}
        /// <summary>
        /// Authenticate with Facebook. When not logged in or never set app authorisation the page will be redirected to Facebook.
        /// </summary>
        /// <param name="context">Http Context</param>
        /// <param name="accessToken">Access token</param>
        /// <param name="me">The user's information</param>
        /// <returns>True if succeed, false if not</returns>
        public static bool FacebookAuth(HttpContext context, out string accessToken, out Me me)
        {
            AuthenticationService authentication = new AuthenticationService();
            me = null;
            accessToken = "";

            if (!authentication.TryAuthenticate(out me, out accessToken))
            {
                authentication.Authenticate(context, out me, out accessToken);
                if (me == null)
                {
                    Logger.Instance.Write(LogLevel.Warning, "Cannot authenticate with facebook", new object[] { accessToken });
                    return false;
                }
            }
            return true;
        }
        private bool FillOwnFacebookInfo()
        {
            if (!string.IsNullOrEmpty(_ManAccClientInfo.FacebookId))
            {
                using (Database db = new MySqlDatabase())
                {
                    ClientInfo ci = db.GetClientInfo(Util.UserId);

                    AuthenticationService authServices = new AuthenticationService();

                    Me me;

                    string accessToken = string.Empty;

                    if (authServices.TryAuthenticate(out me, out accessToken))
                    {
                        Session["FBOwnACC"] = accessToken;

                        try
                        {
                            Session["FBOwnID"] = me.Id;
                        }
                        catch { }

                        FillOwnFBFriendList(Convert.ToString(Session["FBOwnACC"]));

                        FillOwnFBPageList(Convert.ToString(Session["FBOwnACC"]));

                        cbxShareToMyWall.Enabled = true;

                        cbxShareToMyWall.Visible = true;

                        divShareToMyWall.Visible = true;

                        return true;
                    }
                    else
                    {
                        Session["FBOwnACC"] = Session["FBOwnID"] = null;

                        db.RemoveSocialCredential(ci.ClientId, SocialConnector.Facebook);

                        db.UpdateFacebookID(ci.ClientId);

                        FillOwnFBFriendList(null);

                        FillOwnFBPageList(null);

                        cbxShareToMyWall.Enabled = false;

                        cbxShareToMyWall.Visible = false;

                        divShareToMyWall.Visible = false;

                        return false;
                    }
                }
            }

            Session["FBOwnACC"] = Session["FBOwnID"] = null;

            FillOwnFBFriendList(null);

            FillOwnFBPageList(null);

            cbxShareToMyWall.Enabled = false;

            cbxShareToMyWall.Visible = false;

            divShareToMyWall.Visible = false;

            return false;
        }
        private bool FillFacebookInfo()
        {
            if (!string.IsNullOrEmpty(_clientInfo.FacebookId))
            {
                using (Database db = new MySqlDatabase())
                {
                    ClientInfo ci = db.GetClientInfo(Util.UserId);

                    AuthenticationService authServices = new AuthenticationService();

                    Me me;

                    string accessToken = string.Empty;

                    if (authServices.TryAuthenticate(out me, out accessToken))
                    {
                        Session["FBACC"] = accessToken;

                        try
                        {
                            Session["FBID"] = me.Id;
                        }
                        catch { }

                        Session["AppId"] = db.GetSetting("facebook.app_id");

                        Session["AppSecret"] = db.GetSetting("facebook.app_secret");

                        cbxSendToFacebook.Enabled = true;

                        FacebookMsg.Enabled = true;

                        cbxSendToFacebook.Visible = true;

                        return true;
                    }
                    else
                    {
                        Session["FBACC"] = Session["FBID"] = Session["AppId"] = Session["AppSecret"] = null;

                        db.RemoveSocialCredential(ci.ClientId, SocialConnector.Facebook);
                        db.UpdateFacebookID(ci.ClientId);

                        cbxSendToFacebook.Enabled = false;

                        FacebookMsg.Enabled = false;

                        cbxSendToFacebook.Visible = false;

                        return false;
                    }
                }
            }

            Session["FBACC"] = Session["FBID"] = Session["AppId"] = Session["AppSecret"] = null;

            cbxSendToFacebook.Enabled = false;

            FacebookMsg.Enabled = false;

            cbxSendToFacebook.Visible = false;

            return false;
        }
        protected void Page_PreRender(Object o, EventArgs e)
        {
            using (Database db = new MySqlDatabase())
            {
                ClientInfo ci = db.GetClientInfo(Util.UserId);

                bool isNotExpired = true;

                Facebook.AuthenticationService authService = new Facebook.AuthenticationService();

                Facebook.Me me;
                string accessToken = string.Empty;

                if (authService.TryAuthenticate(out me, out accessToken))
                {
                    isNotExpired = true;
                }
                else
                {
                    db.RemoveSocialCredential(ci.ClientId, SocialConnector.Facebook);
                    db.UpdateFacebookID(ci.ClientId);

                    isNotExpired = false;
                }

                if (!string.IsNullOrEmpty(ci.SoundCloudId))
                    SoundcloudItag.Attributes.Add("class", "soundcloud");
                else
                    SoundcloudItag.Attributes.Add("class", "soundcloud disabled");

                if (isNotExpired)
                    FacebookHeading.Attributes.Add("class", "social facebook");
                else
                    FacebookHeading.Attributes.Add("class", "social facebook disabled");

                if (!string.IsNullOrEmpty(ci.TwitterId))
                    TwitterHeading.Attributes.Add("class", "social twitter");
                else
                    TwitterHeading.Attributes.Add("class", "social twitter disabled");
            }
        }
        private bool authenticateAndPopulateInformation()
        {
            try
            {
                using (Database db = new MySqlDatabase())
                {
                    IDictionary<object, object> credDict = db.getAdminFBCred();

                    if (credDict != null)
                    {
                        if (credDict.Count > 0)
                        {
                            AuthenticationService auth = new AuthenticationService();

                            if (auth.TryAuthenticateAdminFBCred(Convert.ToString(credDict["expires"]), Convert.ToString(credDict["fbtoken"])))
                            {
                                adminName = db.getAdminFBName();
                                return true;
                            }
                            else
                                return false;
                        }

                        return false;
                    }
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Write(LogLevel.Error, ex, "Manage Pages");
                return false;
            }
        }