Inheritance: IDisposable, IUnitOfWork
        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 Boolean AddAchievementStoryText(int instanceID, String text)
        {
            if (!HttpContext.Request.IsAjaxRequest())
            {
                return false;
            }
            if (String.IsNullOrWhiteSpace(text))
            {
                return false;
            }

            UnitOfWork work = new UnitOfWork();
            return work.AchievementRepository.UserAddAchievementStoryText(instanceID, text);
        }
        public ActionResult Assertion(int userID, int achievementID)
        {
            string userEmail, achievementImageURL;
            DateTime achievementDate;
            using (UnitOfWork work = new UnitOfWork())
            {
                // Verify user actually has achievement
                if (!work.AchievementRepository.DoesUserHaveAchievement(userID, achievementID))
                {
                    return new HttpStatusCodeResult(HttpStatusCode.NotFound);
                }

                // If so, get data and generate assertion
                userEmail = work.UserRepository.GetUser(userID).email;

                achievement_template achievementTemplate = work.AchievementRepository.GetTemplateById(achievementID);
                achievementImageURL = JppUriInfo.GetAbsoluteUri(Request, achievementTemplate.icon);

                achievement_instance achievementInstance = work.AchievementRepository.GetUserAchievementInstance(userID, achievementID);
                achievementDate = achievementInstance.achieved_date;
            }
            string salt = "CoeA8DQf"; // As we are exposing the salt anyway, using a constant isn't an issue, and it saves us from having to store every randomly-generated salt in the db
            string hashedEmail;
            hashedEmail = Sha256Helper.HashStringWithSalt(userEmail, salt);

            var badgeAssertion = new
            {
                uid = GenerateUniqueId(userID, achievementID),
                recipient = new
                {
                    identity = "sha256$" + hashedEmail,
                    type = "email",
                    hashed = true,
                    salt = salt
                },
                image = achievementImageURL,
                badge = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("OpenBadgeDescriptionRoute", new { Action = "BadgeDescription", achievementID = achievementID }),
                verify = new
                {
                    type = "hosted",
                    url = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("OpenBadgeRoute", new { Action = "Assertion", userID = userID, achievementID = achievementID }),
                },
                issuedOn = achievementDate.ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                evidence = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("AchievementsPlayersRoute", new { id = achievementID, playerID = userID }),
            };

            return Json(badgeAssertion, JsonRequestBehavior.AllowGet);
        }
        public static ContactPageViewModel Populate(UnitOfWork work = null)
        {
            if (work == null)
                work = new UnitOfWork();

            ContactPageViewModel model = new ContactPageViewModel();

            if (WebSecurity.IsAuthenticated)
            {
               var currentUser =  work.EntityContext.user.Find(WebSecurity.CurrentUserId);
               model.SenderEmail = currentUser.email;
                model.SenderName = currentUser.first_name + " " +currentUser.last_name;
            }

            return model;
        }
        public static FacebookConnectionViewModel Populate(int userId, IUnitOfWork work = null)
        {
            if (work == null) work = new UnitOfWork();

            facebook_connection fbConnection = work.EntityContext.facebook_connection.Find(userId);
            if (fbConnection == null)
            {
                fbConnection = new facebook_connection() { notifications_enabled = false, automatic_sharing_enabled = false };
            }

            FacebookConnectionViewModel model = new FacebookConnectionViewModel()
            {
                NotificationsEnabled = fbConnection.notifications_enabled,
                AutomaticSharingEnabled = fbConnection.automatic_sharing_enabled,
            };

            return model;
        }
