コード例 #1
0
ファイル: ProvidersLocator.cs プロジェクト: DCT-UA/Monator
 private static BaseAuthenticationInfo LocateFacebookResponse()
 {
     FacebookAuthenticationInfo authInformation = null;
     var connectSession = new ConnectSession(Constants.FacebookApplicationKey, Constants.FacebookApplicationSecret);
     if (connectSession.IsConnected())
     {
         var facebookApi = new Api(connectSession);
         try
         {
             var userInfo = facebookApi.Users.GetInfo();
             authInformation = new FacebookAuthenticationInfo();
             authInformation.Identifier = userInfo.uid.HasValue ? userInfo.uid.Value.ToString() : String.Empty;
             authInformation.FirstName = userInfo.first_name;
             authInformation.LastName = userInfo.last_name;
             authInformation.Email = userInfo.proxied_email;
             authInformation.UserName = userInfo.name;
             authInformation.Provider = providerModule.GetProvider("Facebook");
             authInformation.Picture = userInfo.pic;
             facebookApi.Auth.ExpireSession();
             return authInformation;
         }
         catch (FacebookException ex)
         {
             return null;
         }
     }
     return authInformation;
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     connectSession = new Facebook.Session.ConnectSession(ConfigurationManager.AppSettings["ApiKey"], ConfigurationManager.AppSettings["Secret"]);
     if (!connectSession.IsConnected())
     {
     }
     else
     {
         api = new Facebook.Rest.Api(connectSession);
         Facebook.Schema.user u = api.Users.GetInfo();
     }
 }
コード例 #3
0
ファイル: HomeController.cs プロジェクト: ledgarl/Samples
        public ActionResult Index()
        {
            ConnectSession session = new ConnectSession(ConfigurationManager.AppSettings["Facebook_API_Key"], ConfigurationManager.AppSettings["Facebook_API_Secret"]);
            if(session.IsConnected())
            {
                Api facebook = new Api(session);

                ViewData["Message"] = "Hello, " + facebook.Users.GetInfo().name;
            }
            else
            {
                ViewData["Message"] = "Login with Facebook!";
            }

            return View();
        }
コード例 #4
0
 private void EnsureSession()
 {
     if (session != null) return;
     session = new ConnectSession(ApiKey, ApiSecret);
 }
