public void Test_Update_InvalidEntityMustNotUpdate()
        {
            // Create the mock entity
            MockRequiredEntity entity = new MockRequiredEntity();

            entity.TestProperty = "Test1";

            entity.Validator = new ValidateStrategy();


            // Save the entity
            SaveStrategy.New(entity, false).Save(entity);

            // Set the required property to empty
            entity.TestProperty = "";

            Assert.IsFalse(entity.IsValid, "The validator returned true when it should return false.");

            // Update the invalid entity
            bool isValid = UpdateStrategy.New(entity, false).Update(entity);

            Assert.IsFalse(isValid, "The update strategy didn't recognise the entity as invalid.");

            MockRequiredEntity foundEntity = RetrieveStrategy.New <MockRequiredEntity>(false).Retrieve <MockRequiredEntity>("ID", entity.ID);

            Assert.IsNotNull(foundEntity);

            Assert.AreNotEqual(foundEntity.TestProperty, entity.TestProperty, "The entity was updated despite being invalid.");
        }
        public void Test_Save_RemovesUnauthorisedReferences()
        {
            MockEntity entity = new MockEntity();

            entity.ID = Guid.NewGuid();

            MockRestrictedEntity restrictedEntity = new MockRestrictedEntity();

            restrictedEntity.ID = Guid.NewGuid();

            entity.RestrictedEntities = new MockRestrictedEntity[] {
                restrictedEntity
            };

            SaveStrategy.New(restrictedEntity, false).Save(restrictedEntity);
            SaveStrategy.New(entity).Save(entity);

            MockEntity foundEntity = RetrieveStrategy.New <MockEntity>(false).Retrieve <MockEntity>("ID", entity.ID);

            Assert.IsNotNull(foundEntity);

            foundEntity.Activate();

            Assert.AreEqual(0, foundEntity.RestrictedEntities.Length, "Restricted entity wasn't removed from reference property.");
        }
Esempio n. 3
0
        /// <summary>
        /// Authenticates the user with the provided username and password.
        /// </summary>
        /// <param name="username">The username of the user to authenticate.</param>
        /// <param name="password">The unencrypted password of the user to authenticate.</param>
        /// <returns>A value indicating whether the user's credentials are authentic.</returns>
        public bool Authenticate(string username, string password)
        {
            string encryptedPassword = Crypter.EncryptPassword(password);

            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("Username", username);
            parameters.Add("Password", encryptedPassword);

            IRetrieveStrategy strategy = RetrieveStrategy.New <User>(false);

            User user = strategy.Retrieve <User>(parameters);

            bool isAuthenticated = (user != null) &&
                                   user.IsApproved &&
                                   !user.IsLockedOut;

            if (isAuthenticated)
            {
                user.Activate();
                user.LastLoginDate = DateTime.Now;
                UpdateStrategy.New(user, false).Update(user);
            }

            return(isAuthenticated);
        }