Example #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Dependency injection
            //DependencyResolver.SetResolver(new NinjectDependencyResolver());

            // Database initialization
            Database.SetInitializer<JustPressPlayDBEntities>(new JPPDatabaseInit());
            using (UnitOfWork db = new UnitOfWork())
            {
                db.EntityContext.Database.Initialize(true);
            }
        }
        public JsonResult ExpireAuthorizationToken(string token, string authHash)
        {
            /*---------------------------------Token Validation Begin-----------------------------------*/
            #region Validate the Token

            //Get the current token
            UnitOfWork work = new UnitOfWork();
            external_token currentToken = work.SystemRepository.GetAuthorizationToken(token);

            //Invalid token
            if (currentToken == null)
                return Json(new MobileAppTokenErrorModel() { Success = false, Message = GetTokenValidationResultMessage(TokenValidationResult.FailureInvalid) });

            //Build the string to be hashed
            string salt = currentToken.refresh_token;
            string paramString = "token=" + token;
            string stringToHash = salt + "?" + paramString;

            //Invalid hash
            if (!ValidateHash(stringToHash, authHash))
                return Json(new MobileAppTokenErrorModel() { Success = false, Message = GetTokenValidationResultMessage(TokenValidationResult.FailureHash) });

            #endregion
            /*----------------------------------Token Validation End------------------------------------*/

            //Expire the token
            bool expired = work.SystemRepository.ExpireAuthorizationToken(token);

            //Build the response
            MobileAppTokenErrorModel response = new MobileAppTokenErrorModel() { Success = expired, Message = "Unknown Error" };
            if (expired)
                response.Message = "Token Expired";

            //Return
            return Json(response);
        }
 public ActionResult AwardCard(int id)
 {
     if (Request.UrlReferrer != null)
     {
         UnitOfWork work = new UnitOfWork();
         achievement_instance instance = work.AchievementRepository.InstanceExists(id);
         if (instance != null)
             work.AchievementRepository.AwardCard(instance);
     }
     //Redirect back to the ManageUserCards for the currently selected user
     return Redirect(Request.UrlReferrer.ToString());
 }
 public void DenyUserQuest(int questID, string reason)
 {
     UnitOfWork work = new UnitOfWork();
     work.QuestRepository.DenyUserQuest(questID, reason);
 }
        public ActionResult AssignGlobalAchievement(AssignGlobalAchievementViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UnitOfWork work = new UnitOfWork();
                    work.AchievementRepository.AssignGlobalAchievement(model.AchievementID, model.StartRange, model.EndRange, WebSecurity.CurrentUserId);
                    TempData["Message"] = "Global Achievement Successfully Awarded!";
                    return RedirectToAction("Index");
                }
                catch
                {
                }
            }

            AssignGlobalAchievementViewModel refreshModel = AssignGlobalAchievementViewModel.Populate();
            model.Achievements = refreshModel.Achievements;
            return View(model);
        }
        public ActionResult AssignIndividualAchievement(AssignIndividualAchievementViewModel model)
        {
            if (ModelState.IsValid)
            {
                UnitOfWork work = new UnitOfWork();
                int achievementType = work.AchievementRepository.GetAchievementType(model.AchievementID);
                // Attempt to assign the achievement
                try
                {
                    if(achievementType != (int)JPPConstants.AchievementTypes.UserSubmission)
                        TempData["Message"] = work.AchievementRepository.AssignAchievement(model.UserID, model.AchievementID, WebSecurity.CurrentUserId).ToString();
                    return RedirectToAction("AssignIndividualAchievement");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                }
            }

            AssignIndividualAchievementViewModel refreshModel = AssignIndividualAchievementViewModel.Populate();
            model.Users = refreshModel.Users;
            model.Achievements = refreshModel.Achievements;

            // Problem, return the model
            return View(model);
        }
        /// <summary>
        /// Populates a view model with a list of quests
        /// </summary>
        /// <param name="userID">The id of a user for user-related searches</param>
        /// <param name="completedQuests">Only include completed quests?</param>
        /// <param name="partiallyCompletedQuests">Only include partially completed quests?</param>
        /// <param name="incompleteQuests">Only include fully incomplete quests?</param>
        /// <param name="inactiveQuests">Include inactive quests?</param>
        /// <param name="trackedQuests">Show only tracked quests?</param>
        /// <param name="userGeneratedQuests">Include user generated quests?</param>
        /// <param name="search">A string for searching</param>
        /// <param name="work">The unit of work for DB access.  If null, one will be created.</param>
        /// <returns>A populated view model with a list of quests</returns>
        public static QuestsListViewModel Populate(
			int? userID = null,
			bool completedQuests = false,
			bool partiallyCompletedQuests = false,
			bool incompleteQuests = false,
			bool inactiveQuests = false,
			bool trackedQuests = false,
			bool userGeneratedQuests = false,
			int? start = null,
			int? count = null,
			String search = null,
			UnitOfWork work = null)
        {
            if (work == null)
                work = new UnitOfWork();

            // Set up the filter query
            var query = from q in work.EntityContext.quest_template
                        select q;

            // Keep user-gen quests out unless specifically requested -
            // TODO: Verify this behavior
            if (!userGeneratedQuests)
            {
                query = from q in query
                        where q.user_generated == false
                        select q;
            }

            // User stuff required authentication
            if (WebSecurity.IsAuthenticated)
            {

                // Tracking?
                if (trackedQuests)
                {
                    query = from q in query
                            join t in work.EntityContext.quest_tracking
                            on q.id equals t.quest_id
                            where t.user_id == WebSecurity.CurrentUserId
                            select q;
                }

                // Just include completed quests?  Look for quest instance
                if (completedQuests)
                {
                    int userForCompleted = userID == null ? WebSecurity.CurrentUserId : userID.Value;

                    query = from q in query
                            join qi in work.EntityContext.quest_instance
                            on q.id equals qi.quest_id
                            where qi.user_id == userForCompleted
                            select q;
                }

                // Progress-related?
                if (partiallyCompletedQuests || incompleteQuests)
                {
                    int userForCompleted = userID == null ? WebSecurity.CurrentUserId : userID.Value;
                    // Create the query for progress
                    query = (from q in query
                               select q)
                               .Except(from q in query
                            join qi in work.EntityContext.quest_instance
                            on q.id equals qi.quest_id
                            where qi.user_id == userForCompleted
                            select q);

                    var progressQ = (from q in query
                                    join step in work.EntityContext.quest_achievement_step
                                    on q.id equals step.quest_id
                                    join ai in work.EntityContext.achievement_instance
                                    on step.achievement_id equals ai.achievement_id
                                    where ai.user_id == userForCompleted
                                    select q).Distinct();

                    // Quests where the achieved count is zero
                    if (incompleteQuests)
                    {
                        query = (from q in query
                                select q).Except(progressQ);
                    }

                    // Quests where at least some of the threshold has been met,
                    // but not the whole thing!
                    if (partiallyCompletedQuests)
                    {
                        query = progressQ;
                        // TODO: Update current quests to use
                    }
                }
            }

            // Include inactive?
            if (inactiveQuests)
            {
                query = from q in query
                        where q.state == (int)JPPConstants.AchievementQuestStates.Active || q.state == (int)JPPConstants.AchievementQuestStates.Inactive
                        select q;
            }
            else
            {
                // Only active
                query = from q in query
                        where q.state == (int)JPPConstants.AchievementQuestStates.Active
                        select q;
            }

            // TODO: Handle search keywords
            // ...

            // Do filtering on titles and descriptions
            if (search != null)
            {
                query = from q in query
                        where q.title.Contains(search) || q.description.Contains(search)
                        select q;
            }

            // Order by the title
            query = query.OrderBy(q => q.title);

            // Get the total before limits
            int total = query.Count();

            // Start at a specific index?
            if (start != null && start.Value > 0)
            {
                query = query.Skip(start.Value);
            }

            // Keep only a specific amount?
            if (count != null)
            {
                query = query.Take(count.Value);
            }

            return new QuestsListViewModel()
            {
                Quests = (from q in query
                          select new BasicQuestInfo()
                          {
                              ID = q.id,
                              Image = q.icon,
                              Title = q.title,
                              IsUserGenerated = q.user_generated
                          }).ToList(),
                Total = total
            };
        }
