示例#1
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (Session["FacebookUserId"] == null)
            {
                FacebookApp      facebookApp = new FacebookApp();
                CanvasAuthorizer authorizor  = new CanvasAuthorizer(facebookApp);
                authorizor.ReturnUrlPath = "default.aspx";
                authorizor.Perms         = "publish_stream"; //,offline_access
                authorizor.Authorize(Request, Response);
                IsLoggedIn = authorizor.IsAuthorized();

                if (IsLoggedIn)
                {
                    Session["FacebookUserId"] = facebookApp.UserId;
                }
                else
                {
                    Session["FacebookUserId"] = 0;
                }
            }

            FacebookUserId = (long)Session["FacebookUserId"];
            IsLoggedIn     = FacebookUserId > 0;
        }
示例#2
0
        private void button1_Click(object sender, EventArgs e)
        {
            lblStep1.Visible = false;
            FbLoginBrowser dlg = new FbLoginBrowser();

            dlg.ExtendedPermissions.Add("read_stream");
            dlg.ExtendedPermissions.Add("friends_birthday");
            dlg.ExtendedPermissions.Add("friends_status");
            dlg.ExtendedPermissions.Add("friends_education_history");
            dlg.ExtendedPermissions.Add("friends_relationships");

            dlg.AppId = FbApp.ApplicationKey;
            dlg.ShowDialog();

            if (dlg.Success)
            {
                app = new FacebookApp(dlg.AccessToken);
                var     result  = app.Get("me");
                JObject jobject = JObject.Parse(result.ToString());
                tsStatusMessage.Text = string.Format("Connected as {0}", jobject["name"]);
                me.Name   = (string)jobject["name"];
                me.Gender = (string)jobject["gender"];

                btnGetFriends.Enabled = true;
                btnConnect.Enabled    = false;
                lblStep1.Visible      = true;
            }
            else
            {
                tsStatusMessage.Text = string.Format("FAILED to connect: {0}", dlg.ErrorReason);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            CanvasUrlBuilder = new CanvasUrlBuilder(FacebookApplication.Current, new HttpRequestWrapper(Request));

            var client = new FacebookWebClient();
            PicUrlWebClient = ((dynamic)client.Get("/4", new Dictionary<string, object> { { "fields", "picture" } })).picture;
            
            var app = new FacebookApp();
            PicUrlApp = ((dynamic)app.Get("/4", new Dictionary<string, object> { { "fields", "picture" } })).picture;
        }
示例#4
0
        public void Get_Insights_By_Facebook_Ids()
        {
            dynamic parameters = new ExpandoObject();
            parameters.ids = String.Join(",", 136963329653478, 113767478670024);
            parameters.period = (int)TimeSpan.FromDays(1).TotalSeconds;
            parameters.endtime = (int)DateTime.UtcNow.Date.ToUnixTime();

            var app = new FacebookApp(ConfigurationManager.AppSettings["AccessToken"]);
            var result = app.Get<List<KeyValuePair<string, InsightCollectionItem>>>("/insights", (IDictionary<string, object>)parameters);

            Assert.Equal(2, result.Count);
        }
示例#5
0
        public ActionResult Index()
        {
            string                  xml;
            FacebookApp             app             = new FacebookApp();
            JsonObject              me              = (JsonObject)app.Get("me");
            JsonObject              friends         = (JsonObject)app.Get("me/friends");
            FacebookFriends         facebookFriends = JsonConvert.DeserializeObject <FacebookFriends>(friends.ToString());
            XmlSerializer           serializer      = new XmlSerializer(typeof(GraphML));
            XmlSerializerNamespaces namespaces      = new XmlSerializerNamespaces();
            List <FacebookUser>     users           = new List <FacebookUser>();
            GraphML                 graphML         = new GraphML();

            // Add Users
            users.Add(JsonConvert.DeserializeObject <FacebookUser>(me.ToString()));

            foreach (FacebookUser user in facebookFriends.Friends)
            {
                JsonObject friend = (JsonObject)app.Get(user.Id.ToString());
                users.Add(JsonConvert.DeserializeObject <FacebookUser>(friend.ToString()));
            }

            // Prepare the keys
            AddKeys(graphML.Keys);

            // Add the Berico namspace
            namespaces.Add("berico", "http://graph.bericotechnologies.com/xmlns");

            foreach (FacebookUser user in users)
            {
                graphML.Graph.Nodes.Add(Mapper.Map <FacebookUser, Node>(user));
            }

            using (MemoryStream stream = new MemoryStream())
            {
                XmlDocument doc = new XmlDocument();

                serializer.Serialize(stream, graphML, namespaces);
                stream.Seek(0, SeekOrigin.Begin);
                doc.Load(stream);

                // Read the XML into a string object
                xml = doc.OuterXml;
            }

            return(this.Content(xml, "txt/xml"));
        }
        public ActionResult Index()
        {
            string xml;
            FacebookApp app = new FacebookApp();
            JsonObject me = (JsonObject)app.Get("me");
            JsonObject friends = (JsonObject)app.Get("me/friends");
            FacebookFriends facebookFriends = JsonConvert.DeserializeObject<FacebookFriends>(friends.ToString());
            XmlSerializer serializer = new XmlSerializer(typeof(GraphML));
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            List<FacebookUser> users = new List<FacebookUser>();
            GraphML graphML = new GraphML();

            // Add Users
            users.Add(JsonConvert.DeserializeObject<FacebookUser>(me.ToString()));

            foreach (FacebookUser user in facebookFriends.Friends)
            {
                JsonObject friend = (JsonObject)app.Get(user.Id.ToString());
                users.Add(JsonConvert.DeserializeObject<FacebookUser>(friend.ToString()));
            }

            // Prepare the keys
            AddKeys(graphML.Keys);

            // Add the Berico namspace
            namespaces.Add("berico", "http://graph.bericotechnologies.com/xmlns");

            foreach (FacebookUser user in users)
            {
                graphML.Graph.Nodes.Add(Mapper.Map<FacebookUser, Node>(user));
            }

            using (MemoryStream stream = new MemoryStream())
            {
                XmlDocument doc = new XmlDocument();

                serializer.Serialize(stream, graphML, namespaces);
                stream.Seek(0, SeekOrigin.Begin);
                doc.Load(stream);

                // Read the XML into a string object
                xml = doc.OuterXml;
            }

            return this.Content(xml, "txt/xml");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            FacebookApp fap = new FacebookApp();

            fap.AppId     = "************";
            fap.AppSecret = "********************";
            string requested_Data     = Request.Form["signed_request"];
            FacebookSignedRequest fsr = fap.ParseSignedRequest(requested_Data);
            // string json = JsonConvert.SerializeObject(fsr.Dictionary, Formatting.Indented);
            UserData ud = new UserData(fsr);

            Response.Write(ud.name + "<br>");
            Response.Write(ud.birthday + "<br>");
            Response.Write(ud.country + "<br>");
            Response.Write(ud.email + "<br>");
            Response.Write(ud.gender + "<br>");
            Response.Write(ud.location + "<br>");
            Response.Write(ud.userId + "<br>");
        }
示例#8
0
        private void FacebookAuthBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult result;
            if (FacebookOAuthResult.TryParse(e.Uri, out result))
            {
                if (result.IsSuccess)
                {
                    //user logged in successfully and access token is returned from facebook.
                    //Save that Access token for future use.
                    FacebookApp client = new FacebookApp(result.AccessToken);
                    client.GetAsync("me", (facebookResult) =>
                    {
                        IsolatedStorageSettings.ApplicationSettings["FacebookUserId"] = (facebookResult.Result as JsonObject)["id"].ToString();
                    });

                    IsolatedStorageSettings.ApplicationSettings["FacebookAccessToken"] = result.AccessToken;
                    FacebookAuthBrowser.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MessageBox.Show(result.ErrorDescription + " \n" + result.ErrorReason);
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            lblStep1.Visible = false;
            FbLoginBrowser dlg = new FbLoginBrowser();
            dlg.ExtendedPermissions.Add("read_stream");
            dlg.ExtendedPermissions.Add("friends_birthday");
            dlg.ExtendedPermissions.Add("friends_status");
            dlg.ExtendedPermissions.Add("friends_education_history");
            dlg.ExtendedPermissions.Add("friends_relationships");

            dlg.AppId = FbApp.ApplicationKey;
            dlg.ShowDialog();

            if (dlg.Success)
            {
                app = new FacebookApp(dlg.AccessToken);
                var result = app.Get("me");
                JObject jobject = JObject.Parse(result.ToString());
                tsStatusMessage.Text = string.Format("Connected as {0}", jobject["name"]);
                me.Name = (string)jobject["name"];
                me.Gender = (string)jobject["gender"];

                btnGetFriends.Enabled = true;
                btnConnect.Enabled = false;
                lblStep1.Visible = true;

            }
            else
                tsStatusMessage.Text = string.Format("FAILED to connect: {0}", dlg.ErrorReason);
        }
示例#10
0
 /// <summary>
 /// This method uploads the stored photo to Facebook on the given album Id.
 /// </summary>
 /// <param name="accessToken">the OAuth access token</param>
 /// <param name="AlbumId">The album Id to which the photo will belong.</param>
 private void UploadPhoto(string accessToken, string AlbumId)
 {
     FacebookApp facebookClient = new FacebookApp(accessToken);
     FacebookMediaObject mediaObject = new FacebookMediaObject
     {
         FileName = "image",
         ContentType = "image/png"
     };
     byte[] fileBytes = bytes;
     mediaObject.SetValue(fileBytes);
     IDictionary<string, object> upload = new Dictionary<string, object>();
     upload.Add("name", "photo name");
     upload.Add("message", PhotoLegend);
     upload.Add("@file.jpg", mediaObject);
     facebookClient.PostAsync("/" + AlbumId + "/photos", upload, UploadPhotoAsyncCallback);
 }
示例#11
0
        /// <summary>
        /// A method which executes a FQL query to get the album Id to which the photo will be uploaded.
        /// </summary>
        /// <param name="accessToken">the OAuth access token</param>
        /// <param name="albumId">Id of the album's owner (current user)</param>
        private void GetAlbum(string accessToken, string userId)
        {
            FacebookApp facebookClient = new FacebookApp(accessToken);

            facebookClient.QueryAsync("SELECT object_id, name FROM album WHERE owner=\"" + userId + "\"", GetAlbumAsyncCallback);
        }
示例#12
0
 /// <summary>
 /// A method to create an ODAF album on Facebook.
 /// </summary>
 /// <param name="accessToken">the OAuth access token</param>
 private void CreateAlbum(string accessToken)
 {
     FacebookApp facebookClient = new FacebookApp(accessToken);
     Dictionary<string, object> albumParameters = new Dictionary<string, object>();
     albumParameters.Add("message", App.FacebookAlbumDescription);
     albumParameters.Add("name", App.FacebookAlbumName);
     facebookClient.PostAsync("/me/albums", albumParameters, CreateAlbumAsyncCallback);
 }
 public FacebookLogin()
 {
     _facebookApp      = new FacebookApp();
     _authorizer       = new CanvasAuthorizer(_facebookApp);
     _authorizer.Perms = "publish_stream,offline_access";
 }
        private List <Result> UpdateAchievements()
        {
            IEnumerable <User> users;

            using (IAchievementManager manager = new AchievementManager())
            {
                // get users configured for auto update
                users = manager.GetAutoUpdateUsers();
            }

            List <Result> results = new List <Result>();

            using (SteamCommunityManager manager = new SteamCommunityManager())
                using (IAchievementService service = new AchievementService())
                {
                    foreach (User user in users)
                    {
                        Log("User: "******" ( " + user.FacebookUserId + ")");

                        if (String.IsNullOrEmpty(user.AccessToken))
                        {
                            Log("Empty AccessToken");

                            // if there is no access token, the user hasn't given the app offline_access
                            continue;
                        }

                        // update the user's achievements
                        int updated = service.UpdateAchievements(user.SteamUserId);

                        if (updated == 0)
                        {
                            Log("No updated achievements");

                            continue;
                        }

                        // get the user's unpublished achievements
                        IEnumerable <SimpleAchievement> achievements = service.GetNewAchievements(user.SteamUserId);

                        if (!achievements.Any())
                        {
                            Log("No unpublished achievements");

                            continue;
                        }

                        FacebookApp app          = new FacebookApp(user.AccessToken);
                        string      userFeedPath = String.Format("/{0}/feed/", user.FacebookUserId);

                        List <int> publishedAchievements = new List <int>();

                        // post the first 5 new achievements
                        foreach (SimpleAchievement achievement in achievements.Take(5))
                        {
                            string message = String.Format("{0} earned an achievement in {1}",
                                                           user.SteamUserId, achievement.Game.Name);
                            dynamic parameters = new ExpandoObject();
                            parameters.link        = achievement.Game.StatsUrl;
                            parameters.message     = message;
                            parameters.name        = achievement.Name;
                            parameters.description = achievement.Description;
                            parameters.picture     = achievement.ImageUrl;

                            Log(message);

                            Result result = new Result
                            {
                                SteamUserId = user.SteamUserId,
                                GameName    = achievement.Game.Name,
                                Description = achievement.Name
                            };

                            try
                            {
                                dynamic response = app.Api(userFeedPath, parameters, HttpMethod.Post);

                                publishedAchievements.Add(achievement.Id);
                            }
                            catch (FacebookApiException ex)
                            {
                                // log Facebook errors and continue
                                result.ExceptionMessage += Environment.NewLine + "Exception: " + ex.Message;
                                if (ex.InnerException != null)
                                {
                                    result.ExceptionMessage += Environment.NewLine + ", Inner Exception: " + ex.InnerException.Message;
                                }

                                Log(result.ExceptionMessage);
                            }

                            results.Add(result);
                        }

                        // update the published flag
                        service.PublishAchievements(user.SteamUserId, publishedAchievements);

                        Log("User achievements published");
                    }
                }

            return(results);
        }
示例#15
0
	// Use this for initialization
	public void Start () {
		var appManager = AppManager.GetSingleton();
		_app = (FacebookApp)appManager.GetAppBehaviour("facebook");
	}
        public async Task <AssertionGrantResult> ValidateAsync(string assertion)
        {
            // Verify the token is for our app. This also indirectly verifies the token is valid since it's useable.
            string appEndpoint = "https://graph.facebook.com/app/?access_token=" + assertion;

            using (HttpResponseMessage response = await _httpClient.GetAsync(appEndpoint))
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(new AssertionGrantResult {
                        Error = "Token validation failed"
                    });
                }

                Stream stream = await response.Content.ReadAsStreamAsync();

                using (JsonTextReader reader = new(new StreamReader(stream)))
                {
                    JsonSerializer serializer  = new();
                    FacebookApp    facebookApp = serializer.Deserialize <FacebookApp>(reader);
                    if (!_authenticationSettings.Facebook.AppId.Equals(facebookApp.Id, StringComparison.OrdinalIgnoreCase))
                    {
                        return(new AssertionGrantResult {
                            Error = "The token was for the wrong app"
                        });
                    }
                }
            }

            // Get the facebook user id. We also have it on the client already but we can't trust clients to tell us who they are.
            FacebookUser facebookUser;
            string       userEndpoint = "https://graph.facebook.com/me?fields=id,email&access_token=" + assertion;

            using (HttpResponseMessage response = await _httpClient.GetAsync(userEndpoint))
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(new AssertionGrantResult {
                        Error = "Token validation failed"
                    });
                }

                Stream stream = await response.Content.ReadAsStreamAsync();

                using (JsonTextReader reader = new(new StreamReader(stream)))
                {
                    JsonSerializer serializer = new();
                    facebookUser = serializer.Deserialize <FacebookUser>(reader);
                }
            }

            if (string.IsNullOrEmpty(facebookUser.Id))
            {
                return(new AssertionGrantResult {
                    Error = "The token does not belong to a valid user"
                });
            }

            return(new AssertionGrantResult {
                ExternalUserId = facebookUser.Id, ExternalUserEmail = facebookUser.Email
            });
        }
