public ActionResult ConnectFacebook(FacebookConnectionViewModel model) { // Save user settings to db using (UnitOfWork work = new UnitOfWork()) { user currentUser = work.UserRepository.GetUser(WebSecurity.CurrentUserId); work.UserRepository.AddOrUpdateFacebookSettings(currentUser, model.NotificationsEnabled, model.AutomaticSharingEnabled); work.SaveChanges(); } // Redirect to Facebook to ask for permissions string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("Default", new { Controller = "Settings", Action = "ProcessFacebookLogin" }); string scope = string.Empty; // NOTE: No change in scope needed for notifications; apps don't need to ask permission if (model.AutomaticSharingEnabled) { scope += "publish_actions,"; } string appId = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppId); string fbRedirectUrl = string.Format("https://www.facebook.com/dialog/oauth" + "?client_id={0}" + "&redirect_uri={1}" + "&scope={2}", appId, redirectAfterLoginUri, scope); // TODO: state, response_type: https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ Response.Redirect(fbRedirectUrl); // Shouldn't ever get here; if we do, re-show the form return View(model); }
public ActionResult FixQRCodes() { UnitOfWork work = new UnitOfWork(); List<user> users = work.UserRepository.GetAllUsers(); foreach (user user in users) { Utilities.JPPDirectory.CheckAndCreateUserDirectory(user.id, Server); String qrString = Request.Url.GetLeftPart(UriPartial.Authority) + "/Players/" + user.id; //Create the file path and save the image String qrfilePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.UserQRCode, user.id); String qrfileMinusPath = qrfilePath.Replace("~/Content/Images/Users/" + user.id.ToString() + "/UserQRCodes/", ""); //"/Users/" + userID.ToString() + "/ProfilePictures/" + fileName + ".png"; if (JPPImage.SavePlayerQRCodes(qrfilePath, qrfileMinusPath, qrString)) { user.qr_image = qrfilePath; } } work.SaveChanges(); return RedirectToAction("Index"); }
public ActionResult Add(int earningID, bool earningIsAchievement, String text) { /* TODO: if(WebSecurity.CurrentUserId < 0) { return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized }*/ // Need text for a comment if (String.IsNullOrWhiteSpace(text)) { return new HttpStatusCodeResult(406, "Invalid comment text"); // Invalid text } UnitOfWork work = new UnitOfWork(); // Are comments enabled, and can we access the earning? user earningUser = null; object template = null; if (!CommentsEnabled(earningID, earningIsAchievement, work)) { return new HttpStatusCodeResult(403, "Comments currently disabled"); // Disabled comments } if (!UserCanAccessEarning(earningID, earningIsAchievement, work, out earningUser, out template)) { return new HttpStatusCodeResult(403, "Earning cannot be accessed"); // Invalid earning access } comment c = new comment() { date = DateTime.Now, deleted = false, last_modified_by_id = WebSecurity.CurrentUserId, last_modified_date = null, // Not being modified, just created, so this is null location_id = earningID, location_type = earningIsAchievement ? (int)JPPConstants.CommentLocation.Achievement : (int)JPPConstants.CommentLocation.Quest, text = text, user_id = WebSecurity.CurrentUserId }; // Access is validated, create comment work.EntityContext.comment.Add(c); // Get the current user's display name user u = work.EntityContext.user.Find(WebSecurity.CurrentUserId); //ID, Photo, Name, Text, PosterID, Deleted // Send a notification /*if (earningIsAchievement) { achievement_template a = template as achievement_template; work.SystemRepository.AddNotification( earningUser.id, WebSecurity.CurrentUserId, "[" + u.display_name + "] commented on [" + a.title + "]", u.image, new UrlHelper(Request.RequestContext).Action( "IndividualAchievement", "Achievements", new { id = a.id } ) + "#" + earningUser.id + "-" + earningID, false); } else { quest_template q = template as quest_template; work.SystemRepository.AddNotification( earningUser.id, WebSecurity.CurrentUserId, "[" + u.display_name + "] commented on [" + q.title + "]", u.image, new UrlHelper(Request.RequestContext).Action( "IndividualQuest", "Quests", new { id = q.id } ) + "#" + earningUser.id + "-" + earningID, false); }*/ // Success work.SaveChanges(); EarningComment response = new EarningComment() { Deleted = false, ID = c.id, Text = c.text, PlayerID = u.id, DisplayName = u.display_name, PlayerImage = u.image, CommentDate = c.date, CurrentUserCanEdit = true, CurrentUserCanDelete = true }; return Json(response); }
/// <summary> /// Helper for enabling or disabling comments on earnings /// </summary> /// <param name="earningID">The id of the earning</param> /// <param name="earningIsAchievement">Is this earning an achievement? If not, assume quest.</param> /// <param name="newState">The new state (true = DISABLED, false = ENABLED)</param> /// <returns>True if successful, false otherwise</returns> private Boolean EnableDisable(int earningID, bool earningIsAchievement, bool newState) { UnitOfWork work = new UnitOfWork(); // Get the instance, check the user and alter if (earningIsAchievement) { // Only instance owners or admins achievement_instance instance = work.EntityContext.achievement_instance.Find(earningID); if (instance.user_id != WebSecurity.CurrentUserId && !Roles.IsUserInRole(JPPConstants.Roles.FullAdmin)) return false; // Already enabled? if (instance.comments_disabled == newState) return false; instance.comments_disabled = newState; } else { // Only instance owners or admins quest_instance instance = work.EntityContext.quest_instance.Find(earningID); if (instance.user_id != WebSecurity.CurrentUserId && !Roles.IsUserInRole(JPPConstants.Roles.FullAdmin)) return false; // Already enabled? if (instance.comments_disabled == newState) return false; instance.comments_disabled = newState; } work.SaveChanges(); return true; }
public ActionResult Edit(int commentID, String text) { // Need text for a comment if (String.IsNullOrWhiteSpace(text)) return new HttpStatusCodeResult(406, "Invalid comment text"); // Invalid text UnitOfWork work = new UnitOfWork(); // Grab the comment and check for edit capabilities comment c = work.EntityContext.comment.Find(commentID); if (c.deleted) return new HttpStatusCodeResult(406, "Cannot edit: Comment has been deleted"); // Deleted comment if (c.user_id != WebSecurity.CurrentUserId && !Roles.IsUserInRole(JPPConstants.Roles.FullAdmin)) return new HttpStatusCodeResult(406, "Cannot edit: User has insufficient privileges"); // Not admin or original commenter // Edit the comment LoggerModel logCommentEdit = new LoggerModel() { Action = Logger.CommentBehaviorLogType.CommentEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, ID1 = c.id, IDType1 = Logger.LogIDType.Comment.ToString(), Value1 = c.text, Value2 = text }; Logger.LogSingleEntry(logCommentEdit, work.EntityContext); c.text = text; c.last_modified_by_id = WebSecurity.CurrentUserId; c.last_modified_date = DateTime.Now; work.SaveChanges(); EditCommentResponseModel response = new EditCommentResponseModel() { Text = text }; return Json(response); }
public ActionResult Delete(int commentID) { UnitOfWork work = new UnitOfWork(); // Grab the comment and check for edit capabilities comment c = work.EntityContext.comment.Find(commentID); // Is the current user the instance owner? bool instanceOwner = false; if (c.location_type == (int)JPPConstants.CommentLocation.Achievement) { instanceOwner = (from e in work.EntityContext.achievement_instance where e.id == c.location_id && e.user_id == WebSecurity.CurrentUserId select e).Any(); } else if(c.location_type == (int)JPPConstants.CommentLocation.Quest) { instanceOwner = (from e in work.EntityContext.quest_instance where e.id == c.location_id && e.user_id == WebSecurity.CurrentUserId select e).Any(); } // Instance owner, comment owner or admin? if (!instanceOwner && c.user_id != WebSecurity.CurrentUserId && !Roles.IsUserInRole(JPPConstants.Roles.FullAdmin)) return new HttpStatusCodeResult(406, "Invalid credentials"); // Invalid text LoggerModel logCommentDelete = new LoggerModel() { Action = Logger.CommentBehaviorLogType.CommentDelete.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, ID1 = c.id, IDType1 = Logger.LogIDType.Comment.ToString(), Value1 = c.text }; Logger.LogSingleEntry(logCommentDelete, work.EntityContext); // Mark as deleted c.deleted = true; c.last_modified_by_id = WebSecurity.CurrentUserId; c.last_modified_date = DateTime.Now; work.SaveChanges(); // Get the current user's display name user u = work.EntityContext.user.Find(WebSecurity.CurrentUserId); EarningComment response = new EarningComment() { Deleted = true, ID = c.id, Text = JPPConstants.SiteSettings.DeletedCommentText + u.display_name, PlayerID = c.last_modified_by_id, DisplayName = null, PlayerImage = null, CurrentUserCanEdit = false, CurrentUserCanDelete = false }; return Json(response); // Success }
/// <summary> /// Imports the quest templates from V2 /// </summary> /// <param name="questTemplateTable">File w/ quest template data</param> /// <param name="questAchievementStepTable">Achievement steps data</param> /// <param name="delimiter">Delimiter between data</param> /// <param name="work">The DB access</param> private void ImportQuestTemplates( HttpPostedFileBase questTemplateTable, HttpPostedFileBase questAchievementStepTable, String delimiter, UnitOfWork work) { // Grab the data List<Dictionary<String, String>> questData = GetDataFromFile(questTemplateTable, delimiter); if (questData == null) { ModelState.AddModelError("", "Error with Quest Template table. Check Debug Output"); return; } List<Dictionary<String, String>> stepData = GetDataFromFile(questAchievementStepTable, delimiter); if (stepData == null) { ModelState.AddModelError("", "Error with Quest Step table. Check Debug Output"); return; } // Loop through quests try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (Dictionary<String, String> row in questData) { // Get the creator ImportedUser creator = GetImportedUserByOldID(row["creatorID"]); if (creator == null || creator.NewID == 0) continue; ImportedUser modifiedBy = GetImportedUserByOldID(row["last_modified_by"]); if (modifiedBy == null || modifiedBy.NewID == 0) continue; int oldID = int.Parse(row["questID"]); int threshold = int.Parse(row["quest_threshhold"]); quest_template quest = new quest_template() { created_date = DateTime.Parse(row["date_created"]), creator_id = creator.NewID, description = row["description"], featured = Boolean.Parse(row["is_featured"]), icon = row["icon"], icon_file_name = "", last_modified_by_id = modifiedBy.NewID, last_modified_date = DateTime.Parse(row["date_modified"]), posted_date = DateTime.Parse(row["date_posted"]), retire_date = null, state = (int)JPPConstants.AchievementQuestStates.Inactive, threshold = threshold <= 0 ? (int?)null : threshold, title = row["title"], user_generated = false, keywords = "" }; ImportedEarnable impQuest = new ImportedEarnable() { OldID = oldID, UniqueData = quest.title }; work.EntityContext.quest_template.Add(quest); _questMap.Add(impQuest.OldID, impQuest); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); foreach (ImportedEarnable impQuest in _questMap.Values) { impQuest.NewID = (from q in work.EntityContext.quest_template where q.title == impQuest.UniqueData select q.id).FirstOrDefault(); } // Achievement steps try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (Dictionary<String, String> row in stepData) { // Get the achievement and quest ImportedEarnable quest = GetImportedEarnableByOldID(_questMap, row["questID"]); if (quest == null || quest.NewID == 0) continue; ImportedEarnable achieve = GetImportedEarnableByOldID(_achievementMap, row["achievementID"]); if (achieve == null || achieve.NewID == 0) continue; quest_achievement_step step = new quest_achievement_step() { achievement_id = achieve.NewID, quest_id = quest.NewID }; work.EntityContext.quest_achievement_step.Add(step); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); }
/// <summary> /// Imports the friends table from V2 /// </summary> /// <param name="friendsTable">File w/ friend data</param> /// <param name="delimiter">Delimiter between data</param> /// <param name="work">The DB access</param> private void ImportFriends(HttpPostedFileBase friendsTable, String delimiter, UnitOfWork work) { if (friendsTable == null) return; // Grab the data List<Dictionary<String, String>> data = GetDataFromFile(friendsTable, delimiter); if (data == null) { ModelState.AddModelError("", "Error with Friends table. Check Debug Output"); return; } try { // Speed up work.EntityContext.Configuration.AutoDetectChangesEnabled = false; // Go through each data row foreach (Dictionary<String, String> row in data) { // Do we know about this user? ImportedUser user1 = GetImportedUserByOldID(row["src_userID"]); ImportedUser user2 = GetImportedUserByOldID(row["dst_userID"]); if (user1 == null || user2 == null || user1.NewID == 0 || user2.NewID == 0) continue; // Friendship is bi-directional, so make 2 friend friend1 = new friend() { source_id = user1.NewID, destination_id = user2.NewID, friended_date = DateTime.Parse(row["date_friended"]), request_date = DateTime.Parse(row["date_requested"]) }; friend friend2 = new friend() { source_id = friend1.destination_id, destination_id = friend1.source_id, friended_date = friend1.friended_date, request_date = friend1.request_date }; work.EntityContext.friend.Add(friend1); work.EntityContext.friend.Add(friend2); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); }
/// <summary> /// Imports the profile table from V2 /// </summary> /// <param name="profileTable">The file w/ profile table data</param> /// <param name="delimiter">The delimiter between data</param> /// <param name="work">The DB access</param> private void ImportProfiles(HttpPostedFileBase profileTable, String delimiter, UnitOfWork work) { // Grab the data List<Dictionary<String, String>> data = GetDataFromFile(profileTable, delimiter); if (data == null) { ModelState.AddModelError("", "Error with Profile table. Check Debug Output"); return; } try { // Speed up work.EntityContext.Configuration.AutoDetectChangesEnabled = false; // Rename directories RenameUserDirs(); // Go through each data row and create users foreach (Dictionary<String, String> row in data) { int oldID = -1; if (!int.TryParse(row["userID"], out oldID) || !_userMap.ContainsKey(oldID)) continue; // Get the user, skip if not found ImportedUser impUser = _userMap[oldID]; user u = work.EntityContext.user.Find(impUser.NewID); if (u == null) continue; // Grab data from profile table u.display_name = row["display_name"]; u.six_word_bio = row["six_word_bio"]; u.full_bio = row["full_bio"]; u.image = UpdateImagePathAndGenerateImages(impUser.OldID, impUser.NewID, row["image"]); u.personal_url = row["personalURL"]; Utilities.JPPDirectory.CheckAndCreateUserDirectory(impUser.NewID, Server); String qrString = Request.Url.GetLeftPart(UriPartial.Authority) + "/Players/" + impUser.NewID; //Create the file path and save the image String qrfilePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.UserQRCode, impUser.NewID); String qrfileMinusPath = qrfilePath.Replace("~/Content/Images/Users/" + impUser.NewID.ToString() + "/UserQRCodes/", ""); //"/Users/" + userID.ToString() + "/ProfilePictures/" + fileName + ".png"; if (JPPImage.SavePlayerQRCodes(qrfilePath, qrfileMinusPath, qrString)) { u.qr_image = qrfilePath; } switch (int.Parse(row["privacy"])) { case 1: u.privacy_settings = (int)JPPConstants.PrivacySettings.FriendsOnly; break; // Friends only (old value) case 2: u.privacy_settings = (int)JPPConstants.PrivacySettings.JustPressPlayOnly; break; // JPP Only (old value) case 3: u.privacy_settings = (int)JPPConstants.PrivacySettings.Public; break; // Public (old value) } switch (int.Parse(row["communications"])) { case 1: u.communication_settings = (int)JPPConstants.CommunicationSettings.All; break; // Everything (old value) case 2: u.communication_settings = (int)JPPConstants.CommunicationSettings.Important; break; // Minimal (old value) } // Only update if not currently suspended if (u.status != (int)JPPConstants.UserStatus.Suspended) { switch (int.Parse(row["left_game"])) { case 1: u.status = (int)JPPConstants.UserStatus.Active; break; // Active (old value) case 2: u.status = (int)JPPConstants.UserStatus.Deactivated; break; // Left Game (old value) case 3: u.status = (int)JPPConstants.UserStatus.Deleted; impUser.UserWasDeleted = true; break; // Deleted (old value) } } } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); }
/// <summary> /// Imports the achievements from V2 /// </summary> /// <param name="achieveTemplateTable">File w/ achievement template data</param> /// <param name="achievePointTemplateTable">Achievement point template data (to be rolled into achievement)</param> /// <param name="achieveRequirementsTable">Achievement requirement data</param> /// <param name="achieveCaretakerTable">Achievement caretaker data</param> /// <param name="delimiter">Delimiter between data</param> /// <param name="work">The DB access</param> private void ImportAchievements( HttpPostedFileBase achieveTemplateTable, HttpPostedFileBase achievePointTemplateTable, HttpPostedFileBase achieveRequirementsTable, String delimiter, UnitOfWork work) { // Grab the data List<Dictionary<String, String>> achieveData = GetDataFromFile(achieveTemplateTable, delimiter); if (achieveData == null) { ModelState.AddModelError("", "Error with Achievement Template table. Check Debug Output"); return; } List<Dictionary<String, String>> pointData = GetDataFromFile(achievePointTemplateTable, delimiter); if (pointData == null) { ModelState.AddModelError("", "Error with Achievement Point Template table. Check Debug Output"); return; } List<Dictionary<String, String>> reqData = GetDataFromFile(achieveRequirementsTable, delimiter); if (reqData == null) { ModelState.AddModelError("", "Error with Achievement Requirements table. Check Debug Output"); return; } //List<Dictionary<String, String>> caretakerData = GetDataFromFile(achieveCaretakerTable, delimiter); //if (caretakerData == null) //{ // ModelState.AddModelError("", "Error with Achievement Caretaker table. Check Debug Output"); // return; //} // The templates that need to be added List<achievement_template> templatesToAdd = new List<achievement_template>(); // Go through each data row foreach (Dictionary<String, String> row in achieveData) { // Get related users ImportedUser editedBy = _userMap[int.Parse(row["last_modified_by"])]; ImportedUser creator = _userMap[int.Parse(row["creatorID"])]; if (creator == null) continue; // Must have a creator // Grab other info int oldID = int.Parse(row["achievementID"]); int state = (int)JPPConstants.AchievementQuestStates.Active; bool isRetired = Boolean.Parse(row["is_retired"]); if (isRetired) state = (int)JPPConstants.AchievementQuestStates.Retired; int type = (int)JPPConstants.AchievementTypes.Scan; switch (int.Parse(row["type"])) { // 1 - usersubmission case 1: type = (int)JPPConstants.AchievementTypes.UserSubmission; break; // 2 - scan case 2: type = (int)JPPConstants.AchievementTypes.Scan; break; // 3 - system case 3: type = (int)JPPConstants.AchievementTypes.System; break; // 4 - adminassigned case 4: type = (int)JPPConstants.AchievementTypes.AdminAssigned; break; // 5 - threshold case 5: type = (int)JPPConstants.AchievementTypes.Threshold; break; } int? triggerType = null; if (!String.IsNullOrWhiteSpace(row["system_trigger_type"])) { switch (int.Parse(row["system_trigger_type"])) { // TODO: Finalize this default: break; } } // Set up the template achievement_template template = new achievement_template() { id = oldID, // This will get overridden, but necessary for a look-up later content_type = String.IsNullOrWhiteSpace(row["content_type"]) ? (int?)null : int.Parse(row["content_type"]), created_date = DateTime.Parse(row["date_created"]), creator_id = creator.NewID, description = row["description"], featured = Boolean.Parse(row["is_featured"]), hidden = Boolean.Parse(row["is_hidden"]), icon = row["icon"], icon_file_name = "", is_repeatable = Boolean.Parse(row["is_repeatable"]), last_modified_by_id = editedBy == null ? (int?)null : editedBy.NewID, modified_date = DateTime.Parse(row["date_modified"]), parent_id = String.IsNullOrWhiteSpace(row["parentID"]) ? (int?)null : int.Parse(row["parentID"]), posted_date = DateTime.Now, repeat_delay_days = String.IsNullOrWhiteSpace(row["repeat_delay"]) ? (int?)null : int.Parse(row["repeat_delay"]), retire_date = isRetired ? DateTime.Parse(row["date_retired"]) : (DateTime?)null, state = state, system_trigger_type = triggerType, threshold = String.IsNullOrWhiteSpace(row["threshhold"]) ? (int?)null : int.Parse(row["threshhold"]), title = row["title"], type = type, keywords = "" }; // Create imported achievement ImportedEarnable impAchieve = new ImportedEarnable() { UniqueData = template.title, OldID = oldID }; // Add to temporary list templatesToAdd.Add(template); _achievementMap.Add(impAchieve.OldID, impAchieve); } // Loop through points and put in correct achievements foreach (Dictionary<String, String> row in pointData) { int achievementID = int.Parse(row["achievementID"]); int categoryID = int.Parse(row["categoryID"]); int points = int.Parse(row["points"]); achievement_template template = templatesToAdd.Where(t => t.id == achievementID).FirstOrDefault(); if (template == null) continue; // Switch on old category id switch (categoryID) { case 1: template.points_create = points; break; // Create case 2: template.points_learn = points; break; // Learn case 3: template.points_socialize = points; break; // Socialize case 4: template.points_explore = points; break; // Explore } } // Add templates to database try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (achievement_template template in templatesToAdd) work.EntityContext.achievement_template.Add(template); } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); // Update the map with new ids foreach (ImportedEarnable e in _achievementMap.Values) { e.NewID = (from a in work.EntityContext.achievement_template where a.title == e.UniqueData select a.id).FirstOrDefault(); } // Put in requirements try { // Speed up work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (Dictionary<String, String> row in reqData) { // Get this achievement ImportedEarnable achieve = GetImportedEarnableByOldID(_achievementMap, row["achievementID"]); if (achieve == null || achieve.NewID == 0) continue; work.EntityContext.achievement_requirement.Add(new achievement_requirement() { achievement_id = achieve.NewID, description = row["description"] }); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); //// Put in caretakers //try //{ // // Speed up // work.EntityContext.Configuration.AutoDetectChangesEnabled = false; // foreach (Dictionary<String, String> row in caretakerData) // { // // Get this achievement and user // ImportedEarnable achieve = GetImportedEarnableByOldID(_achievementMap, row["achievementID"]); // if (achieve == null || achieve.NewID == 0) // continue; // ImportedUser user = GetImportedUserByOldID(row["caretakerID"]); // if (user == null || user.NewID == 0) // continue; // work.EntityContext.achievement_caretaker.Add(new achievement_caretaker() // { // achievement_id = achieve.NewID, // caretaker_id = user.NewID // }); // } //} //finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } //work.SaveChanges(); }
/// <summary> /// Imports the user content from V2 /// </summary> /// <param name="userStoriesTable">User Story data</param> /// <param name="userContentTable">User Content data</param> /// <param name="delimiter">Delimiter between data</param> /// <param name="work">The DB access</param> private void ImportAchievementUserStuff( HttpPostedFileBase userStoriesTable, HttpPostedFileBase userContentTable, String delimiter, UnitOfWork work) { // Grab the data List<Dictionary<String, String>> storyData = GetDataFromFile(userStoriesTable, delimiter); if (storyData == null) { ModelState.AddModelError("", "Error with User Story table. Check Debug Output"); return; } List<Dictionary<String, String>> contentData = GetDataFromFile(userContentTable, delimiter); if (contentData == null) { ModelState.AddModelError("", "Error with User Content table. Check Debug Output"); return; } // Go through stories try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (Dictionary<String, String> row in storyData) { int oldID = int.Parse(row["userstoryID"]); achievement_user_story story = new achievement_user_story() { date_submitted = DateTime.Parse(row["date_submitted"]), image = row["uc_url"], text = row["uc_text"] }; ImportedEarnable impStory = new ImportedEarnable() { OldID = oldID, UniqueData = row["date_submitted"] }; work.EntityContext.achievement_user_story.Add(story); _userStoryMap.Add(impStory.OldID, impStory); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } // Save, then get new ids work.SaveChanges(); foreach (ImportedEarnable impStory in _userStoryMap.Values) { DateTime submitTime = DateTime.Parse(impStory.UniqueData); impStory.NewID = (from s in work.EntityContext.achievement_user_story where s.date_submitted == submitTime select s.id).FirstOrDefault(); } // Go through content try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (Dictionary<String, String> row in contentData) { // Get the user ImportedUser approver = GetImportedUserByOldID(row["approverID"]); if (approver == null) continue; // Make the data entry int oldID = int.Parse(row["usercontentID"]); achievement_user_content content = new achievement_user_content() { submitted_date = DateTime.Parse(row["date_submitted"]), text = row["uc_text"], approved_by_id = approver.NewID, approved_date = DateTime.Parse(row["date_handled"]) }; // content type // 1 - image // 2 - url // 3 - text int contentType = int.Parse(row["typeID"]); switch (contentType) { case 1: // image content.content_type = (int)JPPConstants.UserSubmissionTypes.Image; content.image = row["uc_url"]; break; case 2: // url content.content_type = (int)JPPConstants.UserSubmissionTypes.URL; content.url = row["uc_url"]; break; case 3: // text content.content_type = (int)JPPConstants.UserSubmissionTypes.Text; break; } // Make the map item ImportedEarnable impContent = new ImportedEarnable() { OldID = oldID, UniqueData = row["date_submitted"] }; work.EntityContext.achievement_user_content.Add(content); _userContentMap.Add(impContent.OldID, impContent); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } // Save, then get new ids work.SaveChanges(); foreach (ImportedEarnable impStory in _userContentMap.Values) { DateTime submitTime = DateTime.Parse(impStory.UniqueData); impStory.NewID = (from s in work.EntityContext.achievement_user_content where s.submitted_date == submitTime select s.id).FirstOrDefault(); } }
/// <summary> /// Imports the achievement instances from V2 /// </summary> /// <param name="achieveTemplateTable">File w/ achievement instance data</param> /// <param name="achievePointTemplateTable">Achievement point instance data (to be rolled into achievement)</param> /// <param name="delimiter">Delimiter between data</param> /// <param name="work">The DB access</param> private void ImportAchievementInstances( HttpPostedFileBase achieveInstanceTable, HttpPostedFileBase achievePointInstanceTable, String delimiter, UnitOfWork work) { // Grab the data List<Dictionary<String, String>> achieveData = GetDataFromFile(achieveInstanceTable, delimiter); if (achieveData == null) { ModelState.AddModelError("", "Error with Achievement Instance table. Check Debug Output"); return; } List<Dictionary<String, String>> pointData = GetDataFromFile(achievePointInstanceTable, delimiter); if (pointData == null) { ModelState.AddModelError("", "Error with Achievement Point Instance table. Check Debug Output"); return; } // Put points into a dictionary Dictionary<int, int[]> pointLookUp = new Dictionary<int, int[]>(); foreach (Dictionary<String, String> row in pointData) { int oldID = int.Parse(row["achievement_instanceID"]); if (!pointLookUp.ContainsKey(oldID)) { pointLookUp.Add(oldID, new int[5]); } pointLookUp[oldID][int.Parse(row["categoryID"])] = int.Parse(row["points"]); } // Go through each data row try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (Dictionary<String, String> row in achieveData) { // Get the user and achievement ImportedEarnable achieve = GetImportedEarnableByOldID(_achievementMap, row["achievementID"]); ImportedUser user = GetImportedUserByOldID(row["userID"]); ImportedUser assigner = GetImportedUserByOldID(row["assignedbyID"]); if (achieve == null || achieve.NewID == 0 || user == null || user.NewID == 0) continue; // How many? int count = int.Parse(row["achievementcount"]); if (count == 0) count = 1; // Make multiple if it's repeatable! for (int i = 0; i < count; i++) { achievement_instance instance = new achievement_instance() { achieved_date = DateTime.Parse(row["date_achieved"]), achievement_id = achieve.NewID, assigned_by_id = assigner == null ? user.NewID : assigner.NewID, card_given = Boolean.Parse(row["has_cardbeengiven"]), card_given_date = String.IsNullOrWhiteSpace(row["givenDate"]) ? (DateTime?)null : DateTime.Parse(row["givenDate"]), comments_disabled = false, has_user_content = Boolean.Parse(row["has_usercontent"]), has_user_story = Boolean.Parse(row["has_userstory"]), user_id = user.NewID, globally_assigned = false }; if (i == 0) { // Look up points int[] points; if (pointLookUp.TryGetValue(int.Parse(row["achievement_instanceID"]), out points)) { instance.points_create = points[1]; // Create = 1 instance.points_explore = points[4]; // Explore = 4 instance.points_learn = points[2]; // Learn = 2 instance.points_socialize = points[3]; // Socialize = 3 } // Get user content/story stuff ImportedEarnable userContent = GetImportedEarnableByOldID(_userContentMap, row["usercontentID"]); ImportedEarnable userStory = GetImportedEarnableByOldID(_userStoryMap, row["userstoryID"]); if (instance.has_user_content) { if (userContent == null || userContent.NewID == 0) continue; // If content is REQUIRED, and not found, skip this - User will need to re-get achievement else instance.user_content_id = userContent.NewID; } // Check for legit user story if (instance.has_user_story && userStory != null && userStory.NewID > 0) { instance.user_story_id = userStory.NewID; } if (!instance.has_user_story && instance.has_user_content) { var content = work.EntityContext.achievement_user_content.Local.Single(c => c.id == userContent.NewID); achievement_user_story newStory = new achievement_user_story() { date_submitted = content.submitted_date, image = content.image, text = content.text }; work.EntityContext.achievement_user_story.Add(newStory); instance.has_user_story = true; instance.user_story = newStory; } } // Add to the DB work.EntityContext.achievement_instance.Add(instance); } } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); // Update content paths try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (achievement_instance instance in work.EntityContext.achievement_instance) { if (instance.user_content != null) { instance.user_content.image = UpdateContentPath(instance.user_id, instance.user_content.image); } if (instance.user_story != null) { instance.user_story.image = UpdateContentPath(instance.user_id, instance.user_story.image); } } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); }
/// <summary> /// Imports the user table from V2 /// </summary> /// <param name="profileTable">The file w/ user table data</param> /// <param name="delimiter">The delimiter between data</param> /// <param name="work">The DB access</param> private void ImportUsers(HttpPostedFileBase userTable, String delimiter, UnitOfWork work) { // Grab the data List<Dictionary<String, String>> data = GetDataFromFile(userTable, delimiter); if (data == null) { ModelState.AddModelError("", "Error with User table. Check Debug Output"); return; } try { // Disable for speed work.EntityContext.Configuration.AutoDetectChangesEnabled = false; // Go through each data row and create users foreach (Dictionary<String, String> row in data) { String username = row["username"]; String email = row["email"]; // Make the user (don't add directly to DB!) object userObj = new { username = username, first_name = row["real_first_name"], middle_name = row["real_middle_name"], last_name = row["real_last_name"], is_player = Boolean.Parse(row["is_player"]), created_date = DateTime.Parse(row["date_account_created"]), status = Boolean.Parse(row["account_suspended"]) ? (int)JPPConstants.UserStatus.Suspended : (int)JPPConstants.UserStatus.Active, first_login = Boolean.Parse(row["account_first_login"]), email = email, last_login_date = DateTime.Parse(row["date_last_login"]), has_agreed_to_tos = false, // False for everyone! display_name = row["real_first_name"] + " " + row["real_last_name"], privacy_settings = (int)JPPConstants.PrivacySettings.FriendsOnly, communication_settings = (int)JPPConstants.CommunicationSettings.All, notification_settings = 0 }; ImportedUser impUser = new ImportedUser() { Email = email, OldID = int.Parse(row["userID"]), Username = username, UserWasDeleted = false, UsernameConflict = false, EmailConflict = false }; // Check for conflicts impUser.UsernameConflict = work.EntityContext.user.Where(u => u.username == username).Any(); impUser.EmailConflict = work.EntityContext.user.Where(u => u.email == email).Any(); if (!impUser.EmailConflict && !impUser.UsernameConflict) { // No conflicts, so add WebSecurity.CreateUserAndAccount( username, Guid.NewGuid().ToString(), // "Random" password - user will need to reset userObj, false); // No confirmation } // Either way, put in our local map, with the old ID as the key _userMap.Add(impUser.OldID, impUser); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); // Update all the imported users with new ids foreach (ImportedUser user in _userMap.Values) { // Look up via username int? newID = (from u in work.EntityContext.user where u.username == user.Username select u.id).FirstOrDefault(); if (newID != null && newID.Value != 0) { user.NewID = newID.Value; } else { // Username not found, so try email. If not email, we just can't find the user newID = (from u in work.EntityContext.user where u.email == user.Email select u.id).FirstOrDefault(); if (newID != null && newID.Value != 0) user.NewID = newID.Value; } } }
public ActionResult Index(UserSettingsViewModel model) { if (ModelState.IsValid) { using (UnitOfWork work = new UnitOfWork()) { work.UserRepository.UpdateUserSettings(WebSecurity.CurrentUserId, model.CommunicationSettings, model.PrivacySettings); work.SaveChanges(); } // TODO: Figure out why model isn't being refreshed properly return RedirectToAction("Index"); } // TODO: refresh model? return View(model); }
public ActionResult AddUser(AddUserViewModel model) { //return model.Image.InputStream.ToString(); if (ModelState.IsValid) { try { WebSecurity.CreateUserAndAccount( model.Username, model.Password, new { first_name = model.FirstName, middle_name = model.MiddleName, last_name = model.LastName, is_player = model.IsPlayer, created_date = DateTime.Now, status = (int)JPPConstants.UserStatus.Active, first_login = true, email = model.Email, last_login_date = DateTime.Now, display_name = model.DisplayName, privacy_settings = (int)JPPConstants.PrivacySettings.FriendsOnly, has_agreed_to_tos = false, creator_id = WebSecurity.CurrentUserId, communication_settings = (int)JPPConstants.CommunicationSettings.All, notification_settings = 0, }, false); TempData["Message"] = "User " + model.Username + " successfully created."; UnitOfWork work = new UnitOfWork(); user user = work.UserRepository.GetUser(model.Username); try { Utilities.JPPDirectory.CheckAndCreateUserDirectory(user.id, Server); String qrString = Request.Url.GetLeftPart(UriPartial.Authority) + "/Players/" + user.id; //Create the file path and save the image String qrfilePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.UserQRCode, user.id); String qrfileMinusPath = qrfilePath.Replace("~/Content/Images/Users/" + user.id.ToString() + "/UserQRCodes/", ""); //"/Users/" + userID.ToString() + "/ProfilePictures/" + fileName + ".png"; if (JPPImage.SavePlayerQRCodes(qrfilePath, qrfileMinusPath, qrString)) { user.qr_image = qrfilePath; work.SaveChanges(); } if (model.Image != null && user != null) { Utilities.JPPDirectory.CheckAndCreateUserDirectory(user.id, Server); //Create the file path and save the image String filePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.ProfilePicture, user.id); String fileMinusPath = filePath.Replace("~/Content/Images/Users/" + user.id.ToString() + "/ProfilePictures/", ""); //"/Users/" + userID.ToString() + "/ProfilePictures/" + fileName + ".png"; if (JPPImage.SavePlayerImages(filePath, fileMinusPath, model.Image.InputStream)) { user.image = filePath; work.SaveChanges(); } } } catch (Exception e) { TempData["Message"] = TempData["Message"].ToString() +" However, there was an error uploading the profile picture: " + e.Message; } //Success return RedirectToAction("Index"); } catch (Exception e) { // Problem! ModelState.AddModelError("", "There was a problem adding the user: " + e.Message); } } // Something went wrong, redisplay return View(model); }
/// <summary> /// Imports the quest instances from V2 /// </summary> /// <param name="questInstanceTable">File w/ quest template data</param> /// <param name="delimiter">Delimiter between data</param> /// <param name="work">The DB access</param> private void ImportQuestInstances( HttpPostedFileBase questInstanceTable, String delimiter, UnitOfWork work) { // Grab the data List<Dictionary<String, String>> questData = GetDataFromFile(questInstanceTable, delimiter); if (questData == null) { ModelState.AddModelError("", "Error with Quest Instance table. Check Debug Output"); return; } // Loop through quests try { work.EntityContext.Configuration.AutoDetectChangesEnabled = false; foreach (Dictionary<String, String> row in questData) { ImportedUser user = GetImportedUserByOldID(row["userID"]); if (user == null || user.NewID == 0) continue; ImportedEarnable quest = GetImportedEarnableByOldID(_questMap, row["questID"]); if (quest == null || quest.NewID == 0) continue; quest_instance instance = new quest_instance() { comments_disabled = false, completed_date = DateTime.Parse(row["date_completed"]), quest_id = quest.NewID, user_id = user.NewID, globally_assigned = false }; work.EntityContext.quest_instance.Add(instance); } } finally { work.EntityContext.Configuration.AutoDetectChangesEnabled = true; } work.SaveChanges(); }
public ActionResult EditUser(EditUserViewModel model) { UnitOfWork work = new UnitOfWork(); user user = work.UserRepository.GetUser(model.ID); //Commented Out to make Dev easier if (model.Roles == null || !model.Roles.Contains(JPPConstants.Roles.FullAdmin)) { if (user.username.ToLower().Equals(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.AdminUsername).ToLower())) ModelState.AddModelError(String.Empty, "This user is required to be a Full Admin"); } // Valid? if (ModelState.IsValid) { // try //{ /*if (model.Image != null) { Utilities.JPPDirectory.CheckAndCreateUserDirectory(model.ID, Server); //Create the file path and save the image String filePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.ProfilePicture, model.ID); String fileMinusPath = filePath.Replace("~/Content/Images/Users/" + model.ID.ToString() + "/ProfilePictures/", ""); //"/Users/" + userID.ToString() + "/ProfilePictures/" + fileName + ".png"; if (JPPImage.SavePlayerImages(filePath, fileMinusPath, model.Image.InputStream)) { if (user != null) { user.image = filePath; } } }*/ List<LoggerModel> loggerList = new List<LoggerModel>(); // Put the data back into the database if (user != null) { //Check Display Name if (!String.Equals(model.DisplayName, user.display_name)) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.DisplayNameEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.display_name, Value2 = model.DisplayName }); //Change the DB entry user.display_name = model.DisplayName; } //Check Email if (!String.Equals(model.Email, user.email)) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.EmailEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.email, Value2 = model.Email }); //Change the DB entry user.email = model.Email; } //Check IsPlayer if (model.IsPlayer != user.is_player) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.IsPlayerEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.is_player.ToString(), Value2 = model.IsPlayer.ToString() }); //Change the DB entry user.is_player = model.IsPlayer; } //Check First Name if (!String.Equals(model.FirstName, user.first_name)) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.FirstNameEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.first_name, Value2 = model.FirstName }); //Change the DB entry user.first_name = model.FirstName; } //Check Middle Name if (!String.Equals(model.MiddleName, user.middle_name)) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.MiddleNameEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.middle_name, Value2 = model.MiddleName }); //Change the DB entry user.middle_name = model.MiddleName; } //Check Last Name if (!String.Equals(model.LastName, user.last_name)) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.LastNameEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.last_name, Value2 = model.LastName }); //Change the DB entry user.last_name = model.LastName; } //Check the six word bio String modelSixWordBio = model.SixWordBio1 == null ? "" : model.SixWordBio1.Replace(" ", "") + " "; modelSixWordBio += model.SixWordBio2 == null ? "" : model.SixWordBio2.Replace(" ", "") + " "; modelSixWordBio += model.SixWordBio3 == null ? "" : model.SixWordBio3.Replace(" ", "") + " "; modelSixWordBio += model.SixWordBio4 == null ? "" : model.SixWordBio4.Replace(" ", "") + " "; modelSixWordBio += model.SixWordBio5 == null ? "" : model.SixWordBio5.Replace(" ", "") + " "; modelSixWordBio += model.SixWordBio6 == null ? "" : model.SixWordBio6.Replace(" ", ""); if (!String.Equals(user.six_word_bio, modelSixWordBio)) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.SixWordBioEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.six_word_bio, Value2 = modelSixWordBio }); //Change the DB entry user.six_word_bio = modelSixWordBio; } if(!String.Equals(model.FullBio, user.full_bio)) { //Add it to the list to log first to get the old value loggerList.Add(new LoggerModel() { Action = Logger.EditProfileContentLogType.FullBioEdit.ToString(), UserID = WebSecurity.CurrentUserId, IPAddress = Request.UserHostAddress, TimeStamp = DateTime.Now, IDType1 = Logger.LogIDType.User.ToString(), ID1 = user.id, Value1 = user.full_bio, Value2 = model.FullBio }); //Change the DB entry user.full_bio = model.FullBio; } user.modified_date = DateTime.Now; Logger.LogMultipleEntries(loggerList, work.EntityContext); // Save the changes, then add the user to the roles work.SaveChanges(); JPPConstants.Roles.UpdateUserRoles(user.username, model.Roles); // Success TempData["Message"] = "Successfully saved changes to " + user.first_name + " " + user.last_name; return RedirectToAction("EditUserList"); } else { ModelState.AddModelError("", "The specified user could not be found"); } // } // catch (Exception e) // { // ModelState.AddModelError("", e.Message); //} } model.Roles = Roles.GetRolesForUser(user.username); model.ImageURL = user.image; // Problem, redisplay return View(model); }
public ActionResult ProcessFacebookLogin() { if (Request.QueryString["error"] != null) { TempData["FacebookResultMessage"] = "There was an error validating with Facebook: " + Request.QueryString["error_description"]; return RedirectToAction("Index"); // TODO: log error? } // Exchange code for an access token string code = Request.QueryString["code"]; // Redirect to Facebook to ask for permissions string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("Default", new { Controller = "Settings", Action = "ProcessFacebookLogin" }); object accessTokenGetParams = new { client_id = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppId), redirect_uri = redirectAfterLoginUri, client_secret = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppSecret), code = code }; var fbClient = new FacebookClient(); dynamic getAccessTokenResult = fbClient.Get("/oauth/access_token", accessTokenGetParams); string accessToken = getAccessTokenResult.access_token; Int64 secondsTilExpiration = getAccessTokenResult.expires; DateTime expireTime = DateTime.Now.AddSeconds(secondsTilExpiration); // Verify token is valid bool isTokenValid = IsUserAccessTokenValid(accessToken); if (!isTokenValid) { TempData["FacebookResultMessage"] = "There was an error validating with Facebook: User access token was invalid."; return RedirectToAction("Index"); } // Get user ID fbClient = new FacebookClient(accessToken); dynamic fbMe = fbClient.Get("me"); string fbUserId = fbMe.id.ToString(); // Save data from Facebook into db using (UnitOfWork work = new UnitOfWork()) { user currentUser = work.UserRepository.GetUser(WebSecurity.CurrentUserId); work.UserRepository.UpdateFacebookDataForExistingConnection(currentUser, fbUserId, accessToken, expireTime); work.SaveChanges(); } TempData["FacebookResultMessage"] = "Successfully connected to Facebook!"; return RedirectToAction("Index"); }