Example #13
0
        public List<JPPNewsFeed> Populate()
        {
            List<JPPNewsFeed> fullNewsFeedList = new List<JPPNewsFeed>();

            UnitOfWork work = new UnitOfWork();

            fullNewsFeedList.AddRange(work.AchievementRepository.GetAchievementsForFeed());
            fullNewsFeedList.AddRange(work.QuestRepository.GetQuestsForFeed());
            fullNewsFeedList.AddRange(work.SystemRepository.GetNewsForFeed());

            return fullNewsFeedList;
        }
        public ActionResult AddNewsItem(AddNewsItemViewModel model)
        {
            model.CreatorID = WebSecurity.CurrentUserId;

            if (ModelState.IsValid)
            {
                try
                {
                    if (model.Image != null)
                    {
                        Utilities.JPPDirectory.CheckAndCreateNewsDirectory(Server);
                        model.ImageFilePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.News);
                        Utilities.JPPImage.Save(Server, model.ImageFilePath, model.Image.InputStream, JPPConstants.Images.NewsImageMaxSize, 200, true);
                    }

                    UnitOfWork work = new UnitOfWork();
                    work.SystemRepository.AdminAddNewsItem(model);
                    return RedirectToAction("Index");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", "News Item Failed to Add: " + e.Message);
                }
            }

            return View(model);
        }
        public ActionResult AddAchievement(AddAchievementViewModel model)
        {
            //Add the Logged In User(Creator) ID to the Model
            model.CreatorID = WebSecurity.CurrentUserId;

            //Create a new Unit of Work
            UnitOfWork work = new UnitOfWork();

            #region Modify Model based on achievement type

            //Only scans get caretakers| Only thresholds have a threshold number and parent
            //Only user submissions have content types | Only system achievements have system trigger types
            //Thresholds can't be repeatable | Only repeatable achievements have a delay, which must be at least 1

            JPPConstants.AchievementTypes achievementType = (JPPConstants.AchievementTypes)model.Type;
            model.IsRepeatable = !achievementType.Equals(JPPConstants.AchievementTypes.Scan) ? false : model.IsRepeatable;
            model.SelectedCaretakersList = achievementType.Equals(JPPConstants.AchievementTypes.Scan) ? model.SelectedCaretakersList : null;
            model.Threshold = achievementType.Equals(JPPConstants.AchievementTypes.Threshold) ? model.Threshold : null;
            model.ParentID = achievementType.Equals(JPPConstants.AchievementTypes.Threshold) ? model.ParentID : null;
            model.ContentType = achievementType.Equals(JPPConstants.AchievementTypes.UserSubmission) ? model.ContentType : null;
            model.SystemTriggerType = achievementType.Equals(JPPConstants.AchievementTypes.System) ? model.SystemTriggerType : null;
            model.RepeatDelayDays = model.RepeatDelayDays >= 1 ? model.RepeatDelayDays : 1;
            model.RepeatDelayDays = model.IsRepeatable ? model.RepeatDelayDays : null;

            #endregion

            if (model.Type == (int)JPPConstants.AchievementTypes.System && work.AchievementRepository.SystemAchievementExists((int)model.SystemTriggerType))
                ModelState.AddModelError(String.Empty, "There is already a system achievement of that type");
            if (model.Icon == null && model.UploadedIcon == null)
                ModelState.AddModelError(String.Empty, "An icon must be selected for this achievement");
            if (model.Title != null)
                if (work.AchievementRepository.AchievementTitleExists(model.Title))
                    ModelState.AddModelError("", "An achievement with that title already exists");
            //Check to make sure the model is valid and the image uploaded is an actual image
            if (ModelState.IsValid)
            {
                try
                {
                    if(model.UploadedIcon != null)
                    {
                        String filePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.NewIconUpload);
                        model.Icon = filePath.Replace("~/Content/Images/Icons/", "");
                        model.Icon = model.Icon.Replace(".png", "");
                        JPPImage.Save(Server, filePath, model.UploadedIcon.InputStream, 400, 400, true);
                    }
                    //Make Sure the Directories Exist
                    Utilities.JPPDirectory.CheckAndCreateAchievementAndQuestDirectory(Server);

                    //Create the file path and save the image
                    model.IconFilePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.AchievementIcon);
                    if (JPPImage.SaveAchievementIcons(model.IconFilePath, model.Icon, model.PointsCreate, model.PointsExplore, model.PointsLearn, model.PointsSocialize))
                    {
                        //Add the Achievement to the Database
                        work.AchievementRepository.AdminAddAchievement(model);

                        //Return to the Admin index page
                        TempData["Message"] = "Achievement: " + model.Title + " successfully created and is in draft mode awaiting approval.";
                        return RedirectToAction("EditAchievementList");
                    }
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", "Achievement Creation Failed: " + e.Message);
                }
            }

            //ModelState was not valid, refresh the ViewModel
            AddAchievementViewModel refreshModel = AddAchievementViewModel.Populate();
            model.PotentialCaretakersList = refreshModel.PotentialCaretakersList;
            model.ParentAchievements = refreshModel.ParentAchievements;
            model.IconList = refreshModel.IconList;

            //Return the user to the AddAchievement view with the current model
            return View(model);
        }
        public ActionResult SendAnnouncement(SendAnnouncementViewModel model)
        {
            UnitOfWork work = new UnitOfWork();
            List<user> users = work.UserRepository.GetAllActiveUsers();
            List<string> userEmails = new List<string>();
            foreach (user user in users)
            {
                userEmails.Add(user.email);
            }
            Email.Send(userEmails, model.Subject, model.Body);

            TempData["Message"] = "Annoucement Successfully Sent";
            return RedirectToAction("Index");
        }
        public ActionResult ViewPendingSubmission(int id, ViewPendingSubmissionViewModel model)
        {
            if(!model.Approved && String.IsNullOrWhiteSpace(model.Reason))
                ModelState.AddModelError(String.Empty, "A reason must be provided to deny this submission");

            if (ModelState.IsValid)
            {
                UnitOfWork work = new UnitOfWork();
                if (model.Approved)
                {
                    work.AchievementRepository.HandleContentSubmission(id, JPPConstants.HandleUserContent.Approve);
                    return RedirectToAction("PendingUserSubmissionsList");
                }
                else
                {
                    work.AchievementRepository.HandleContentSubmission(id, JPPConstants.HandleUserContent.Deny, model.Reason);
                    return RedirectToAction("PendingUserSubmissionsList");
                }
            }
            ViewPendingSubmissionViewModel refresh = ViewPendingSubmissionViewModel.Populate(id);
            refresh.Reason = model.Reason;
            refresh.Approved = model.Approved;
            return View(refresh);
        }
 public ActionResult RevokeAchievement(int id)
 {
     UnitOfWork work = new UnitOfWork();
     //TODO: FIX PARAMETERS
     work.AchievementRepository.RevokeAchievement(id,"reason",true,1);
     return RedirectToAction("Index");
 }
        public ActionResult ManageHighlights(ManageHighlightsViewModel model)
        {
            // TODO: implement editing
            if (model.SelectedAchievementIDs == null && model.SelectedQuestsIDs == null)
                ModelState.AddModelError(String.Empty, "At least one achievement or quest must be selected to be featured!");

            if (ModelState.IsValid)
            {
                UnitOfWork work = new UnitOfWork();
                work.SystemRepository.AdminEditHighlights(model);
                return RedirectToAction("Index");
            }

            ManageHighlightsViewModel refreshModel = ManageHighlightsViewModel.Populate();
            model.AllAchievementsList = refreshModel.AllAchievementsList;
            model.AllQuestsList = refreshModel.AllQuestsList;

            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 DiscardAchievementDraft(int id)
        {
            UnitOfWork work = new UnitOfWork();
            var message = work.AchievementRepository.DiscardAchievementDraft(id);
            if (!String.IsNullOrWhiteSpace(message))
            {
                TempData["Message"] = message;
                return RedirectToAction("EditAchievementList");
            }

            return RedirectToAction("EditAchievement", new { id = id });
        }
        public ActionResult EditQuest(int id, EditQuestViewModel model)
        {
            //Create a new Unit of Work
            UnitOfWork work = new UnitOfWork();
            model.EditorID = WebSecurity.CurrentUserId;

            //Check to make sure the Quest isn't being put back into draft mode
            JPPConstants.AchievementQuestStates currentQuestState = (JPPConstants.AchievementQuestStates)work.QuestRepository.GetQuestState(id);
            JPPConstants.AchievementQuestStates modelQuestState = (JPPConstants.AchievementQuestStates)model.State;
            if (!currentQuestState.Equals(JPPConstants.AchievementQuestStates.Draft) && modelQuestState.Equals(JPPConstants.AchievementQuestStates.Draft))
                ModelState.AddModelError(String.Empty, "This Achievement was already moved out of draft mode, it cannot be moved back");

            //Make sure the quest has associated achievements
            if (model.SelectedAchievementsList.Count <= 0)
                ModelState.AddModelError(String.Empty, "No Achievements were selected for this quest");

            //Make sure the Threshold value doesn't exceed the number of selected achievements
            if (model.Threshold > model.SelectedAchievementsList.Count)
                ModelState.AddModelError("Threshold", "The Threshold value was greater than the number of achievements selected for this quest.");

            model.Threshold = model.Threshold == null || model.Threshold <= 0 ? model.SelectedAchievementsList.Count : model.Threshold;
            if (model.Icon == null && model.UploadedIcon == null)
            ModelState.AddModelError(String.Empty, "An icon must be selected for this achievement");

            if (model.Title != null)
                if (work.QuestRepository.QuestTitleExists(model.Title, id))
                    ModelState.AddModelError("", "A quest with that title already exists");

            if (ModelState.IsValid)
            {
                if (model.UploadedIcon != null)
                {
                    String filePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.NewIconUpload);
                    model.Icon = filePath.Replace("~/Content/Images/Icons/", "");
                    model.Icon = model.Icon.Replace(".png", "");
                    JPPImage.Save(Server, filePath, model.UploadedIcon.InputStream, 400, 400, true);
                }

                quest_template template = work.EntityContext.quest_template.Find(id);
                model.IconFilePath = template == null ?
                    Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.QuestIcon) :
                    template.icon;
                if (JPPImage.SaveQuestIcons(model.IconFilePath, model.Icon, false))
                {
                    //Add the Quest to the Database
                    work.QuestRepository.AdminEditQuest(id, model);

                    //Return to the Admin index page
                    TempData["Message"] = "Changes to " + model.Title + " were successfully saved.";
                    return RedirectToAction("EditQuestList");
                }
            }
            //ModelState was invalid, refresh the AchievementsList to prevent NullReferenceException
            AddQuestViewModel refreshModel = AddQuestViewModel.Populate();
            model.AchievementsList = refreshModel.AchievementsList;
            model.IconList = refreshModel.IconList;
            return View(model);
        }
        public ActionResult EditAchievement(int id, EditAchievementViewModel model)
        {
            //Add the Logged In User(Creator) ID to the Model
            model.EditorID = WebSecurity.CurrentUserId;
            ViewBag.ModelStateBeforeCode = ModelState.IsValid;
            //Create a new Unit of Work
            UnitOfWork work = new UnitOfWork();

            JPPConstants.AchievementQuestStates currentAchievementState = (JPPConstants.AchievementQuestStates)work.AchievementRepository.GetAchievementState(id);
            JPPConstants.AchievementQuestStates modelAchievementState = (JPPConstants.AchievementQuestStates)model.State;

            if (!currentAchievementState.Equals(JPPConstants.AchievementQuestStates.Draft) && modelAchievementState.Equals(JPPConstants.AchievementQuestStates.Draft))
                ModelState.AddModelError(String.Empty, "This Achievement was already moved out of draft mode, it cannot be moved back");

            #region Modify Model based on achievement type

            //Only scans get caretakers| Only thresholds have a threshold number and parent
            //Only user submissions have content types | Only system achievements have system trigger types
            //Only scans are repeatable | Only repeatable achievements have a delay, which must be at least 1

            JPPConstants.AchievementTypes achievementType = (JPPConstants.AchievementTypes)model.Type;
            model.IsRepeatable = !achievementType.Equals(JPPConstants.AchievementTypes.Scan) ? false : model.IsRepeatable;
            model.SelectedCaretakersList = achievementType.Equals(JPPConstants.AchievementTypes.Scan) ? model.SelectedCaretakersList : null;
            model.Threshold = achievementType.Equals(JPPConstants.AchievementTypes.Threshold) ? model.Threshold : null;
            model.ParentID = achievementType.Equals(JPPConstants.AchievementTypes.Threshold) ? model.ParentID : null;
            model.ContentType = achievementType.Equals(JPPConstants.AchievementTypes.UserSubmission) ? model.ContentType : null;
            model.SystemTriggerType = achievementType.Equals(JPPConstants.AchievementTypes.System) ? model.SystemTriggerType : null;
            model.RepeatDelayDays = model.RepeatDelayDays >= 1 ? model.RepeatDelayDays : 1;
            model.RepeatDelayDays = model.IsRepeatable ? model.RepeatDelayDays : null;

            #endregion

            if (model.Type == (int)JPPConstants.AchievementTypes.System && work.AchievementRepository.SystemAchievementExists((int)model.SystemTriggerType) && id != work.AchievementRepository.GetSystemAchievementID((int)model.SystemTriggerType))
                ModelState.AddModelError(String.Empty, "There is already a system achievement of that type");
            if (model.Icon == null && model.UploadedIcon == null)
                ModelState.AddModelError(String.Empty, "An icon must be selected for this achievement");
            if (model.Title != null)
                if (work.AchievementRepository.AchievementTitleExists(model.Title, id))
                    ModelState.AddModelError("", "An achievement with that title already exists");
            //Check to make sure the model is valid
            if (ModelState.IsValid)
            {

                try
                {

                    if (model.UploadedIcon != null)
                    {
                        String filePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.NewIconUpload);
                        model.Icon = filePath.Replace("~/Content/Images/Icons/", "");
                        model.Icon = model.Icon.Replace(".png", "");
                        JPPImage.Save(Server, filePath, model.UploadedIcon.InputStream, 400, 400, true);
                    }

                    Utilities.JPPDirectory.CheckAndCreateAchievementAndQuestDirectory(Server);
                    achievement_template template = work.EntityContext.achievement_template.Find(id);
                    model.IconFilePath = template == null ?
                        Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.AchievementIcon) :
                        template.icon;
                    if (model.IconFilePath.Contains(".jpg"))
                        model.IconFilePath = model.IconFilePath.Replace(".jpg", "");
                    if (!model.IconFilePath.Contains(".png"))
                        model.IconFilePath += ".png";
                   if(JPPImage.SaveAchievementIcons(model.IconFilePath, model.Icon, model.PointsCreate, model.PointsExplore, model.PointsLearn, model.PointsSocialize))
                    {
                        //Add the Achievement to the Database
                        work.AchievementRepository.AdminEditAchievement(id, model);

                        //Return to the Admin index page
                        TempData["Message"] = "The changes to " + model.Title + " were successfully saved.";
                        return RedirectToAction("EditAchievementList");
                    }
                }
                catch(Exception e)
                {
                    ModelState.AddModelError("", "Achievement Editing Failed: " + e.Message);
                }
            }

            //Modelstate was not valid, refresh the ViewModel
            AddAchievementViewModel refreshModel = AddAchievementViewModel.Populate();
            model.PotentialCaretakersList = refreshModel.PotentialCaretakersList;
            model.ParentAchievements = refreshModel.ParentAchievements;
            model.IconList = refreshModel.IconList;
            //Return the user to the EditAchievement view with the current model
            return View(model);
        }