示例#17
0
 public GraphService(FacebookApp app)
 {
     this.App = app;
 }
示例#18
0
 public GraphService()
 {
     this.App = new FacebookApp();
 }
示例#19
0
    }//end of InitializePagingVars()
		
	protected void Page_PreRender(object sender, EventArgs e)
    {
		try
		{
			//code will load and initialize the JavaScript SDK with all standard options
			if (!Page.ClientScript.IsClientScriptBlockRegistered("facebook_api"))
               	Page.ClientScript.RegisterClientScriptInclude("facebook_api", String.Format("http://connect.facebook.net/{0}/all.js", "en_US"));
 
           	if (!Page.ClientScript.IsStartupScriptRegistered("facebook_api_init"))
				Page.ClientScript.RegisterStartupScript(typeof(string), "facebook_api_init", String.Format("FB.init({{appId: '{0}', status: true, cookie: true, xfbml: true, oauth: true }});", "574005609290762"), true);
 
           	if (!Page.ClientScript.IsStartupScriptRegistered("facebook_login"))
           	{
               	string facebookLogin = String.Format("function fblogin() {{ FB.login(function(response) {{ if (response.authResponse) {{ {0} }} else {{ {1} }}}}, {{ scope: '{2}' }});}}", this.Page.ClientScript.GetPostBackEventReference(this.Page, "FacebookLogin", false), this.Page.ClientScript.GetPostBackEventReference(this.Page, "FacebookLogout", false), "publish_stream,email");
				
               	Page.ClientScript.RegisterStartupScript(typeof(string), "facebook_login", facebookLogin, true);
           	}//end of if
 
           	if (!Page.ClientScript.IsStartupScriptRegistered("facebook_logout"))
           	{
               	string facebookLogout = String.Format("function fblogout() {{ FB.logout(function(response) {{ {0} }}); }}", this.Page.ClientScript.GetPostBackEventReference(this.Page, "FacebookLogout", false));
               	Page.ClientScript.RegisterStartupScript(typeof(string), "facebook_logout",
                  facebookLogout, true);
           	}//end of if
			
			FacebookApp facebookApp = new FacebookApp();//holds an object of the FB
				
			//checks if the user is connected to the session
			if (facebookApp.Session != null && facebookApp.AccessToken != null)
			{
				var facebookUser = facebookApp.Api("me") as JsonObject;//holds the object of the user
	
				//checks if the the user has submited a condolence		
				if(panCondoloncesThankYou.Visible == false)
					//displays the Condolace section
					panLeaveCondolence.Style.Add("display", "block");
				else
					//closes the Leave Condolence section
					panLeaveCondolence.Style.Add("display", "none");
					
				//removes the socail and user text boxes as the user is now already sign in
				//and turns on the label of the user and displays the logout button
				panCondolenceSocialOption.Visible = false;
				panConEnterNameEmail.Visible = false;
				panConNameEmail.Visible = true;
				panLogOutFB.Visible = true;
				
				//checks if there is a user name 
				if (facebookUser.ContainsKey("username") && facebookUser["username"] != null)
					lblConnectedUser.Text = facebookUser["username"].ToString();

				//checks if there is a name from FB	
				if (facebookUser.ContainsKey("name") && facebookUser["name"] != null)		
					//displays the name from FB
					lblConnectedName.Text = facebookUser["name"].ToString();
				
				//checks if there is a email from FB
				if (facebookUser.ContainsKey("email") && facebookUser["email"] != null)
					//displays the email from FB
					lblConnectedEmail.Text = facebookUser["email"].ToString();
					
				//sets the which social network the user is usiing
				hfObituaryCondolenceSocialNetwork.Value = "1";
			}//end of if
			else
			{
				//adds the Social Options and allow the user to enter their own email
				//and removes the FB Logout and email
				panCondolenceSocialOption.Visible = true;
				panConEnterNameEmail.Visible = true;
				panConNameEmail.Visible = false;
				panLogOutFB.Visible = false;
		
				//resets all of the social fields
				lblConnectedUser.Text = "";
				lblConnectedName.Text = "";
				lblConnectedEmail.Text = "";
				hfObituaryCondolenceSocialNetwork.Value = "0";
			}//end of else
			
			//checks if the user is logged into twitter
			if (Request["oauth_token"] != null)
			{
				Session["TwitterRequestToken"] = Request["oauth_token"].ToString();
                Session["TwitterPin"] = Request["oauth_verifier"].ToString();
 
                var tokens = OAuthUtility.GetAccessToken(
                    ConfigurationManager.AppSettings["consumerKey"],
                    ConfigurationManager.AppSettings["consumerSecret"],
                    Session["TwitterRequestToken"].ToString(),
                    Session["TwitterPin"].ToString());
 
                OAuthTokens oatAccess = new OAuthTokens()
					{
						AccessToken = tokens.Token,
						AccessTokenSecret = tokens.TokenSecret,
						ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
						ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
					};
 
 				TwitterResponse<TwitterUser> twitterResponse = TwitterAccount.VerifyCredentials(oatAccess);//holds the response that has come from twitter with if this is a good token
 
                if (twitterResponse.Result == RequestResult.Success)
				{
                   //We now have the credentials, so make a call to the Twitter API.
					HtmlMeta hmTwitter = new HtmlMeta();//holds the meta takes that will go into the header
			    	HtmlHead head = (HtmlHead)Page.Header;//holds the reference of the Header
										
					//removes the socail and user text boxes as the user is now already sign in
					//and turns on the label of the user
					panCondolenceSocialOption.Visible = false;
					panConEnterNameEmail.Visible = false;
					panConNameEmail.Visible = true;
					
					//sets the which social network the user is usiing
					hfObituaryCondolenceSocialNetwork.Value = "2";
													
					//sets the username and actully name
					lblConnectedUser.Text = twitterResponse.ResponseObject.ScreenName;
					lblConnectedName.Text = twitterResponse.ResponseObject.Name;

					//define an HTML meta twitter:creator in the header 
					hmTwitter.Name = "twitter:creator";
					hmTwitter.Content = lblConnectedUser.Text;
					hmTwitter.Controls.Add(hmTwitter);
					
					//because twitter does not allow access to the email address this should not be display
					panConnectedEmail.Visible = false;
				}//end of if
			}//end of if
				

                DataTable dtObituaryDetails = null;
                if (panSidebarLinks.Visible)
                    dtObituaryDetails = DAL.getRow("", "WHERE  = '" + General.ObituaryStatus.Published.ToString() + "' AND  = " + hfObituaryID.Value);//holds the Obituary details
                else
                    dtObituaryDetails = DAL.getRow("", "WHERE  = " + hfObituaryID.Value);//holds the Obituary details
								
				//checks if there is any details for this obituary
				if (dtObituaryDetails != null && dtObituaryDetails.Rows.Count > 0)
				{
					int intIndexServiceID = 0;//holds the unquie id of the row
					string strLastFHID = "";//holds what is the last FHID
					string strShareDescription = "";//holds the description that will share to the world
					DataTable dtImage = DAL.getRow("","Where  = " + hfObituaryID.Value + " Order by ");//holds the Images for this Obituary
					DataTable dtObitService = DAL.getRow("", "WHERE  = " + hfObituaryID.Value + " Order by , , ");//gets all services for this obituary
					DataTable dtObitFlowers = DAL.getRow("", "WHERE  = " + hfObituaryID.Value + " AND  = 1 Order by , ");//holds the Flower Recipient
					DataTable dtObitCards = DAL.queryDbTable("SELECT , ,  + ' ' +   FROM  WHERE  = " + hfObituaryID.Value + " AND  = 1");

					//checks if there is any images to display
					if(dtImage.Rows.Count > 0)
						//sets an iframe to display the image slider as the image slider uses a advance jquery
						//the DNN does not run
						litImageSlider.Text = "<iframe id='iframeImageSlider' src='/ImageSlider.aspx?=" + hfObituaryID.Value + "' scrolling='no'></iframe>";

                    //checks if this is PrePla or Memorial n if so then change the text for Leave Condolence
                    if (dtObituaryDetails.Rows[0][""].ToString() == ((int)General.ObituaryType.PrePlan).ToString() || dtObituaryDetails.Rows[0][""].ToString() == ((int)General.ObituaryType.Memorial).ToString())
                    {
                        hlLeaveCondolence.Text = "Leave a Condolence or Message";
                        lblNoOfCondolences.Text = " Condolences or Messages";
						panLeaveCondolenceTitleLeft.CssClass += " divLeaveCondolenceMmemoralTitleLeft";
                    }//end of if
					
					//checks if this user is logged in and they have not logged into a soical network
					//get there there details instead of typing it in
					if(Session[""] != null && panConNameEmail.Visible == false)
					{
						DataTable dtUserDetails = DAL.getRow("", "WHERE  = " + Session[""].ToString());//holds the this user detail that is logged in
						
						//sets the users name and email to tell the user that this is what is going to be displayed
						lblConnectedName.Text = dtUserDetails.Rows[0][""].ToString() + " " + dtUserDetails.Rows[0][""].ToString();
						lblConnectedEmail.Text = dtUserDetails.Rows[0][""].ToString();
						lblReminderEmail.Text = dtUserDetails.Rows[0][""].ToString();
																		
						//displays the user name and email to tell the user who the are login in as
						panConNameEmail.Visible = true;
						//lblReminderEmail.Visible = true;
						panConEnterNameEmail.Visible = false;
						panCondolenceSocialOption.Visible = false;                        
					}//end of if

					//sets the condolences, the number of them for this Obituary and paging
			        BindDesignsPanel();
					
					//sets the on Click for the link Leave Condolence to turn it off and on
					hlLeaveCondolence.Attributes.Add("onClick", "javascript:toggleLayer('" + panLeaveCondolence.ClientID + "', '', '');");
                    hlSectionCondolence.Attributes.Add("onClick", "javascript:toggleLayer('" + panLeaveCondolence.ClientID + "', '', '');" + panLeaveCondolence.ClientID + ".scrollIntoView(true);");
					
					//sets the basis settings
					lblName.Text = dtObituaryDetails.Rows[0][""].ToString() + ", "  + dtObituaryDetails.Rows[0][""].ToString() + " " + dtObituaryDetails.Rows[0][""].ToString();
					lblPrintName.Text = dtObituaryDetails.Rows[0][""].ToString() + ", "  + dtObituaryDetails.Rows[0][""].ToString() + " " + dtObituaryDetails.Rows[0][""].ToString();
					
					//sets the sidebar name of the user
                    lblShareForName.Text = dtObituaryDetails.Rows[0][""].ToString() + " " + dtObituaryDetails.Rows[0][""].ToString();
					lblReminderForName.Text = dtObituaryDetails.Rows[0][""].ToString() + " " + dtObituaryDetails.Rows[0][""].ToString();
					lblReminderForName2.Text = dtObituaryDetails.Rows[0][""].ToString() + " " + dtObituaryDetails.Rows[0][""].ToString();
					
					//sets the title of the page
					Page.Title = "The Obituaries - Details for " + dtObituaryDetails.Rows[0][""].ToString() + " " + dtObituaryDetails.Rows[0][""].ToString();
					
					//sets the flower FH sidebar
					panFlowersFH.Visible = Convert.ToBoolean(dtObituaryDetails.Rows[0][""].ToString());
					
					//checks if there is a FHID
                    if (Convert.ToInt32(dtObituaryDetails.Rows[0][""].ToString()) > 0)
                    {
                        //sets the FHID for this flower request
                        hlFlowerFH.NavigateUrl += dtObituaryDetails.Rows[0][""].ToString() + "&oid=" + hfObituaryID.Value;
                        chkFuneralHome.Text = " All announcements from <strong>" + DAL.queryDbScalar("SELECT  FROM  WHERE  = '" + dtObituaryDetails.Rows[0][""].ToString() + "'") + "</strong>";
                    }//end of if
                    else
                        //removes the Flowers FH is there is no FHID to use
                        panFlowersFH.Visible = chkFuneralHome.Visible = false;
					
					//sets the Anotehr Address URL for flowers and cards	
					hlSendCardsAnotherAddress.NavigateUrl = "/Obituaries/sympathycards.aspx?ObituariesID=" + hfObituaryID.Value;
					hlSendFlowersAnotherAddress.NavigateUrl = "/Obituaries/flower.aspx?person=2&FHPID=0&oid=" + hfObituaryID.Value;
					
					//checks if there is any flowsers 
					if(dtObitFlowers.Rows.Count > 0)
					{
						//sets the flowers recipient in the sidebar
						dlFlowerRecipient.DataSource = dtObitFlowers;
						dlFlowerRecipient.DataBind();
					}//end of if
					else
						//removes the 'or' flowers from view
                        panFlowersOr.Visible = false;
											
					//checks if there is any cards 
					if (dtObitCards != null && dtObitCards.Rows.Count > 0)
					{
						//sets the card recipient in the sidebar
						rpCardReceiver.DataSource = dtObitCards;
						rpCardReceiver.DataBind();
					}//end of if
					else
						//removes the 'or' card from view
						panCardOr.Visible = false;
						
					//resets lblBirthDateAndPassingDate
					lblBirthDateAndPassingDate.Text = "";
		
					//checks if there is a birth date
					if(!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString()))
						lblBirthDateAndPassingDate.Text += Convert.ToDateTime(dtObituaryDetails.Rows[0][""].ToString()).ToString("MMMM dd, yyyy");
						
					//checks that there must be both a birth\death date for - to display
					if(!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString()) && !string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString())) 
						lblBirthDateAndPassingDate.Text += " - ";
						
					//checks if there is a death date or a is this a pre-plan obituarie
					if(!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString()))
						//sets the death year
						lblBirthDateAndPassingDate.Text += Convert.ToDateTime(dtObituaryDetails.Rows[0][""].ToString()).ToString("MMMM dd, yyyy");
						
					//checks if there is any text in the lblBirthDateAndPassingDate
					//in order to add it to the print version
					if(!string.IsNullOrEmpty(lblBirthDateAndPassingDate.Text))
						lblPrintBirthDateAndPassingDate.Text = lblBirthDateAndPassingDate.Text;
						
					//sets the twitter sharing for this obituery
					hlShareTwiiter.NavigateUrl = "https://twitter.com/share?url=" + Server.UrlEncode("http://theobituaries.ca/Obituaries.aspx?ObituariesID=" + hfObituaryID.Value) + "&text=Obituary for " + lblName.Text;
					
					//sets the linkin sharing for this obituery
					ltlLinkin.Text = "<script type='IN/Share' data-url='" + Server.UrlEncode("http://theobituaries.ca/Obituaries.aspx?ObituariesID=" + hfObituaryID.Value) + "'></script>";
					
					//checks if strShareDescription has any content
					if(string.IsNullOrEmpty(strShareDescription))
						//uses a default text as to not have DNN text display on the user's condolences
						strShareDescription = "A condolence for " + dtObituaryDetails.Rows[0][""].ToString() + " "  + dtObituaryDetails.Rows[0][""].ToString();
					
					//sets the Facebook sharing for this obituery
					litFB.Text = "<iframe src='http://www.facebook.com/plugins/like.php?href=http%3A%2F%2F" + Request.Url.Host + "%2FObituaries.aspx%3FObituariesID%3D" + hfObituaryID.Value + "&amp;send=false&amp;layout=button_count&amp;width=60&amp;show_faces=false&amp;font&amp;colorscheme=light&amp;action=like&amp;height=21&amp;appId=574005609290762' scrolling='no' frameborder='0' style='overflow:hidden;height:21px;' allowTransparency='true'></iframe>";
								  
					HtmlMeta hmFB = new HtmlMeta();//holds the meta takes that will go into the header
				    HtmlHead head = (HtmlHead)Page.Header;//holds the reference of the Header
					
                    lnkSendCardToFuneralHome.Visible = false;

                    if (dtObituaryDetails.Rows[0][""].ToString() == "True" && !string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString()) && dtObituaryDetails.Rows[0][""].ToString() != "0")
                    {
                        lnkSendCardToFuneralHome.NavigateUrl = "/Obituaries/sympathycards.aspx?ObituariesID=" + hfObituaryID.Value + "&FuneralHomeID=" + dtObituaryDetails.Rows[0][""].ToString();
                        lnkSendCardToFuneralHome.Visible = true;
                    }//end of if

                    if (!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString()))
                        hfObituaryCreatorEmail.Value = DAL.queryDbScalar("SELECT  FROM  WHERE  = '" + dtObituaryDetails.Rows[0][""].ToString() + "'");
						
					//resets litObituaryServices
					litObituaryServices.Text = "";
							
					//checks if there is any sevices
					if(dtObitService.Rows.Count > 0)
					{
						//goes around adding the services of the Obituary
						foreach (DataRow drObitService in dtObitService.Rows)
						{
							//checks if there is a FHID or or  is the different
							//this is different from the next one as this will skip the whole row
							if(Convert.ToInt32(drObitService[""].ToString()) != 0 || Convert.ToInt32(drObitService[""].ToString()) == 0 && strLastFHID != drObitService[""].ToString())
							{ 
								//checks if the last FHID or  is the different
								if(strLastFHID != drObitService[""].ToString() || Convert.ToInt32(drObitService[""].ToString()) == 0 && strLastFHID != drObitService[""].ToString())
								{
									DataTable dtFHDetails = DAL.getRow("", "WHERE  = " + Convert.ToInt32(drObitService[""].ToString()));//holds the Funeral Home details
						
									//checks if this is a the first service
									//as there is not last service yet
									if(!string.IsNullOrEmpty(strLastFHID))			
										//create a ends the last serivce 
										litObituaryServices.Text += "</div>";
									
									//starts a new one
									litObituaryServices.Text += "<div class='customContainer divObiturayDetailsServiceContainer'>" + 
										"<div class='customLeft divObiturayDetailsServiceLeft'>";
										
											//checks if this FH is in the database and if it is a partner
											if (dtFHDetails != null && dtFHDetails.Rows.Count > 0)
											{
												string strSearchItemMap = "";//holds the map of the search itme
												
												//checks if there is a address to search for the google map
												if(!string.IsNullOrEmpty(dtFHDetails.Rows[0][""].ToString()) && !string.IsNullOrEmpty(dtFHDetails.Rows[0][""].ToString()) && !string.IsNullOrEmpty(dtFHDetails.Rows[0][""].ToString()))
												{
													//checks if there is a already a location that the user wants to use
													if(dtFHDetails.Rows[0][""] == null || string.IsNullOrEmpty(dtFHDetails.Rows[0][""].ToString().Trim()))					
														//adds the funcation that will activate the google map hidden
														strSearchItemMap = "getLocationHiddenGeo(&quot;" + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "," + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "," + dtFHDetails.Rows[0][""] + "&quot;,&quot;" + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "&quot;,43.64100156269233,-79.38599562435303);";
													else
														//adds funcation that will activate the google map hidden what the user want to display
														strSearchItemMap = "getLocationHiddenGeo(&quot;" + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "," + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "," + dtFHDetails.Rows[0][""] + "&quot;,&quot;" + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "&quot;," + dtFHDetails.Rows[0][""] + ");";
												}//end of if
																								
												//loads the ability to display the map
                                                if (panSidebarLinks.Visible)
                                                    litObituaryServices.Text += "<a href='javascript:void(0);' onClick='" + strSearchItemMap + "toggleLayer(&quot;divHiddenHeaderMap&quot;,&quot;divGrayBG&quot;,&quot;&quot;);getDocID(&quot;lblHiddenMapName&quot;).innerHTML=&quot;Location for " + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + " - " + dtFHDetails.Rows[0][""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + ", " + dtFHDetails.Rows[0][""].ToString() + "&quot;;'><img alt='Map' src='/Portals/_default/skins/Obit/Images/obits-map.jpg' /></a>";
                                                else
                                                    litObituaryServices.Text += "<img alt='Map' src='/Portals/_default/skins/Obit/Images/obits-map.jpg' />";
											}//end of if
											//displays a custom FH that the user has create
											else
												litObituaryServices.Text += "<a href='javascript:void(0);' onClick='getLocationHiddenGeo(&quot;" + drObitService[""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "," + drObitService[""].ToString().Replace("'", "&lsquo;").Replace("\"", "&quot;") + "," + drObitService[""] + "&quot;,&quot;" + drObitService[""].ToString().Replace("'","&lsquo;").Replace("\"","&quot;") + "&quot;,43.64100156269233,-79.38599562435303);toggleLayer(&quot;divHiddenHeaderMap&quot;,&quot;divGrayBG&quot;,&quot;&quot;);getDocID(&quot;lblHiddenMapName&quot;).innerHTML=&quot;Location for " + drObitService[""].ToString().Replace("'","&lsquo;").Replace("\"","&quot;") + " - " + drObitService[""].ToString().Replace("'","&lsquo;").Replace("\"","&quot;") + ", " + drObitService[""].ToString() + "&quot;;'><img alt='Map' src='/Portals/_default/skins/Obit/Images/obits-map.jpg' /></a>";
												
										litObituaryServices.Text += "</div>" + 
										"<div class='customRight divObiturayDetailsServiceRight'>";
											
												//checks if this FH is in the database and if it is a partner
												if (dtFHDetails != null && dtFHDetails.Rows.Count > 0)
												{
													//checks if this is a Publish FH or non
                                                    if (dtFHDetails.Rows[0][""].ToString() == "1" && panSidebarLinks.Visible)
														litObituaryServices.Text += "<a href='/FuneralHome.aspx?FuneralHomeId=" + dtFHDetails.Rows[0][""].ToString() + "'>" + 
															dtFHDetails.Rows[0][""].ToString() + 
														"</a>";
													else
														litObituaryServices.Text += "<label class='lblObituaryFHServiceName'>" +
															dtFHDetails.Rows[0][""].ToString() + 
														"</label>";
													
													litObituaryServices.Text += "<div class='divObiturayServiceLocation'>" +
														dtFHDetails.Rows[0][""].ToString() + ", " + dtFHDetails.Rows[0][""].ToString() + ", " + dtFHDetails.Rows[0][""].ToString() + ", " + dtFHDetails.Rows[0][""].ToString() + 
													"</div>";
												}//end of if
												//displays a custom FH that the user has create
												else
												{
													//checks if there is a custom name for this custom FH
													if(!string.IsNullOrEmpty(drObitService[""].ToString()))
														litObituaryServices.Text += "<label class='lblObituaryFHServiceName'>" +
															drObitService[""].ToString() + 
														"</label>" +
														"<div class='divObiturayServiceLocation'>";
													else
														//beacuse divObiturayServiceLocation has a padding this will move
														//make the address not appeaeal with the map icon this wll fix it
														litObituaryServices.Text += "<div class='divObiturayServiceNoCustomLocationName'>";
														
													litObituaryServices.Text += drObitService[""].ToString() + ", " + drObitService[""].ToString() + ", " + drObitService[""].ToString() + ", " + drObitService[""].ToString() + 
													"</div>";
												}//end of else
												 
											//sets the link to open the location and start the service detail div
											litObituaryServices.Text += "<a href='#service-location-" + intIndexServiceID + "' class='toggle-location scroll-show'>Open Location</a>" + 
										"</div>" + 
										"<div class='customFooter divObiturayDetailsServiceFooter'></div>";
									
									//checks if this row is a FH or a custom address
									//and then updates the strLastFHID
									if(Convert.ToInt32(drObitService[""].ToString()) == 0)
										strLastFHID = drObitService[""].ToString();
									else
										strLastFHID = drObitService[""].ToString();
								}//end of if
								
								//displays the details of the service
								litObituaryServices.Text += "<div class='divObiturayServiceDateTime'>" + 
									"<div class='divObiturayServiceDate'>" + 
										"<label>" + Convert.ToDateTime(drObitService[""].ToString()).ToString("dddd, MMMM d, yyyy") + "</label>" + 
									"</div>" + 
									"<div class='divObiturayServiceTime'>" + 
										"<label><strong>"; 
				
									//checks which Obituary Service Type is this and displays it
									switch(Convert.ToInt32(drObitService[""].ToString()))
									{
										case 0:
											litObituaryServices.Text += "Visitation";
										break;
										case 1:
											litObituaryServices.Text += "Funeral Service";
										break;
										case 2:
											litObituaryServices.Text += "Graveside Service";
										break;
										case 3:
											litObituaryServices.Text += "Memorial Service";
										break;
										case 4:
											litObituaryServices.Text += "Non Commemorative Funeral";
										break;
										case 6:
											litObituaryServices.Text += "Celebration of Life";
										break;
										default:
											litObituaryServices.Text += drObitService[""].ToString();
										break;										
									}//end of switch
										
									//displays the service start time
									litObituaryServices.Text += " - " + Convert.ToDateTime(drObitService[""].ToString()).ToString("h:mm tt");
									
									//checks if there is a service end time
									if(!string.IsNullOrEmpty(drObitService[""].ToString()) && drObitService[""].ToString() != "00:00:00")
										//displays the service end time
										litObituaryServices.Text += " - " + Convert.ToDateTime(drObitService[""].ToString()).ToString("h:mm tt");
									
								//end the details of the service
								litObituaryServices.Text += "</strong></label>" + 
									"</div>" + 
								"</div>";
								
								intIndexServiceID++;
							}//end of if
						}//end of foreach
						
						//closes the last service
						litObituaryServices.Text += "</div>";
					}//end of if
					else
						//remvoes the service section from display	
						panObituaryServices.Visible = false;
				}//end of if
			//}//end of if				
		}//end of try
        catch (Exception ex)
        {
            lblMainError.Text = ex.Message;// + " " + ex.StackTrace;
            lblMainError.Visible = true;
        }//end of catch
    }//end of Page_PreRender()