コード例 #5
0
        public ActionResult Default()
        {
            #region PreviousCoding
            Repository repoObj = new Repository();
            Member memberData = (Member)SessionStore.GetSessionValue(SessionStore.Memberobject);
            if (memberData != null)
            {
                //ViewData["LocationData"] = locations;
                //ViewData["Memberlocation"] = memberLocation;
            }
            else
            {
                string logoutString = TempData["Logout"] as string;
                if (logoutString != "Logout")
                {
                    const string myFacebookApiKey = "101151816623334";
                    const string myFacebookSecret = "65f49046dce2d1f54d6991e43c4af675";

                    var connectSession = new ConnectSession(myFacebookApiKey, myFacebookSecret);
                    if (connectSession.IsConnected())
                    {
                        ViewData["FBConnected"] = true;
                        var api = new Api(connectSession);
                        ViewData["FBUser"] = api.Users.GetInfo();
                        ViewData["UserID"] = api.Users.GetInfo().uid;
                        SessionStore.SetSessionValue(SessionStore.FacebookConnect, "FacebookUserLoggedIn");
                        string[] fbDetails = new string[2];
                        fbDetails[0] = Convert.ToString("fb_" + api.Users.GetInfo().uid);
                        fbDetails[1] = api.Users.GetInfo().name;
                        SessionStore.SetSessionValue("FacebookDetails", fbDetails);
                        api.Session.Logout();
                        connectSession.Logout();
                        return RedirectToAction("FBUser", "Member");
                    }
                }
            }
            #endregion

            GetTopPlanters();

            CommonMethods objCmnMethods = new CommonMethods();

            string strIpAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
            if (strIpAddress == "127.0.0.1")
                strIpAddress = "61.246.241.162";

            string citySearch = string.Empty;
            string stateSearch = string.Empty;
            string zipCodeSearch = string.Empty;
            string latSearch = string.Empty;
            string lngSearch = string.Empty;
            string[] currentAddress;

            string ipLocation = objCmnMethods.MaxMindIPData(strIpAddress);
            if (!string.IsNullOrEmpty(ipLocation) && (!ipLocation.Contains("IP_NOT_FOUND")))
            {
                //IPaddressAPI
                currentAddress = ipLocation.Split(',');

                if (string.IsNullOrEmpty(currentAddress[1].Replace("\"", "").ToString()))
                    stateSearch = "AZ";
                else
                {
                    stateSearch = currentAddress[1].Replace("\"", "").ToString();
                    //stateSearch = "WA";
                }

                if (string.IsNullOrEmpty(currentAddress[2].ToString()))
                    citySearch = "Phoenix";
                else
                {
                    citySearch = currentAddress[2].Replace("\"", "").ToString();
                    //citySearch = "Seattle";
                }

                if (string.IsNullOrEmpty(currentAddress[3].Replace("\"", "").ToString()))
                {
                    //zipCodeSearch = "85027";
                    SeedAction objS = new SeedAction();
                    LocationAction objLocation = new LocationAction();
                    string cityId = objLocation.GetCityIdByCityName(citySearch, stateSearch);
                    zipCodeSearch = objS.GetZipOfSeedByCityId(cityId);
                }
                else
                    zipCodeSearch = currentAddress[3].Replace("\"", "").ToString();

                latSearch = currentAddress[4].Replace("\"", "").ToString();
                lngSearch = currentAddress[5].Replace("\"", "").ToString();
            }
            else
            {
                //MaxMind
                ipLocation = objCmnMethods.IP2AddressMaxMind();
                currentAddress = ipLocation.Split('\'');

                if (string.IsNullOrEmpty(currentAddress[7].ToString()))
                    stateSearch = "AZ";
                else
                    stateSearch = currentAddress[7].ToString();

                if (string.IsNullOrEmpty(currentAddress[5].ToString()))
                    citySearch = "Phoenix";
                else
                    citySearch = currentAddress[5].ToString();

                if (string.IsNullOrEmpty(currentAddress[15].ToString()))
                    zipCodeSearch = "85027";
                else
                    zipCodeSearch = currentAddress[15].ToString();

                latSearch = currentAddress[11].ToString();
                lngSearch = currentAddress[13].ToString();
            }

            ViewData["LocLat"] = latSearch;
            ViewData["LocLng"] = lngSearch;
            Session["LocLatLng"] = latSearch + "," + lngSearch;

            SeedAction objSeed = new SeedAction();
            IList<Seed> lstSeed = getHomeSearchResult(citySearch, "", "", zipCodeSearch, "");
            if (lstSeed.Count > 0)
            {
                ViewData["SeedList"] = lstSeed.OrderByDescending(x => x.createDate).ToList();
                ViewData["userLocation"] = "Your Location : " + citySearch + ", " + stateSearch;
                ViewData["CatLocation"] = citySearch + ", " + stateSearch;
            }
            else
            {
                lstSeed = repoObj.List<Seed>().Where(x => x.status.Equals(SystemStatements.STATUS_NEW) || x.status.Equals(SystemStatements.STATUS_GROWING)).OrderByDescending(x => x.createDate).Take(20).ToList();
                ViewData["SeedList"] = lstSeed;
                ViewData["userLocation"] = "Your Location : " + citySearch + ", " + stateSearch;
                ViewData["CatLocation"] = citySearch + ", " + stateSearch;
                ViewData["CitySearchMsg"] = "<span>Sorry, no seeds planted in '" + citySearch + "' area. Showing latest additions.</span>";
                string streamFeed = "Select top 20 * from Seed order by createDate desc";
                SessionStore.SetSessionValue(SessionStore.DefaultFeed, streamFeed);
            }

            string advSearch = TempData["DiscoverSeed"] as string;
            if (advSearch != "AdvanceSearch")
            {
                if (lstSeed.Count > 0)
                    SessionStore.SetSessionValue(SessionStore.DiscoverSeed, lstSeed);
            }

            if (SessionStore.GetSessionValue(SessionStore.DiscoverSeed) != null)
                lstSeed = (IList<Seed>)SessionStore.GetSessionValue(SessionStore.DiscoverSeed);

            int rowCount = lstSeed.Count;
            Session["RowCount"] = rowCount;
            Session["PageCount"] = "1";
            ViewData["SeedList"] = lstSeed.Take(10).ToList();
            ViewData["PrevVisibility"] = "visibility:hidden;";
            if (lstSeed.Count > 10)
                ViewData["NxtVisibility"] = "visibility:visible;";
            else
                ViewData["NxtVisibility"] = "visibility:hidden;";

            foreach (Seed sd in lstSeed)
            {
                sd.seedDistance = (int)objCmnMethods.distance(Convert.ToDouble(latSearch), Convert.ToDouble(lngSearch), Convert.ToDouble(sd.Location.localLat), Convert.ToDouble(sd.Location.localLong));
            }
            if (lstSeed.Count > 0)
                SessionStore.SetSessionValue(SessionStore.DiscoverSeed, lstSeed);
            ViewData["SeedList"] = lstSeed.OrderBy(x => x.seedDistance).ToList();

            ViewData["MarkerList"] = MarkerGenerator((IList<Seed>)ViewData["SeedList"]);

            //ListBox
            if (Session["SelectedCategory"] != null)
            {
                Session["SelectedCategory"] = null;
            }
            else
            {
                if (str != null)
                {
                    string myString = null;
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (i == 0)
                        {
                            myString = str[i];

                        }
                        else
                        {
                            myString = myString + "," + str[i];
                        }
                    }
                    Session["SelectedCategory"] = myString;
                    ViewData["SelectedCategories"] = myString;
                }
            }
            //ListBox
            if (lstSeed.Count > 0)
            {
                CategoryAction objCat = new CategoryAction();
                IList<Category> categ = new List<Category>();
                Category c = null;
                foreach (Seed s in lstSeed)
                {
                    IList<Category> listCategory = s.Categories.ToList();
                    if (listCategory.Count > 0)
                    {
                        foreach (Category c1 in listCategory)
                        {
                            c = objCat.GetCategoryById(s.Categories.FirstOrDefault().id.ToString());
                            if (c != null)
                                categ.Add(c);
                        }
                    }
                }
                ViewData["SeedCategories"] = categ.Distinct().ToList();
            }

            return View();
        }