Example #24
0
        /// <summary>
        /// Populates the timeline view model.  If the user is logged in, the player's profile information
        /// and friends earnings will be included.  If the user is not logged in, only public earnings
        /// will be included.
        /// </summary>
        /// <param name="start">The zero-based index of the first earning to return</param>
        /// <param name="count">The amount of earnings to return</param>
        /// <param name="includePublic">Include public earnings? Only used when logged in.</param>
        /// <param name="work">Unit of work for DB access.  If null, one will be created.</param>
        /// <returns>A popualted timeline view model</returns>
        public static HomeViewModel Populate(
			int? start = null,
			int? count = null,
			int? startComments = null,
			int? countComments = null,
			bool? includePublic = null,
			int? newsCount = null,
			UnitOfWork work = null)
        {
            if (work == null)
                work = new UnitOfWork();

            // News
            var news = from n in work.EntityContext.news select n;
            if (newsCount != null)
            {
                news = news.Take(newsCount.Value);
            }
            news = news.OrderByDescending(n => n.created_date);

            // Featured Achievements & quests
            var achievements = from a in work.EntityContext.achievement_template
                               where a.featured == true
                               orderby a.created_date descending
                               select a;
            var quests = from q in work.EntityContext.quest_template
                         where q.featured == true
                         orderby q.created_date descending
                         select q;

            // Overall game stats
            var gamePoints = (from ai in work.EntityContext.achievement_instance
                              group ai by 1 into achieves
                              select new
                              {
                                  PointsCreate = achieves.Sum(p => p.points_create),
                                  PointsExplore = achieves.Sum(p => p.points_explore),
                                  PointsLearn = achieves.Sum(p => p.points_learn),
                                  PointsSocialize = achieves.Sum(p => p.points_socialize),
                                  TotalAchievements = achieves.Count()
                              }).FirstOrDefault();
            Stats gameStats = new Stats()
            {
                PointsCreate = gamePoints == null ? 0 : gamePoints.PointsCreate,
                PointsExplore = gamePoints == null ? 0 : gamePoints.PointsExplore,
                PointsLearn = gamePoints == null ? 0 : gamePoints.PointsLearn,
                PointsSocialize = gamePoints == null ? 0 : gamePoints.PointsSocialize,
                TotalAchievements = gamePoints == null ? 0 : gamePoints.TotalAchievements,
                TotalQuests = (from qi in work.EntityContext.quest_instance select qi).Count(),
                TotalPlayers = (from u in work.EntityContext.user where u.is_player == true select u).Count()
            };

            // Current player stats
            Stats myStats = null;
            if (WebSecurity.IsAuthenticated)
            {
                var myPoints = (from ai in work.EntityContext.achievement_instance
                                where ai.user_id == WebSecurity.CurrentUserId
                                group ai by 1 into achieves
                                select new
                                {
                                    PointsCreate = achieves.Sum(p => p.points_create),
                                    PointsExplore = achieves.Sum(p => p.points_explore),
                                    PointsLearn = achieves.Sum(p => p.points_learn),
                                    PointsSocialize = achieves.Sum(p => p.points_socialize),
                                    TotalAchievements = achieves.Count()
                                }).FirstOrDefault();
                myStats = new Stats()
                {
                    PointsCreate = myPoints == null ? 0 : myPoints.PointsCreate,
                    PointsExplore = myPoints == null ? 0 : myPoints.PointsExplore,
                    PointsLearn = myPoints == null ? 0 : myPoints.PointsLearn,
                    PointsSocialize = myPoints == null ? 0 : myPoints.PointsSocialize,
                    TotalAchievements = myPoints == null ? 0 : myPoints.TotalAchievements,
                    TotalQuests = (from qi in work.EntityContext.quest_instance where qi.user_id == WebSecurity.CurrentUserId select qi).Count(),
                    TotalPlayers = (from f in work.EntityContext.friend where f.destination_id == WebSecurity.CurrentUserId select f).Count()
                };
            }

            // Assemble and return
            return new HomeViewModel()
            {
                MyStats = myStats,
                GameStats = gameStats,
                News = news.ToList(),
                FeaturedAchievements = achievements.ToList(),
                FeaturedQuests = quests.ToList()
            };
        }
        public ActionResult EditNewsItem(int id, EditNewsItemViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (model.Image != null)
                    {
                        Utilities.JPPDirectory.CheckAndCreateNewsDirectory(Server);
                        model.ImageFilePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.News);
                        Utilities.JPPImage.Save(Server, model.ImageFilePath, model.Image.InputStream, JPPConstants.Images.NewsImageMaxSize, 0, true);
                    }

                    UnitOfWork work = new UnitOfWork();
                    work.SystemRepository.AdminEditNewsItem(id, model);
                    return RedirectToAction("Index");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", "Edit Failed to Save: " + e.Message);
                }
            }

            return View(model);
        }
        /// <summary>
        /// Populates an quest view model with information about a single quest
        /// </summary>
        /// <param name="id">The id of the quest</param>
        /// <param name="work">The Unit of Work for DB access.  If null, one will be created</param>
        /// <returns>Info about a single quest</returns>
        public static QuestViewModel Populate(int id, UnitOfWork work = null)
        {
            if (work == null)
                work = new UnitOfWork();

            bool currentUserEarned = false;
            DateTime? currentUserEarnedDate = null;
            if (WebSecurity.IsAuthenticated)
            {
                quest_instance instance = (from qi in work.EntityContext.quest_instance
                                           where qi.quest_id == id && qi.user_id == WebSecurity.CurrentUserId
                                           select qi).FirstOrDefault();
                if (instance != null)
                {
                    currentUserEarnedDate = instance.completed_date;
                    currentUserEarned = true;
                }
            }

            // Base query
            bool isAuthenticated = WebSecurity.IsAuthenticated;
            int currentUserID = WebSecurity.CurrentUserId;
            bool tracking = isAuthenticated ? (from t in work.EntityContext.quest_tracking where t.user_id == currentUserID && t.quest_id == id select t).Any() : false;
            return(from qt in work.EntityContext.quest_template
                    where qt.id == id
                    select new QuestViewModel()
                    {
                        ID = qt.id,
                        Title = qt.title,
                        Image = qt.icon,
                        Description = qt.description,
                        Threshold = qt.threshold == null ? 0 : qt.threshold.Value,
                        CreationDate = qt.created_date,
                        UserCreated = qt.user_generated,
                        Tracking = tracking,
                        Author = new QuestAuthor()
                                  {
                                      ID = qt.creator.id,
                                      DisplayName = qt.creator.display_name,
                                      Image = qt.creator.image,
                                      IsPlayer = qt.creator.is_player
                                  },
                        State = qt.state,
                        Achievements = from step in qt.quest_achievement_step
                                       select new AssociatedAchievement()
                                       {
                                           ID = step.achievement_id,
                                           Image = step.achievement_template.icon,
                                           Title = step.achievement_template.title
                                       },
                        CurrentUserEarnedDate = currentUserEarnedDate,
                        CurrentUserHasEarned = currentUserEarned
                    }).FirstOrDefault();
        }
        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 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);
        }
        public ActionResult AddQuest(AddQuestViewModel model)
        {
            //Create a new Unit of Work
            UnitOfWork work = new UnitOfWork();
            //Add the current logged in user to the model (They are the ones creating it)
            model.CreatorID = WebSecurity.CurrentUserId;
            model.UserGenerated = false;
            //Make sure the quest has associated achievements
            if (model.SelectedAchievementsList == null || model.SelectedAchievementsList.Count <= 0)
                ModelState.AddModelError(String.Empty, "No Achievements were selected for this quest");

            //Make sure the Threshold value doesn't exceed the number of selected achievements
            if (model.SelectedAchievementsList == null || model.Threshold > model.SelectedAchievementsList.Count)
                ModelState.AddModelError("Threshold", "The Threshold value was greater than the number of achievements selected for this quest.");

            model.Threshold = model.Threshold == null || model.Threshold <= 0 ? model.SelectedAchievementsList.Count : model.Threshold;
            if (model.Icon == null && model.UploadedIcon == null)
                ModelState.AddModelError(String.Empty, "An icon must be selected for this achievement");
            if (model.Title != null)
                if (work.QuestRepository.QuestTitleExists(model.Title))
                    ModelState.AddModelError("", "A quest with that title already exists");
            if (ModelState.IsValid)
            {

                if (model.UploadedIcon != null)
                {
                    String filePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.NewIconUpload);
                    model.Icon = filePath.Replace("~/Content/Images/Icons/", "");
                    model.Icon = model.Icon.Replace(".png", "");
                    JPPImage.Save(Server, filePath, model.UploadedIcon.InputStream, 400, 400, true);
                }
                //Make Sure the Directories Exist
                Utilities.JPPDirectory.CheckAndCreateAchievementAndQuestDirectory(Server);

                //Create the file path and save the image
                model.IconFilePath = Utilities.JPPDirectory.CreateFilePath(JPPDirectory.ImageTypes.QuestIcon);
                if (JPPImage.SaveQuestIcons(model.IconFilePath, model.Icon, false))
                {

                    //Add the Quest
                    work.QuestRepository.AddQuest(model);

                    TempData["Message"] = "Quest: " + model.Title + " successfully created and is in draft mode awaiting approval.";
                    return RedirectToAction("EditQuestList");
                }

            }

            //ModelState was invalid, refrech the Achievements list to prevent NullRefrenceException
            AddQuestViewModel refreshModel = AddQuestViewModel.Populate();
            model.AchievementsList = refreshModel.AchievementsList;
            model.IconList = refreshModel.IconList;

            return View(model);
        }
 public void ApproveQuest(int questID)
 {
     UnitOfWork work = new UnitOfWork();
     work.QuestRepository.ApproveUserQuest(questID);
 }