示例#20
0
    }//end of dlCondolence_ItemDataBound()

	protected void cmdSaveCondolonces_Click(object sender, EventArgs e)
    {
		try
		{
            lblConError.Text = string.Empty;
            lblConError.Visible = false;
			
			//checks if the page is valid if so then prcess the event
			if (Page.IsValid)
			{			
				//checks if the Captcha is validated
                if (Captcha.Validate(txtCaptchaCode.Text.Trim().ToUpper()))
                {
                    string strUserEmail = lblConnectedEmail.Text;//holds the users email address
                    string strAddSubject = "condolences";//holds the and the condolences as they could be two ways of sending it public or private
					DataTable dtObitUsers = DAL.getRow("", "WHERE  = " + hfObituaryID.Value);//gets all users that are either creators or co-owners

                    //checks if there is a user email addres if the user has not loged in 
                    //and needs to type it out
                    if (string.IsNullOrEmpty(strUserEmail))
                        strUserEmail = txtConEMail.Text;

                    //checks if the user is log into the site
                    if (Session[""] != null)
                        //adds a new condolence with the user who is logged into the site
                        DAL.addUpdateObituaryCondolence(0, Convert.ToInt32(hfObituaryID.Value), Convert.ToInt32(Session[""].ToString()), 0, "", "", txtConMessage.Text, "", chkPrivateCon.Checked);
                    else
                    {
                        //checks if the user is logged into the site or soical site
                        if (panConNameEmail.Visible == false)
                            //adds a new condolence with the user who is not logged in
                            DAL.addUpdateObituaryCondolence(0, Convert.ToInt32(hfObituaryID.Value), 0, 0, txtConName.Text, strUserEmail, txtConMessage.Text, "", chkPrivateCon.Checked);
                        else
						{
							FacebookApp facebookApp = new FacebookApp();//holds an object of the FB
							
                            //adds a new condolence with the user who is logged into soical site
                            //for intObituaryCondolenceSocialNetwork
							/*
								1 = FB
								2 = Twitter
								3 = Linkin
								4 = Google
							*/
                            DAL.addUpdateObituaryCondolence(0, Convert.ToInt32(hfObituaryID.Value), 0, Convert.ToInt32(hfObituaryCondolenceSocialNetwork.Value), lblConnectedName.Text, strUserEmail, txtConMessage.Text, lblConnectedUser.Text, chkPrivateCon.Checked);
							
							//checks if the user is connected to FB
							if (facebookApp.Session != null && facebookApp.AccessToken != null && chkPrivateCon.Checked == false)
							{
								var fb = new FacebookClient(facebookApp.AccessToken);
								
								//publish the user's public condolence to their FB wall
								dynamic result = fb.Post("me/feed", new { 
								    message = txtConMessage.Text,
									link = "http://" + Request.Url.Host + "/ObituaryDetailShare.aspx?id=" + hfObituaryID.Value
								});
							}//end of if
							//tweets to the user
							else if (Request["oauth_token"] != null && chkPrivateCon.Checked == false)
							{
								var tokens = OAuthUtility.GetAccessToken(
                    				ConfigurationManager.AppSettings[""],
                    				ConfigurationManager.AppSettings[""],
            				        Session["TwitterRequestToken"].ToString(),
			                	    Session["TwitterPin"].ToString());
				 
								OAuthTokens oatAccess = new OAuthTokens()
									{
										AccessToken = tokens.Token,
										AccessTokenSecret = tokens.TokenSecret,
										ConsumerKey = ConfigurationManager.AppSettings[""],
										ConsumerSecret = ConfigurationManager.AppSettings[""]
									};
								
								TwitterResponse<TwitterStatus> tsResponse = TwitterStatus.Update(oatAccess, txtConMessage.Text);
							}//end of else if
						}//end of else
                    }//end of else

                    //checks if this is a Private Condolence for the admin send out
                    if (chkPrivateCon.Checked == true)
                        //changes the subject for the send out to the admin
                        strAddSubject = "a Private Condolence";

					//checks if there is a email 
    	            if (!string.IsNullOrEmpty(hfObituaryCreatorEmail.Value))
		            	//sends out email to creators
						sendCondolencesEmail(hfObituaryCreatorEmail.Value, "You have received " + strAddSubject, "send-condolence-nophoto", chkPrivateCon.Checked, true);
						
					//goes around send it to all user who are any coowners
					foreach (DataRow drObitUsers in dtObitUsers.Rows)
					{
						//checks if there is a email 
    		            if (!string.IsNullOrEmpty(drObitUsers[""].ToString()))
			            	//sends out email to any coowners
							sendCondolencesEmail(drObitUsers[""].ToString(), "You have received " + strAddSubject, "send-condolence-nophoto", chkPrivateCon.Checked, true);
					}//end of for loop
					
                    //checks if this is a Private Condolence for the user send out
                    if (chkPrivateCon.Checked == true)
					{
                        //changes the subject for private condolence
                        strAddSubject = "PRIVATE Condolences";
						
						//changes the thank you message for private condolence
						litThankYou.Text = "Your private condolence will be shared with the family. A copy has also been sent to your email address.";
					}//end of if

					//checks if there is a email to send to as if the user uses twitter it will be not avialable
					if (!string.IsNullOrEmpty(strUserEmail))
                    	//sends out email to admin to send to user
                    	sendCondolencesEmail(strUserEmail, "Your " + strAddSubject + " have been sent", "send-condolence", chkPrivateCon.Checked);

                    //resets the condolences, the number of them for this Obituary and paging
			      					
					//gets the number of condolences
					InitializePagingVars(true);
			
					//resets the condolences
					Bind(-1);
			
					//resets the paging contorls
					BindPagingControls();
					
                    //turns on the thank you message
                    //panCondoloncesFourm.Visible = false;
                    panCondoloncesThankYou.Visible = true;
                    chkPrivateCon.Checked = false;
                    txtCaptchaCode.Text = string.Empty;
                    txtConName.Text = "Your Name *";
                    txtConEMail.Text = "Your Email Address *";
                    txtConMessage.Text = "Your Message *";
                }//end of if
                else
                {
                    lblConError.Text = "Invalid captcha!!";
                    lblConError.Visible = true;
                    panCondoloncesThankYou.Visible = false;
                }//end of else
			}//end of if
		}//end of try
        catch (Exception ex)
        {
            lblConError.Text = ex.Message;
            lblConError.Visible = true;
            panCondoloncesThankYou.Visible = false;
        }//end of catch
    }//end of cmdSaveCondolonces_Click()