コード例 #6
0
        private string ManageFacebook()
        {
            string FacebookUserAuthicatedCheck = "false";
            // Authenticated, created session and API object
            _connectSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);
            _connectSession.Logout();
            _connectSession.Login();

            //Check User Is Login in with Facebook
            if (_connectSession.IsConnected())
            {
                // Authenticated, create API instance

                _facebookAPI = new Api(_connectSession);
                user user = null;
                if (_facebookAPI != null)
                {
                    try
                    {
                        // Load user
                        user = _facebookAPI.Users.GetInfo();
                        string a = _facebookAPI.LogOffUrl;
                    }
                    catch (Exception ex)
                    {
                        return FacebookUserAuthicatedCheck;
                    }
                }

                if (user != null)
                {
                    long FacebookID = user.uid.Value;

                    FacebookUserAuthicatedCheck = FacebookAuthenticateUser(FacebookID);

                    return FacebookUserAuthicatedCheck;
                }
            }

            return FacebookUserAuthicatedCheck;
        }
コード例 #7
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (!model.RememberMe)
                {
                    if (Request.Cookies["CLU"] != null)
                    {
                        DeleteCookieRememberMe();
                    }
                }

                if (Request.Cookies["CLU"] != null)
                {
                    model.RememberMe = true;
                    model.Username = Request.Cookies["CLU"].Value.ToString();
                }

                string AuthenticationStatus = String.Empty;
                _connectSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);
                _connectSession.Logout();
                _connectSession.Login();

                //Check User Is Login in with Facebook
                if (_connectSession.IsConnected())
                {
                    AuthenticationStatus = ManageFacebook();
                    if (AuthenticationStatus == "true")
                    {
                        return Redirect("~/Profile/CurrentCourses");
                        //return Redirect("~/CourseHome/CourseHome?CourseID=10&IsTopVoted=0");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(model.Password))
                        {
                            model.Password = Cryptography.Cryptography.Encrypt(model.Password);
                            AuthenticationStatus = AuthenticateUser(model.Username, model.Password, model.RememberMe);
                        }
                        if (AuthenticationStatus == "true")
                        {
                            return Redirect("~/Profile/CurrentCourses");
                            //return Redirect("~/CourseHome/CourseHome?CourseID=10&IsTopVoted=0");
                        }
                        else
                        {
                            ViewData["Message"] = string.Format("Facebook user does not exist !");
                            WebCookies WebCookieInstance = new WebCookies();
                            WebCookieInstance.ClearCookies();
                            FormsAuthentication.SignOut();
                            return View(model);
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(model.Password))
                    {
                        model.Password = Cryptography.Cryptography.Encrypt(model.Password);
                        AuthenticationStatus = AuthenticateUser(model.Username, model.Password, model.RememberMe);
                    }
                    if (AuthenticationStatus == "true")
                    {
                        return Redirect("~/Profile/CurrentCourses");
                        //return Redirect("~/CourseHome/CourseHome?CourseID=10&IsTopVoted=0");
                    }
                    else
                    {
                        if ((model.Username != null || model.Password != null))
                        {
                            if (Request.Cookies["CLU"] != null)
                            {
                                model.RememberMe = true;
                                model.Username = Request.Cookies["CLU"].Value.ToString();
                                if (AuthenticationStatus == "false" && model.Password != null)
                                {
                                    ViewData["Message"] = string.Format("Invalid username/password combination. Please try again.");
                                }
                            }
                            else
                            {
                                ViewData["Message"] = string.Format("Invalid username/password combination. Please try again.");
                            }
                        }
                        WebCookies WebCookieInstance = new WebCookies();
                        WebCookieInstance.ClearCookies();
                        FormsAuthentication.SignOut();
                        return View(model);
                    }
                }
            }
            else
            {
                //ViewData["Message"] = string.Format("Invalid username/password combination. Please try again.");
                return View(model);
            }
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            FacebookSession session = null;
            FilterContext = filterContext;
            switch (PageType)
            {
                case FacebookPageType.Connect:
                    session = new ConnectSession(ApiKey ?? WebConfigurationManager.AppSettings["ApiKey"],
                        Secret ?? WebConfigurationManager.AppSettings["Secret"]);
                    break;
                case FacebookPageType.IFrame:
                    session = new IFrameCanvasSession(ApiKey ?? WebConfigurationManager.AppSettings["ApiKey"],
                        Secret ?? WebConfigurationManager.AppSettings["Secret"],
                        ParsePermissions(RequiredPermissions));
                    break;
                case FacebookPageType.FBML:
                    session = new FBMLCanvasSession(ApiKey ?? WebConfigurationManager.AppSettings["ApiKey"],
                        Secret ?? WebConfigurationManager.AppSettings["Secret"],
                        ParsePermissions(RequiredPermissions));
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (string.IsNullOrEmpty(session.SessionKey))
            {
                AddFormValuesToCookie(filterContext.HttpContext.Response, filterContext.HttpContext.Request.Form);
                if(session is CanvasSession)
                {
                    filterContext.Result = new ContentResult { Content = ((CanvasSession)session).GetRedirect() };
                }
                else
                {
                    var returnUrl = HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.ToString());
                    filterContext.Result = new RedirectResult("/account/logon/?returnUrl=" + returnUrl);
                }
                return;
            }

            var permissionsString = session.CheckPermissions();
            if (!string.IsNullOrEmpty(permissionsString))
            {
                AddFormValuesToCookie(filterContext.HttpContext.Response, filterContext.HttpContext.Request.Form);
                if (session is CanvasSession)
                {
                    filterContext.Result = new ContentResult
                   	{
                   		Content = ((CanvasSession) session).GetPermissionsRedirect(
                   			session.GetPermissionUrl(permissionsString, ((CanvasSession) session).GetNextUrl()))
                   	};
                }
                return;
            }

            // Everything is ok, so I need to stash this session somewhere for use.
            filterContext.HttpContext.Items.Add(FACEBOOK_CANVAS_SESSION, session);

            // Now I need to set the user context
            var currentUserId = session.UserId;
            if (currentUserId != 0)
            {
                var identity = new GenericIdentity(currentUserId.ToString());
                filterContext.HttpContext.User = new GenericPrincipal(identity, null);
            }
        }
    protected void btn_Go_Click(object sender, EventArgs e)
    {
        _connectSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);

        FBConnectAuthentication auth = new FBConnectAuthentication("148883595138929", "94da7bd77167c18aa7b075d87f445cf9"); //Note this is the "app id", not "api Key"
        if (auth.Validate() != ValidationState.Valid)
        {
            // The request does not contain the details of a valid Facebook connect session -
            // you'll probably want to throw an error here.
            this.lbl_currentStatus.Text = "Error";

        }
        else
        {
            FBConnectSession fbSession = auth.GetSession();
            string userId = fbSession.UserID;
            string sessionKey = fbSession.SessionKey;
            string accessToken = fbSession.AccessToken; //This is the Graph API access token (available only when using the Graph API)
            // These values can now be used to communicate with Facebook on behalf of your user - perhaps using the Facebook Developer Toolkit
            // The expiry time and session secret is also available.
            this.lbl_currentStatus.Text = accessToken;

           /* if (!_connectSession.IsConnected())
            {
                this.lbl_currentStatus.Text = "Usuario no conectado";
            }
            else
            {
                _facebookAPI = new Api(_connectSession);

                user user = _facebookAPI.Users.GetInfo();

                this.lbl_user.Text = string.Format("{0} {1}", user.first_name, user.last_name);

            }*/

            if (userId == "639765435")
            {
                lbl_user.Text = "Hector Fernando Sabillon";
            }
            else if (userId == "894045382")
            {
                lbl_user.Text = "Ricardo Escobar";
            }
            else if(userId == "1037870586")
            {
                lbl_user.Text = "Uchiha Sama";
            }
            else if (userId == "549886672")
            {
                lbl_user.Text = "Alexis Castillo";
            }
            else if (userId == "553699803")
            {
                lbl_user.Text = "Rogger Vasquez";
            }
            else
            {
                lbl_user.Text = userId;
            }

        }

        if (lbl_currentStatus.Text != "Error" && lbl_currentStatus.Text!="No estas conectado")
        {
            tbx_pub.Visible = true;
            btn_Publicar.Visible = true;
            btn_OtroDia.Visible = true;
            lbl_currentStatus.Text = "Conectado";
        }
    }