protected void Page_Load(object sender, EventArgs e) { var extendedPermissions = ConfigurationManager.AppSettings["extendedPermissions"].Split(','); if (!FacebookWebContext.Current.IsAuthorized(extendedPermissions)) { // this sample actually does not make use of FormsAuthentication, // besides redirecting to the proper login url defined in web.config // this will also automatically add ReturnUrl. FormsAuthentication.RedirectToLoginPage(); } else { // checking IsPostBack may reduce the number of requests to Facebook server. if (!IsPostBack) { var fb = new FacebookWebClient(); dynamic me = fb.Get("me"); imgProfilePic.ImageUrl = string.Format("https://graph.facebook.com/{0}/picture", me.id); lblName.Text = me.name; lblFirstName.Text = me.first_name; lblLastName.Text = me.last_name; } } }
private void FacebookSignInMethod() { var client = new FacebookWebClient(); dynamic me = client.Get("me"); Session["CameFromSocialNetwork"] = true; if (Membership.GetUser(me.email) == null) { Session["FacebookUserName"] = me.email; Session["FacebookName"] = me.name; string urlRegister = ConvertRelativeUrlToAbsoluteUrl(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Register/Register.aspx")); Response.Redirect(urlRegister); } else { //PortalSecurity.SignOn(me.email, GeneratePasswordHash(me.email as String)); Session["UserName"] = me.email; } Response.Redirect(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/SignIn/LoginIn.aspx")); if (this.Settings["SIGNIN_AUTOMATICALLYHIDE"] != null) { bool hide = bool.Parse(this.Settings["SIGNIN_AUTOMATICALLYHIDE"].ToString()); this.Visible = false; } }
public ActionResult LogIn(string returnUrl) { //On the refresh check if the user is logged in with facebook if (FacebookWebContext.Current.IsAuthenticated()) { try { var client = new FacebookWebClient(); dynamic user = client.Get("me"); var userData = this.MembershipService.GetUser(user.email); if (userData == null) { ModelState.AddModelError("", "the facebook user name is not registered."); } else { this.MembershipService.UpdateLastLogin(userData.Email); this.FormsService.SignIn(userData.Email, false, userData.ToString()); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } } } catch { } } return(View()); }
private void LogInUser() { if (!User.Identity.IsAuthenticated) { FacebookWebClient fb = new FacebookWebClient(); dynamic result = fb.Get("me"); long fbId = long.Parse(result.id); AppUser appUser = Ctx.AppUsers.FirstOrDefault(u => u.FacebookId == fbId); if (appUser == null) { appUser = AppUser.CreateAppUser(fbId); Ctx.AppUsers.AddObject(appUser); } else { if (appUser.LastVisited != DateTime.Today) { appUser.LastVisited = DateTime.Today; appUser.InvitationSentToday = 0; } } Ctx.SaveChanges(); FormsService.SignIn(appUser.Id.ToString(), false); } }
/// <summary> /// Makes a async request to the Facebook server. /// </summary> /// <param name="path"> /// The path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="httpMethod"> /// The http Method. /// </param> /// <param name="callback"> /// The callback. /// </param> /// <param name="userToken"> /// The user Token. /// </param> public virtual void ApiAsync(string path, IDictionary <string, object> parameters, HttpMethod httpMethod, FacebookAsyncCallback callback, object userToken) { var facebookClient = GetFacebookClient(); if (callback != null) { switch (httpMethod) { case HttpMethod.Get: facebookClient.GetCompleted += (o, e) => callback(new FacebookAsyncResult(e.GetResultData(), e.UserState, null, false, true, e.Error as FacebookApiException)); break; case HttpMethod.Post: facebookClient.PostCompleted += (o, e) => callback(new FacebookAsyncResult(e.GetResultData(), e.UserState, null, false, true, e.Error as FacebookApiException)); break; case HttpMethod.Delete: facebookClient.DeleteCompleted += (o, e) => callback(new FacebookAsyncResult(e.GetResultData(), e.UserState, null, false, true, e.Error as FacebookApiException)); break; default: throw new ArgumentOutOfRangeException("httpMethod"); } } facebookClient.ApiAsync(path, FacebookWebClient.AddReturnSslResourceIfRequired(parameters, IsSecureConnection), httpMethod, userToken); }
public ActionResult AcceptPlayerGrid(int page, string offerId) { Guid offerGuid; if (Guid.TryParse(offerId, out offerGuid)) { ViewData["Page"] = page; var app = new FacebookWebClient(); var fbContext = FacebookWebContext.Current; TennisUserModel existingUser = ModelUtils.GetTennisUsers(this.DB).Where(tu => tu.FacebookId == fbContext.UserId).FirstOrDefault(); var model = new AcceptPlayersDataGridModel(offerGuid, existingUser, this.DB); model.IsPostBack = false; return(Json ( new { PlayerGrid = RenderPartialViewToString("PlayerGrid", model) } )); } else { // BUGBUG: return error } return(Json("")); }
public ActionResult Index() { var client = new FacebookWebClient(); dynamic me = client.Get("me"); ViewBag.Name = me.name; ViewBag.Id = me.id.ToString(); JokesFeedViewModel model = new JokesFeedViewModel(); model.UserName = me.name; model.UserId = me.id; IJokesRepository jokeRep = new JokesRepository(); IVotesRepository votesRep = new VotesRepository(); List <Jokes> allJokes = jokeRep.GetAllJokesByDate().ToList <Jokes>(); if (allJokes != null) { foreach (Jokes joke in allJokes) { joke.UserVoteType = votesRep.GetCurrentUserVote(joke.JokeId, joke.UserId); joke.UpVotesCount = votesRep.GetJokesVotesCount(joke.JokeId, true); joke.DownVotesCount = votesRep.GetJokesVotesCount(joke.JokeId, false); dynamic jUser = client.Get(joke.UserId.ToString()); joke.UserName = jUser.name; } model.Jokes = allJokes; } return(View(model)); }
private static bool SendMessage(IEnumerable <long> pushIds, string subject, string templatePath, Dictionary <string, string> tokens) { FacebookOAuthClient oAuth = new FacebookOAuthClient(FacebookApplication.Current); dynamic tokenResponse = oAuth.GetApplicationAccessToken(); string accessToken = tokenResponse.access_token; FacebookWebClient postApp = new FacebookWebClient(accessToken); string body = System.IO.File.ReadAllText(templatePath); tokens.Add("CanvasUrl", FacebookApplication.Current.ReturnUrlPath); foreach (string key in tokens.Keys) { body = body.Replace("{" + key + "}", tokens[key]); } Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("method", "notifications.sendEmail"); parameters.Add("recipients", string.Join(",", pushIds)); parameters.Add("subject", subject); parameters.Add("fbml", body); dynamic messageResult = postApp.Post(parameters); return(true); }
private Core.Entities.User AcceptFacebookOAuthToken(FacebookOAuthResult facebookOAuthResult) { Condition.Requires(facebookOAuthResult).IsNotNull(); // Grab the code. string code = facebookOAuthResult.Code; // Grab the access token. FacebookOAuthClient facebookOAuthClient = FacebookOAuthClient; dynamic result = facebookOAuthClient.ExchangeCodeForAccessToken(code); var oauthData = new OAuthData { OAuthProvider = OAuthProvider.Facebook, AccessToken = result.access_token, ExpiresOn = DateTime.UtcNow.AddSeconds(result.expires) }; // Now grab their info. var facebookWebClient = new FacebookWebClient(oauthData.AccessToken); dynamic facebookUser = facebookWebClient.Get("me"); oauthData.Id = facebookUser.id; // Not sure how to Inject an IUserService because it requires a Session .. which I don't have. var userService = new UserService(DocumentSession); // Now associate this facebook user to an existing user OR create a new one. return(userService.CreateOrUpdate(oauthData, facebookUser.username, facebookUser.name, facebookUser.email)); }
public ActionResult Profile() { var client = new FacebookWebClient(); dynamic me = client.Get("me"); ViewBag.Name = me.name; ViewBag.Id = me.id; return(View()); }
/// <summary> /// Get FB info of the user, save the recommendation into our SimpleDB and then redirect to a web page that posts to the uers's wall. /// </summary> private void ShowFacebookContent() { var fb = new FacebookWebClient(); dynamic myInfo = fb.Get("me"); string myFBId = myInfo["id"];; if (SaveRecoToSimpleDB(myFBId)) { Response.Redirect("posttowall.htm?rn=" + RecoName.Text + "&rc=" + RecoCity.Text + "&rs=" + RecoService.SelectedValue); } }
public ActionResult DataGrid() { var app = new FacebookWebClient(); var fbContext = FacebookWebContext.Current; TennisUserModel existingUser = ModelUtils.GetTennisUsers(this.DB).Where(tu => tu.FacebookId == fbContext.UserId).FirstOrDefault(); //ViewData.Model = new PlayersDataGridModel(existingUser, this.DB); return(View("DataGrid")); }
public ActionResult MensagemPost(string message) { var fb = new FacebookWebClient(); dynamic parameters = new ExpandoObject(); parameters.message = message; dynamic result = fb.Post("me/feed", parameters); return(RedirectToAction("Index", new { success = true })); }
public ActionResult PostCook() { var ns = ConfigurationManager.AppSettings["FBAppNamespace"]; var fb = new FacebookWebClient(); dynamic result = fb.Post(string.Format("/me/{0}:{1}", ns, "cook"), new Dictionary <string, object> { { "recipe", Url.Action("Cookie", "Facebook", null, Request.Url.Scheme) } }); return(RedirectToAction("Cookie", new { id = result.id })); }
protected void Page_Load(object sender, EventArgs e) { if (CanvasAuthorizer.Authorize()) { var fb = new FacebookWebClient(); dynamic me = fb.Get("me"); imgProfilePic.ImageUrl = string.Format("https://graph.facebook.com/{0}/picture", me.id); lblName.Text = me.name; lblFirstName.Text = me.first_name; lblLastName.Text = me.last_name; } }
public ActionResult Index() { var fb = new FacebookWebClient(); dynamic me = fb.Get("me"); ViewBag.ProfilePictureUrl = string.Format("http://graph.facebok.com/{0}/picture", me.id); ViewBag.Name = me.name; ViewBag.FirstName = me.first_name; ViewBag.LastName = me.last_name; ViewBag.MessagePostSuccess = Request.QueryString.AllKeys.Contains("success") && Request.QueryString["success"] == "True"; return(View()); }
/// <summary> /// Makes a async request to the Facebook server. /// </summary> /// <param name="path"> /// The path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="httpMethod"> /// The http Method. /// </param> /// <param name="callback"> /// The callback. /// </param> /// <param name="state"> /// The state. /// </param> public virtual void ApiAsync <T>(string path, IDictionary <string, object> parameters, HttpMethod httpMethod, FacebookAsyncCallback <T> callback, object state) { ApiAsync( path, FacebookWebClient.AddReturnSslResourceIfRequired(parameters, IsSecureConnection), httpMethod, ar => { if (callback != null) { callback(new FacebookAsyncResult <T>(ar.Result, ar.AsyncState, ar.AsyncWaitHandle, ar.CompletedSynchronously, ar.IsCompleted, ar.Error)); } }, state); }
public ActionResult Listas() { var client = new FacebookWebClient(); dynamic me = client.Get("me"); tcc_imoveisEntities tcc = new tcc_imoveisEntities(); IEnumerable <Pesquisa_Result> pesquisa_result = tcc.ListaPesquisaUsuario(long.Parse(me.id)); ViewBag.pesquisas = pesquisa_result.ToList(); return(View()); }
private void UpdateProfile() { var client = new FacebookWebClient(); dynamic me = client.Get("me"); ProfileManager.Provider.ApplicationName = PortalSettings.PortalAlias; ProfileBase profile = ProfileBase.Create(me.email); profile.SetPropertyValue("Email", me.email); profile.SetPropertyValue("Name", me.name); try { profile.Save(); } catch (Exception exc) { ErrorHandler.Publish(LogLevel.Error, "Error al salvar un perfil", exc); } }
public JsonResult SavePesquisa(string nomePesquisa) { if (FacebookWebContext.Current.IsAuthenticated()) { int idPesquisa = Convert.ToInt32(System.Web.HttpContext.Current.Session["pesquisa_id"]); var client = new FacebookWebClient(); dynamic me = client.Get("me"); using (tcc_imoveisEntities tcc = new tcc_imoveisEntities()) { tcc.SalvaPesquisa(idPesquisa, me.id, nomePesquisa); } return(Json(true)); } return(Json(false)); }
//protected long Uid { get; set; } protected virtual void InitFacebook() { this.Facebook = new FacebookWebClient(); bool fbCanvas = this.SessionManager.FbCanvas; // Check for forced fb removal (frame detection from js) if (!String.IsNullOrEmpty(this.Request[SessionHelper.KEY_FBCANVAS])) { bool.TryParse(this.Request[SessionHelper.KEY_FBCANVAS], out fbCanvas); } // Check for facebook signed post (indicates fb canvas) else if (FacebookWebContext.Current.SignedRequest != null) { fbCanvas = true; } this.SessionManager.FbCanvas = fbCanvas; }
/// <summary> /// Makes a request to the Facebook server. /// </summary> /// <param name="path"> /// The path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="resultType"> /// The result type. /// </param> /// <param name="httpMethod"> /// The http method. /// </param> /// <exception cref="Facebook.FacebookApiException"/> /// <returns> /// The json result. /// </returns> public virtual object Api(string path, IDictionary <string, object> parameters, Type resultType, HttpMethod httpMethod) { try { var facebookClient = GetFacebookClient(); return(facebookClient.Api(path, FacebookWebClient.AddReturnSslResourceIfRequired(parameters, IsSecureConnection), httpMethod, resultType)); } catch (FacebookOAuthException) { try { _request.DeleteAuthCookie(); } catch { } throw; } }
public ActionResult Calendar(int page) { ViewData["Page"] = page; var app = new FacebookWebClient(); var fbContext = FacebookWebContext.Current; TennisUserModel existingUser = ModelUtils.GetTennisUsers(this.DB).Where(tu => tu.FacebookId == fbContext.UserId).FirstOrDefault(); var calendarModel = new CalendarModel(DateTime.Now.AddDays(7 * page), existingUser, this.DB); return(Json ( new { Calendar = RenderPartialViewToString("Calendar", calendarModel) } )); }
protected void btnPostToWall_Click(object sender, EventArgs e) { var fb = new FacebookWebClient(); dynamic parameters = new ExpandoObject(); parameters.message = txtMessage.Text; try { dynamic id = fb.Post("me/feed", parameters); lblPostMessageResult.Text = "Message posted successfully"; txtMessage.Text = string.Empty; } catch (FacebookApiException ex) { lblPostMessageResult.Text = ex.Message; } }
private void ShowFacebookContent() { var fb = new FacebookWebClient(); dynamic myInfo = fb.Get("me"); lblName.Text = myInfo.name; pnlHello.Visible = true; dynamic myFriendsInfo = fb.Get("me/friends"); foreach (var friend in myFriendsInfo.data) { FriendsList.Items.Add(friend.name); } /* OR */ //var fbApp = new FacebookApp(); //dynamic info = fbApp.Get("me"); //lblName.Text = info.name; //pnlHello.Visible = true; }
public ActionResult PlayerGrid(int page, string filter) { ViewData["Page"] = page; var app = new FacebookWebClient(); var fbContext = FacebookWebContext.Current; TennisUserModel existingUser = ModelUtils.GetTennisUsers(this.DB).Where(tu => tu.FacebookId == fbContext.UserId).FirstOrDefault(); var model = new PlayersDataGridModel(filter, existingUser, this.DB); model.IsPostBack = !string.IsNullOrEmpty(filter); return(Json ( new { PlayerGrid = RenderPartialViewToString("PlayerGrid", model) } )); }
public ActionResult Index() { var app = new FacebookWebClient(); var fbContext = FacebookWebContext.Current; ViewData["FirstRun"] = false; TennisUserModel existingUser = ModelUtils.GetTennisUsers(this.DB).Where(tu => tu.FacebookId == fbContext.UserId).FirstOrDefault(); if (null == existingUser && null != fbContext.SignedRequest) { if (!fbContext.SignedRequest.Data.ContainsKey("registration")) { return(new RedirectResult("/home/register")); } var regInfo = (JsonObject)fbContext.SignedRequest.Data["registration"]; long locationId; City city = GetCity(regInfo, out locationId); double timeZoneOffset = 0; JsonArray users = (JsonArray)app.Query("SELECT timezone FROM user WHERE uid = " + fbContext.UserId); if (null != users && users.Count > 0) { dynamic userData = users[0]; timeZoneOffset = Convert.ToDouble(userData.timezone); } if (null == city) { JsonArray places = (JsonArray)app.Query("SELECT latitude,longitude FROM place WHERE page_id = " + locationId); if (null != places && places.Count > 0) { JsonObject location = regInfo.GetValue <JsonObject>("location"); dynamic place = places[0]; city = new City(); city.LocationId = location.GetValue <long>("id"); city.Name = location.GetValue <string>("name"); city.Latitude = Convert.ToDouble(place.latitude); city.Longitude = Convert.ToDouble(place.longitude); this.DB.City.InsertOnSubmit(city); } } User user = new User(); user.FacebookId = fbContext.UserId; user.Name = regInfo.GetValue <string>("name"); user.Email = regInfo.GetValue <string>("email"); user.Birthday = regInfo.GetValue <DateTime>("birthday"); user.Gender = regInfo.GetValue <string>("gender") == "male"; user.City = city; user.TimeZoneOffset = timeZoneOffset; user.EmailOffers = true; TennisUser tennisUser = new TennisUser(); tennisUser.FacebookId = fbContext.UserId; tennisUser.Rating = regInfo.GetValue <double>("NTRPRating"); tennisUser.SinglesDoubles = regInfo.GetValue <string>("SinglesDoubles"); tennisUser.CurrentAvailability = true; this.DB.User.InsertOnSubmit(user); this.DB.TennisUser.InsertOnSubmit(tennisUser); this.DB.SubmitChanges(); return(new RedirectResult(Facebook.FacebookApplication.Current.ReturnUrlPath + "?fr=1")); } if (null == existingUser) { return(new RedirectResult("/home/register")); } if (!string.IsNullOrEmpty(Request["fr"])) { ViewData["FirstRun"] = true; } ViewData.Model = new IndexModel(existingUser, this.DB); ViewData["Action"] = "Index"; return(View("~/Views/Home/Index.aspx")); }