示例#21
0
        /*
        private fbuser Setfbid()
        {
            string oauth = "";
            oauth = HttpContext.Current.Request.QueryString["code"].ToString();
            //oauth = oauth.Substring(0, oauth.IndexOf("|"));
            fbuser fbuser = new fbuser();
            //oauth = oauth.Substring(0, oauth.IndexOf("|"));

            WebClient wc = new WebClient();
            wc.Encoding = System.Text.Encoding.UTF8; //This is if you have non english characters
            //string result = wc.DownloadString("https://graph.facebook.com/oauth/access_token?response_type=token&client_secret=" + ConfigurationManager.AppSettings.Get("Secret").ToString() + "&client_id=" + ConfigurationManager.AppSettings.Get("fbAppID").ToString() + "&code=" + oauth);
            string strsend = "https://graph.facebook.com/oauth/access_token?client_id=" + ConfigurationManager.AppSettings.Get("fbAppID").ToString() + "&redirect_uri=" + thereturnpage + "&client_secret=" + ConfigurationManager.AppSettings.Get("Secret").ToString() + "&code=" + oauth;
            var url = "https://graph.facebook.com/oauth/authorize?client_id=" + ConfigurationSettings.AppSettings.Get("fbAppID").ToString() + "&redirect_uri=" + ConfigurationSettings.AppSettings.Get("App_URL").ToString() + "default.aspx&scope=" + strrequiredAppPermissions;
            string result = wc.DownloadString(url);
            string accesstoken = result.Replace("access_token=", "");
            int endofaccesstoken = accesstoken.IndexOf("&expire");
            accesstoken = accesstoken.Substring(0, endofaccesstoken);

            //Get user id
            wc.Encoding = System.Text.Encoding.UTF8; //This is if you have non english characters
            string result2 = wc.DownloadString("https://graph.facebook.com/me?access_token=" + accesstoken);

            try
            {
                JObject o = JObject.Parse(result2);
                string fbid = (string)o["id"];
                string email = "";
                string firstname = "";
                string lastname = "";
                if (o["email"] != null)
                {
                    email = (string)o["email"];
                }
                if (o["first_name"] != null)
                {
                    firstname = (string)o["first_name"];
                }
                if (o["last_name"] != null)
                {
                    lastname = (string)o["last_name"];
                }

                bool isnewuser = false;

                BlueIkons_DB.SPs.UpdateFBUser(Convert.ToInt64(fbid), firstname, lastname, email, accesstoken).Execute();
                fbuser.UID = Convert.ToInt64(fbid);
                fbuser.Email = email;
                fbuser.Firstname = firstname;
                fbuser.Lastname = lastname;
                fbuser.AccessToken = accesstoken;

            }
            catch
            {
            }

            return fbuser;
        }*/
        protected fbuser PopulatefbuserGraph()
        {
            CanvasAuthorizer authorizer;
            fbuser localfbuser = new fbuser();
            FacebookApp fbApp = new FacebookApp();

            authorizer = new CanvasAuthorizer();
            authorizer.Permissions = requiredAppPermissions;
            //if ((authorizer.Session != null) || ((HttpContext.Current.Request.QueryString["code"] != null) && (HttpContext.Current.Request.QueryString["code"] != "")))
            if (authorizer.Session != null)
            {
                //ShowFacebookContent();
                JsonObject myInfo = (JsonObject)fbApp.Get("me");

                localfbuser.UID = Convert.ToInt64(myInfo["id"].ToString());
                localfbuser.AccessToken = fbApp.AccessToken;
                localfbuser.SessionKey = fbApp.Session.Signature;
                localfbuser.Firstname = myInfo["first_name"].ToString();
                localfbuser.Lastname = myInfo["last_name"].ToString();
                localfbuser.Fullname = localfbuser.Firstname + " " + localfbuser.Lastname;
                localfbuser.Email = getfbappemail(myInfo);

                //HttpContext.Current.Session["fbuser"] = fbuser;
                BlueIkons_DB.SPs.UpdateFBUser(localfbuser.UID, localfbuser.Firstname, localfbuser.Lastname, localfbuser.Email, localfbuser.AccessToken).Execute();

                if ((HttpContext.Current.Session["invite"] != null) || (HttpContext.Current.Request.QueryString["invite"] != null))
                {
                    updateinvite(localfbuser);
                }
                //Eventomatic_DB.SPs.UpdateResource(fbuser.UID, fbuser.Firstname, fbuser.Lastname, "", HttpContext.Current.Request.UserHostAddress, GetCurrentPageName(), 0, 0, fbuser.SessionKey, fbuser.AccessToken, 0).Execute();
            }
            else if ((HttpContext.Current.Request.QueryString["fbid"] != null) && (HttpContext.Current.Request.QueryString["fbid"] != ""))
            {
                localfbuser = Getfbuser(Convert.ToInt64(HttpContext.Current.Request.QueryString["fbid"].ToString()));
                if (HttpContext.Current.Request.QueryString["invite"] != null)
                {
                    updateinvite(localfbuser);
                }
                //HttpContext.Current.Session["fbuser"] = fbuser;
            }
            else
            {
                if (HttpContext.Current.Request.QueryString["invite"] != null)
                {
                    //remember invitekey
                    HttpContext.Current.Session["invite"] = HttpContext.Current.Request.QueryString["invite"].ToString();
                }
                var pageName = Path.GetFileName(HttpContext.Current.Request.PhysicalPath);
                var urlSB = new StringBuilder();
                urlSB.Append("https://graph.facebook.com/oauth/authorize?client_id=");
                urlSB.Append(ConfigurationManager.AppSettings["fbAppID"]);
                urlSB.Append("&redirect_uri=");
                urlSB.Append(ConfigurationManager.AppSettings["App_URL"]);
                urlSB.Append(pageName);
                urlSB.Append("&scope=");
                urlSB.Append(strrequiredAppPermissions);
                //var url = authorizer.ge auth.GetLoginUrl(new HttpRequestWrapper(Request));
                Uri newuri = new Uri(urlSB.ToString());
                var content = CanvasUrlBuilder.GetCanvasRedirectHtml(newuri);
                HttpContext.Current.Response.ContentType = "text/html";
                HttpContext.Current.Response.Write(content);
                HttpContext.Current.Response.End();
            }
            return localfbuser;
        }