Esempio n. 4
0
        static public string ParseSetting(string key)
        {
            if (!Config.Application.Settings.ContainsKey(key))
            {
                return(String.Empty);
            }

            string settingValue = Config.Application.Settings[key].ToString();

            IUser user = null;

            if (HttpContext.Current.Request.IsAuthenticated && AuthenticationState.User != null)
            {
                user = RetrieveStrategy.New <User>().Retrieve <User>(AuthenticationState.User.ID);
            }

            string output = String.Empty;

            if (settingValue != null)
            {
                output = settingValue;
                if (user != null)
                {
                    output = Parse(output, user);
                }

                output = Parse(output);
            }

            return(output);
        }
        public void SendEmail(Exception exception)
        {
            try
            {
                if (new ModeDetector().IsRelease)
                {
                    if (StrategyState.IsInitialized)
                    {
                        UserRole role = RetrieveStrategy.New <UserRole>(false).Retrieve <UserRole>("Name", "Administrator");

                        if (role != null)
                        {
                            ActivateStrategy.New(role, false).Activate(role, "Users");

                            foreach (User user in role.Users)
                            {
                                string subject = "Exception";
                                string message = "An exception occurred...\n";

                                if (HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
                                {
                                    message = "URL:\n"
                                              + HttpContext.Current.Request.Url.ToString() + "\n\n";
                                }

                                if (HttpContext.Current.Request.UrlReferrer != null)
                                {
                                    message = message + "Referrer:\n"
                                              + HttpContext.Current.Request.UrlReferrer.ToString() + "\n\n";
                                }

                                if (HttpContext.Current.Request != null)
                                {
                                    message = message + Environment.NewLine
                                              + "User Agent:"
                                              + HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"] + Environment.NewLine;
                                }

                                message = message + "Site:\n"
                                          + new UrlConverter().ToAbsolute(HttpContext.Current.Request.ApplicationPath) + "\n\n"
                                          + "Time:\n"
                                          + DateTime.Now.ToLongDateString() + " - " + DateTime.Now.ToLongTimeString() + "\n\n"
                                          + "Exception:\n"
                                          + exception.ToString() + "\n\n"
                                          + "(please do not reply to this email)\n";

                                Emailer.New().SendEmail(user, subject, message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.Error("Exception occurred when trying to send error report email.");

                LogWriter.Error(ex);
            }
        }
        public override string GetUserNameByEmail(string email)
        {
            User user = RetrieveStrategy.New <User>().Retrieve <User>("Email", email);

            if (user == null)
            {
                throw new ArgumentException("No user found with the email address: " + email);
            }

            return(user.Username);
        }
        public void Test_CreateStrategy()
        {
            string typeName = "MockEntity";

            IStrategy strategy = new RetrieveStrategy();
            StrategyInfo info = StrategyInfo.ExtractInfo(strategy.GetType())[0];

            IStrategy created = info.New(typeName);

            Assert.IsNotNull(created);

            Assert.AreEqual(strategy.GetType().ToString(), created.GetType().ToString());
        }
        public void Test_CreateStrategy()
        {
            string typeName = "MockEntity";

            IStrategy    strategy = new RetrieveStrategy();
            StrategyInfo info     = StrategyInfo.ExtractInfo(strategy.GetType())[0];

            IStrategy created = info.New(typeName);

            Assert.IsNotNull(created);

            Assert.AreEqual(strategy.GetType().ToString(), created.GetType().ToString());
        }
Esempio n. 9
0
        public void Test_Retrieve_ByUniqueKey()
        {
            TestArticle article = new TestArticle();

            article.ID = Guid.NewGuid();

            DataAccess.Data.Saver.Save(article);

            IRetrieveStrategy strategy = RetrieveStrategy.New <TestArticle>(false);

            IEntity foundArticle = strategy.Retrieve <TestArticle>(article.UniqueKey);

            Assert.IsNotNull(foundArticle, "Test article wasn't retrieved.");
        }
Esempio n. 10
0
        public void Test_Retrieve_ByCustomProperty()
        {
            TestArticle article = new TestArticle();

            article.ID    = Guid.NewGuid();
            article.Title = "Test Title";

            DataAccess.Data.Saver.Save(article);

            IRetrieveStrategy strategy = RetrieveStrategy.New <TestArticle>(false);

            IEntity foundArticle = strategy.Retrieve <TestArticle>("Title", article.Title);

            Assert.IsNotNull(foundArticle, "Test article wasn't retrieved.");
        }
Esempio n. 11
0
        static public string Parse(string text)
        {
            if (text == null || text == String.Empty)
            {
                return(String.Empty);
            }

            Entities.IUser systemAdministrator = RetrieveStrategy.New <User>().Retrieve <User>(Config.Application.PrimaryAdministratorID);

            string newText = text;

            newText = newText.Replace("${WebSite.Title}", Config.Application.Title);
            newText = newText.Replace("${SystemAdministrator.Name}", systemAdministrator.Name);
            return(newText);
        }
Esempio n. 12
0
        public void Test_Delete_Reorder()
        {
            using (LogGroup logGroup = LogGroup.StartDebug("Testing deletion of sub entities to ensure their position is updated."))
            {
                TestArticle article = CreateStrategy.New <TestArticle>(false).Create <TestArticle>();

                article.ID    = Guid.NewGuid();
                article.Title = "Test Article";

                SaveStrategy.New(article, false).Save(article);

                Collection <TestArticlePage> pages = new Collection <TestArticlePage>();

                // Create and save 3 article pages associated with the article
                for (int i = 0; i < 3; i++)
                {
                    TestArticlePage page = CreateStrategy.New <TestArticlePage>(false).Create <TestArticlePage>();
                    page.Article    = article;
                    page.Title      = "Page " + (i + 1);
                    page.ID         = Guid.NewGuid();
                    page.PageNumber = i + 1;

                    pages.Add(page);

                    SaveStrategy.New(page, false).Save(page);
                }

                // Delete the second page (0 based position = 1)
                DeleteStrategy.New(pages[1], false).Delete(pages[1]);

                // Load the article from the store
                TestArticle foundArticle = RetrieveStrategy.New <TestArticle>(false).Retrieve <TestArticle>("ID", article.ID);

                // Activate the pages on the article
                ActivateStrategy.New(foundArticle, false).Activate(foundArticle, "Pages");

                Assert.IsNotNull(foundArticle.Pages, "Pages property isn't set.");

                Assert.AreEqual(2, foundArticle.Pages.Length, "Invalid number of pages.");

                foundArticle.Pages = Collection <TestArticlePage> .Sort(foundArticle.Pages, "PageNumberAscending");

                Assert.AreEqual(1, foundArticle.Pages[0].PageNumber, "First page has wrong number.");
                Assert.AreEqual("Page 1", foundArticle.Pages[0].Title, "First page has wrong title.");
                Assert.AreEqual(2, foundArticle.Pages[1].PageNumber, "Third page has wrong number (should now be 2 as it's moved up one spot).");
                Assert.AreEqual("Page 3", foundArticle.Pages[1].Title, "Third page has wrong title.");                 // Page 3 should now be at position 1 (ie. second place)
            }
        }
        public void Test_Update_AutoActivateReferences()
        {
            // Create the mock entities
            TestUser user = CreateStrategy.New <TestUser>(false).Create <TestUser>();

            user.ID        = Guid.NewGuid();
            user.FirstName = "Test";
            user.LastName  = "User";

            TestRole role = CreateStrategy.New <TestRole>(false).Create <TestRole>();

            role.ID   = Guid.NewGuid();
            role.Name = "Test Role";

            // Assign the user to the role
            user.Roles = new TestRole[] { role };

            // Save the entities
            SaveStrategy.New(role, false).Save(role);
            SaveStrategy.New(user, false).Save(user);

            // Retrieve the mock user from the data store
            TestUser foundUser = RetrieveStrategy.New <TestUser>(false).Retrieve <TestUser>("ID", user.ID);

            // Change a standard property value
            foundUser.FirstName = "Test2";

            // Update WITHOUT having activated the user manually
            // This update should automatically activate the user entity before updating and
            // should therefore persist the references
            UpdateStrategy.New(foundUser, false).Update(foundUser);

            // Retrieve the mock user again
            TestUser foundUser2 = RetrieveStrategy.New <TestUser>(false).Retrieve <TestUser>("ID", user.ID);

            // Manually activate the user
            foundUser2.Activate();

            // Assert that the referenced roles are found on the user which indicates
            // that the update strategy did automatically activate the entity and persist
            // the references
            Assert.IsNotNull(foundUser2.Roles, "Roles property is null.");
            Assert.AreEqual(1, foundUser2.Roles.Length, "Invalid number of roles assigned to user.");
        }
        public void Test_Save_InvalidEntityMustNotSave()
        {
            // Create the mock entity
            MockInvalidEntity entity = new MockInvalidEntity();

            entity.Validator = new ValidateStrategy();

            Assert.IsFalse(entity.IsValid, "The validator returned true when it should return false.");

            // Try to save the entity
            bool isValid = SaveStrategy.New(entity, false).Save(entity);

            // Ensure that the save was rejected
            Assert.IsFalse(isValid, "The save strategy didn't recognise the entity as invalid.");

            // Try loading the entity from the data store to see if it's found
            MockInvalidEntity foundEntity = RetrieveStrategy.New <MockInvalidEntity>(false).Retrieve <MockInvalidEntity>("ID", entity.ID);

            // Ensure the entity wasn't found and therefore wasn't saved
            Assert.IsNull(foundEntity, "The entity was found in the store even though it shouldn't have saved.");
        }
Esempio n. 15
0
        /// <summary>
        /// Updates the user from the form.
        /// </summary>
        public bool Update(User user)
        {
            AutoNavigate = false;

            // Get the original user data
            User originalUser = RetrieveStrategy.New <User>().Retrieve <User>("ID", user.ID);

            // If the password wasn't added then reset it
            if (user.Password == null || user.Password == String.Empty)
            {
                user.Password = originalUser.Password;
            }
            else
            {
                user.Password = Crypter.EncryptPassword(user.Password);
            }

            bool success = base.Update(user);

            // If the current user edited their username then fix their authentication session
            if (originalUser.Username == AuthenticationState.Username &&
                user.Username != AuthenticationState.Username)
            {
                AuthenticationState.Username = user.Username;
            }

            Result.Display(IsSelf
                                       ? Properties.Language.YourAccountUpdated
                                       : Properties.Language.UserUpdated);

            if (success)
            {
                NavigateAfterUpdate();
            }

            return(success);
        }