public void BasicTest()
 {
     using (ValidationScope scope = new ValidationScope())
     {
         scope.Error("Name cannot be empty!");
         scope.Error("Password cannot be empty!");
     }
 }
 public void BasicTestWithSpecifiedThrownException()
 {
     using (ValidationScope scope = new ValidationScope(typeof(InvalidOperationException)))
     {
         scope.Error("Name cannot be empty!");
         scope.Error("Password cannot be empty!");
     }
 }
        public void NestedValidationScopeTest()
        {
            try
            {
                using (ValidationScope scope = new ValidationScope())
                {
                    scope.Error("The organization is invalid!");

                    Log2ErrorsIntoValidationScope();
                }
            }
            catch (ValidationException exp)
            {
                Assert.AreEqual(3, exp.Message.Split(';').Count());
            }
        }
        /// <summary>
        /// Validate data input from client.
        /// </summary>
        /// <param name="userId"></param>
        protected virtual void ValidateDataInputForm(Guid? userId)
        {
            using (ValidationScope validationScope = new ValidationScope())
            {
                int recordCount;

                if (this.OrganizationSelector != null && this.OrganizationSelector.SelectedOrganization == null)
                    validationScope.Error(Resources.OrganizationCannotBeEmpty);

                if (this.TextBoxUserName != null && this.TextBoxUserName.Text.Trim().Length == 0)
                    validationScope.Error(Resources.UserNameCannotBeEmpty);
                else if (this.TextBoxUserName != null)
                {
                    LinqPredicate linqPredicate = new LinqPredicate("UserName=@0 AND UserId!=@1", this.TextBoxUserName.Text, userId.HasValue ? userId.Value : Guid.NewGuid());
                    membershipApi.FindUsers(linqPredicate, null, 0, 1, out recordCount);
                    if (recordCount > 0)
                        validationScope.Error(Resources.DuplicateUserName, this.TextBoxUserName.Text);
                }

                if (this.TextBoxPassword != null && !userId.HasValue && this.TextBoxPassword.Text.Trim().Length == 0)
                    validationScope.Error(Resources.PasswordCannotBeEmpty);

                if (this.TextBoxPassword != null && this.TextBoxPassword.Text.Trim().Length > 0)
                {
                    if (this.TextBoxPassword.Text.Trim() != this.TextBoxConfirmPassword.Text.Trim())
                        validationScope.Error(Resources.PasswordNotEqualToConfirmPassword);
                    else
                    {
                        if (this.TextBoxPassword.Text.Trim().Length < AspNetMembership.MinRequiredPasswordLength)
                            validationScope.Error(Resources.PasswordLengthLessThanRequired, AspNetMembership.MinRequiredPasswordLength);

                        if (!Kit.IsEmpty(AspNetMembership.PasswordStrengthRegularExpression))
                        {
                            Regex regex = new Regex(AspNetMembership.PasswordStrengthRegularExpression, RegexOptions.Compiled);
                            if (!regex.IsMatch(TextBoxPassword.Text.Trim()))
                                validationScope.Error(Resources.PasswordFormatIsInvalid, AspNetMembership.PasswordStrengthRegularExpression);
                        }
                    }
                }

                if (this.TextBoxDisplayName != null && this.TextBoxDisplayName.Text.Trim().Length == 0)
                    validationScope.Error(Resources.DisplayNameCannotBeEmpty);
                else if (this.TextBoxDisplayName != null)
                {
                    LinqPredicate linqPredicate = new LinqPredicate("DisplayName=@0 AND UserId!=@1", this.TextBoxDisplayName.Text, userId.HasValue ? userId.Value : Guid.NewGuid());
                    membershipApi.FindUsers(linqPredicate, null, 0, 1, out recordCount);
                    if (recordCount > 0)
                        validationScope.Error(Resources.DuplicateDisplayName, this.TextBoxDisplayName.Text);
                }
            }
        }
        /// <summary>
        /// Convert propertyValue to IFieldValue interface
        /// </summary>
        /// <param name="extensionDataTypeId"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyValue"></param>
        /// <returns>IFieldValue interface</returns>
        /// <exception cref="NotSupportedException">when propertyValue's type is not supported</exception>
        /// <exception cref="InvalidFieldValueException">When property's value is invalid</exception>
        private IFieldValue ConvertToFieldValueInterface(Guid extensionDataTypeId, string propertyName, object propertyValue)
        {
            using (ValidationScope validationScope = new ValidationScope())
            {
                IFieldValue fieldValue = null;

                try
                {
                    IFieldMetadata fieldMetadata = this.metadataApi.GetField(extensionDataTypeId, propertyName);
                    if (fieldMetadata != null)
                    {
                        fieldValue = ConvertToFieldValueInterface(fieldMetadata, propertyName, propertyValue);
                        fieldMetadata.Validate(fieldValue);
                        if (fieldValue == null || fieldValue.Value == null)
                            fieldValue = fieldMetadata.GetDefaultValue();
                    }
                    else
                        fieldValue = ConvertToFieldValueInterface(null, propertyName, propertyValue);
                }
                catch (InvalidSaaSApplicationException)
                {
                    fieldValue = ConvertToFieldValueInterface(null, propertyName, propertyValue);
                }

                return fieldValue;
            }
        }
        /// <summary>
        /// Push an ValidationScope into current executing thread and return the total number of alive validation scopes in current executing thread.
        /// </summary>
        /// <param name="validationScope"></param>
        internal void Push(ValidationScope validationScope)
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            Stack<ValidationScope> stack = null;
            if (this.validationScopeRefContainer.ContainsKey(threadId))
                stack = this.validationScopeRefContainer[threadId];
            else
            {
                stack = new Stack<ValidationScope>();
                this.validationScopeRefContainer[threadId] = stack;
            }

            stack.Push(validationScope);
        }
        /// <summary>
        /// Validate organization type name and domain.
        /// </summary>
        /// <param name="organizationTypeId"></param>
        protected virtual void ValidateInput(Guid organizationTypeId)
        {
            using (ValidationScope validationScope = new ValidationScope())
            {
                if (Kit.IsEmpty(this.TextBoxName.Text.Trim()))
                    validationScope.Error(Resources.OrganizationTypeNameCannotBeEmpty);
                else
                {
                    OrganizationTypeObject organizationTypeObject = organizationApi.GetOrganizationType(this.TextBoxName.Text.Trim());
                    if (organizationTypeObject != null && organizationTypeObject.OrganizationTypeId != organizationTypeId)
                        validationScope.Error(Resources.DuplicateOrganizationTypeName, this.TextBoxName.Text.Trim());
                }

                if (this.DropDownListDomain != null && Kit.IsEmpty(this.DropDownListDomain.SelectedValue))
                    validationScope.Error(Resources.OrganizationTypeDomainCannotBeEmpty);
            }
        }
        /// <summary>
        /// Save extension field serilized into extension field (ExtensionData)
        /// </summary>
        /// <param name="extensionObject"></param>
        public void Serialize(IExtensionObject extensionObject)
        {
            FieldCollection fieldValues = new FieldCollection();
            IEnumerator<KeyValuePair<string, object>> fieldNameValueEnumerator = extensionObject.GetFieldEnumerator();
            while (fieldNameValueEnumerator.MoveNext())
            {
                KeyValuePair<string, object> fieldNameValuePair = fieldNameValueEnumerator.Current;

                using (ValidationScope validationScope = new ValidationScope())
                {
                    try
                    {
                        IFieldValue fieldValue = ConvertToFieldValueInterface(extensionObject.ExtensionDataTypeId, fieldNameValuePair.Key, fieldNameValuePair.Value);
                        if (fieldValue != null) fieldValues.Add(new FieldNameValuePair(fieldNameValuePair.Key, fieldValue));
                    }
                    catch (InvalidFieldValueException exp)
                    {
                        validationScope.Error(exp.Message);
                    }
                    catch (NotSupportedException exp)
                    {
                        validationScope.Error(exp.Message);
                    }
                }
            }

            StringBuilder output = new StringBuilder();

            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                Indent = true
            };

            using (XmlWriter writer = XmlWriter.Create(output, settings))
            {
                serializer.WriteObject(writer, fieldValues);
            }

            extensionObject.ExtensionData = output.ToString();
        }
        /// <summary>
        /// Save organization business object. 
        /// If organizationObject.Id equals Guid.Empty, it means to save a new organization. 
        /// Otherwise it's updating an existed organization.
        /// </summary>
        /// <param name="organizationObject"></param>
        private void SaveOrganization(OrganizationObject organizationObject)
        {
            try
            {
                Organization organization = null;

                using (TransactionScope transactionScope = new TransactionScope())
                using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
                {
                    using (ValidationScope validationScope = new ValidationScope(true))
                    {
                        // check duplicate organization name
                        int existedOrganizationCount = (from org in ctx.Organizations
                                                        where org.OrganizationName == organizationObject.OrganizationName
                                                             && org.ApplicationId == this.authenticationContext.ApplicationId
                                                             && org.OrganizationId != organizationObject.OrganizationId
                                                        select org).Count();
                        if (existedOrganizationCount > 0)
                            validationScope.Error(Resources.ExistedOrganizationName, organizationObject.OrganizationName);

                        // check duplicate organization code
                        if (!string.IsNullOrEmpty(organizationObject.OrganizationCode))
                        {
                            existedOrganizationCount = (from org in ctx.Organizations
                                                        where org.OrganizationCode == organizationObject.OrganizationCode
                                                             && org.ApplicationId == this.authenticationContext.ApplicationId
                                                             && org.OrganizationId != organizationObject.OrganizationId
                                                        select org).Count();
                            if (existedOrganizationCount > 0)
                                validationScope.Error(Resources.ExistedOrganizationCode, organizationObject.OrganizationCode);
                        }

                        // validate organization type
                        OrganizationTypeObject organizationTypeObject = this.GetOrganizationType(organizationObject.OrganizationTypeId);
                        if (organizationTypeObject == null)
                            validationScope.Error(Resources.InvalidOrganizationTypeID);

                        // validate organization located area
                        if (organizationObject.Hierarchies != null && organizationObject.Hierarchies.Count > 0)
                        {
                            foreach (string hierarchyType in organizationObject.Hierarchies.Keys)
                            {
                                HierarchyDataObject hierarchyDataObject = hierarchyApi.GetHierarchyData(organizationObject.Hierarchies[hierarchyType]);
                                if (hierarchyDataObject == null || !string.Equals(hierarchyDataObject.HierarchyType, hierarchyType, StringComparison.OrdinalIgnoreCase))
                                    validationScope.Error(Resources.InvalidHierarchyAssociatedWithOrganization, hierarchyType, hierarchyDataObject.HierarchyDataId);
                            }
                        }

                        // check circular reference of parent
                        if (organizationObject.ParentOrganizationId.HasValue)
                        {
                            if (organizationObject.OrganizationId == organizationObject.ParentOrganizationId.Value)
                                validationScope.Error(Resources.InvalidParentOrganizationID);

                            if (organizationObject.OrganizationId != organizationObject.ParentOrganizationId.Value)
                            {
                                List<string> existedOrganizationNames = new List<string>();
                                HashSet<Guid> existedOrganizationIds = new HashSet<Guid> { organizationObject.OrganizationId };
                                OrganizationObject parentOrganizationObject = this.GetOrganization(organizationObject.ParentOrganizationId.Value);

                                if (parentOrganizationObject == null)
                                    validationScope.Error(Resources.InvalidParentOrganizationID);
                                else
                                {
                                    this.VerifyStatusAgainstParentOrganization(parentOrganizationObject, organizationObject.Status, organizationObject.OrganizationName, validationScope);

                                    while (parentOrganizationObject != null)
                                    {
                                        existedOrganizationNames.Add(parentOrganizationObject.OrganizationName);
                                        if (existedOrganizationIds.Contains(parentOrganizationObject.OrganizationId))
                                        {
                                            validationScope.Error(Resources.ParentOrganizationCircularReference, FormatCircularOrganizationNames(existedOrganizationNames));
                                            break;
                                        }

                                        existedOrganizationIds.Add(parentOrganizationObject.OrganizationId);
                                        if (!parentOrganizationObject.ParentOrganizationId.HasValue) break;

                                        parentOrganizationObject = this.GetOrganization(parentOrganizationObject.ParentOrganizationId.Value);
                                    }
                                }
                            }
                        }

                        if (organizationObject.OrganizationId == Guid.Empty)
                        {
                            organization = ExtensionObjectFactory.Create<Organization>(organizationObject);
                            organization.OrganizationCode = organizationObject.OrganizationCode;
                            organization.CreatedDate = DateTime.UtcNow;
                            organization.CreatedBy = this.authenticationContext.User.UserId;

                            ctx.Organizations.InsertOnSubmit(organization);
                        }
                        else
                        {
                            organization = ctx.Organizations.FirstOrDefault(org => org.OrganizationId == organizationObject.OrganizationId);
                            if (organization == null)
                                validationScope.Error(Resources.InvalidOrganizationID);

                            organization.ExtensionDataTypeId = organizationObject.ExtensionDataTypeId;

                            if (organization.OrganizationCode != organizationObject.OrganizationCode)
                                validationScope.Error(Resources.CodeCannotUpdate);

                            // update status of all children only when updates status from Enabled to Disabled.
                            if (organizationObject.Status == OrganizationStatus.Disabled && organization.Status == OrganizationStatus.Enabled)
                                UpdateSubOrganizationsStatus(ctx, new[] { organization.OrganizationId }, organizationObject.Status);
                        }
                    }

                    organization.ApplicationId = this.authenticationContext.ApplicationId;
                    organization.OrganizationName = organizationObject.OrganizationName;
                    organization.OrganizationTypeId = organizationObject.OrganizationTypeId;
                    organization.ParentOrganizationId = organizationObject.ParentOrganizationId;
                    organization.Status = organizationObject.Status;
                    organization.Description = organizationObject.Description;
                    organization.LastUpdatedDate = DateTime.UtcNow;
                    organization.LastUpdatedBy = this.authenticationContext.User.UserId;

                    // remove original hierarchies and added new ones
                    if (organizationObject.OrganizationId != Guid.Empty && organization.Hierarchies.Count > 0)
                        ctx.OrganizationsInHierarchies.DeleteAllOnSubmit(organization.Hierarchies);

                    if (organizationObject.Hierarchies != null && organizationObject.Hierarchies.Count > 0)
                    {
                        foreach (string hierarchyType in organizationObject.Hierarchies.Keys)
                        {
                            HierarchyDataObject hierarchyDataObject = hierarchyApi.GetHierarchyData(organizationObject.Hierarchies[hierarchyType]);
                            if (hierarchyDataObject != null)
                            {
                                ctx.OrganizationsInHierarchies.InsertOnSubmit(new OrganizationsInHierarchy
                                {
                                    ApplicationId = authenticationContext.ApplicationId,
                                    HierarchyType = hierarchyType,
                                    HierarchyDataId = organizationObject.Hierarchies[hierarchyType],
                                    Organization = organization,
                                });
                            }
                        }
                    }

                    organization.ParseExtensionPropertiesFrom(organizationObject);

                    ctx.SubmitChanges();
                    transactionScope.Complete();

                    organizationObject.OrganizationId = organization.OrganizationId;
                    organizationObject.CreatedBy = organization.CreatedBy;
                    organizationObject.CreatedDate = organization.CreatedDate;
                    organizationObject.LastUpdatedBy = organization.LastUpdatedBy;
                    organizationObject.LastUpdatedDate = organization.LastUpdatedDate;
                }
            }
            catch (ValidationException)
            {
                throw;
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                throw;
            }
        }
        /// <summary>
        /// Save organization type object.
        /// </summary>
        /// <param name="organizationTypeObject"></param>
        /// <exception cref="ValidationException">etc organization type name does exist.</exception>
        public void Save(OrganizationTypeObject organizationTypeObject)
        {
            Kit.NotNull(organizationTypeObject, "organizationTypeObject");
            Kit.NotNull(organizationTypeObject.Name, "organizationTypeObject.Name");
            if (!this.platformConfiguration.Domains.Select(d => d.Value).Contains(organizationTypeObject.Domain))
                throw new ArgumentException(string.Format(Resources.InvalidOrganizationTypeDomain, organizationTypeObject.Domain), "organizationTypeObject.Domain");

            Kit.NotNull(organizationTypeObject, "organizationTypeObject");
            Kit.NotNull(organizationTypeObject.Name, "organizationTypeObject.Name");
            if (!this.platformConfiguration.Domains.Select(d => d.Value).Contains(organizationTypeObject.Domain))
                throw new ArgumentException(string.Format(Resources.InvalidOrganizationTypeDomain, organizationTypeObject.Domain), "organizationTypeObject.Domain");

            try
            {
                using (TransactionScope ts = new TransactionScope())
                using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
                {
                    OrganizationType organizationType = null;

                    DeleteStatus originalDeleteStatus = DeleteStatus.Deleted;
                    using (ValidationScope validationScope = new ValidationScope(true))
                    {
                        if (ctx.OrganizationTypes.Where(x => x.Name == organizationTypeObject.Name
                            && x.ApplicationId == this.authenticationContext.ApplicationId
                            && x.OrganizationTypeId != organizationTypeObject.OrganizationTypeId).Count() > 0)
                        {
                            validationScope.Error(Resources.ExistedOrganizationTypeName, organizationTypeObject.Name);
                        }

                        if (organizationTypeObject.OrganizationTypeId == Guid.Empty)
                        {
                            organizationType = new OrganizationType { ApplicationId = this.authenticationContext.ApplicationId };
                            ctx.OrganizationTypes.InsertOnSubmit(organizationType);
                        }
                        else
                        {
                            organizationType = ctx.OrganizationTypes.FirstOrDefault(orgType => orgType.OrganizationTypeId == organizationTypeObject.OrganizationTypeId);
                            if (organizationType == null)
                                validationScope.Error(Resources.InvalidOrganizationTypeID);

                            originalDeleteStatus = organizationType.DeleteStatus;
                        }
                    }

                    // set organization type properties.
                    organizationType.Domain = organizationTypeObject.Domain;
                    organizationType.Name = organizationTypeObject.Name;
                    organizationType.Description = organizationTypeObject.Description;
                    organizationType.LastUpdatedDate = DateTime.UtcNow;
                    organizationType.Predefined = organizationTypeObject.Predefined;
                    organizationType.DeleteStatus = organizationTypeObject.DeleteStatus;

                    // if disable an existed organization type
                    if (organizationTypeObject.OrganizationTypeId != Guid.Empty
                        && organizationTypeObject.DeleteStatus == DeleteStatus.Deleted
                        && organizationTypeObject.DeleteStatus != originalDeleteStatus)
                    {
                        // remove the cache copy for disabled organizations.
                        IEnumerable<Guid> disabledOrganizationIds = (from org in ctx.Organizations
                                                                     where org.ApplicationId == this.authenticationContext.ApplicationId
                                                                         && org.OrganizationTypeId == organizationTypeObject.OrganizationTypeId
                                                                         && org.Status != OrganizationStatus.Disabled
                                                                     select org.OrganizationId).ToList();

                        foreach (Guid disabledOrganizationId in disabledOrganizationIds)
                            base.RemoveCache(disabledOrganizationId);

                        // batch disable the organizations by sql command
                        string command = string.Format(CultureInfo.InvariantCulture, "UPDATE {0} SET Status={1} WHERE ApplicationId='{2}' AND OrganizationTypeId='{3}' AND Status<>{1}",
                            ctx.Mapping.GetTable(typeof(Organization)).TableName,
                            (int)OrganizationStatus.Disabled,
                            this.authenticationContext.ApplicationId,
                            organizationTypeObject.OrganizationTypeId);

                        ctx.ExecuteCommand(command);
                    }

                    ctx.SubmitChanges();
                    ts.Complete();

                    organizationTypeObject.OrganizationTypeId = organizationType.OrganizationTypeId;
                    organizationTypeObject.LastUpdatedDate = organizationType.LastUpdatedDate;

                    // remove cache.
                    base.RemoveCache(CacheKey4AllOrganizationTypes);
                }
            }
            catch (ValidationException)
            {
                throw;
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                throw;
            }
        }
        /// <summary>
        /// The method executed add/update depends on whether identity of object is empty or not.
        /// </summary>
        /// <param name="concreteDataObject">The name of concrete data should be unique in a concrete data type.</param>
        public void Save(ConcreteDataObject concreteDataObject)
        {
            Kit.NotNull(concreteDataObject, "concreteDataObject");
            Kit.NotNull(concreteDataObject.Name, "concreteDataObject.Name");
            Kit.NotNull(concreteDataObject.Type, "concreteDataObject.Type");

            using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
            {
                ConcreteData concreteData = ctx.ConcreteDatas.FirstOrDefault(c => c.ApplicationId == authenticationContext.ApplicationId && c.Name == concreteDataObject.Name && c.Type == concreteDataObject.Type);

                // validate whether Name is unique in a concrete type.
                using (ValidationScope validationScope = new ValidationScope())
                {
                    if (concreteData != null && concreteData.ConcreteDataId != concreteDataObject.ConcreteDataId)
                    {
                        validationScope.Error(Resources.DuplicateConcreteDataName, concreteData.Name);
                        return;
                    }
                }

                if (concreteDataObject.ConcreteDataId == Guid.Empty)
                {
                    concreteData = ExtensionObjectFactory.Create<ConcreteData>(concreteDataObject);
                    concreteData.CreatedBy = authenticationContext.User.UserId;
                    concreteData.CreatedDate = DateTime.UtcNow;
                    concreteData.DeleteStatus = DeleteStatus.NotDeleted;

                    ctx.ConcreteDatas.InsertOnSubmit(concreteData);
                }
                else
                {
                    concreteData = ctx.ConcreteDatas.FirstOrDefault(c => c.ApplicationId == authenticationContext.ApplicationId && c.ConcreteDataId == concreteDataObject.ConcreteDataId);
                }

                concreteData.ApplicationId = authenticationContext.ApplicationId;
                concreteData.Type = concreteDataObject.Type;
                concreteData.DeleteStatus = concreteDataObject.DeleteStatus;
                concreteData.Description = concreteDataObject.Description;
                concreteData.Name = concreteDataObject.Name;
                concreteData.Value = concreteDataObject.Value;
                concreteData.LastUpdatedBy = authenticationContext.User.UserId;
                concreteData.LastUpdatedDate = DateTime.UtcNow;
                concreteData.ParseExtensionPropertiesFrom(concreteDataObject);

                ctx.SubmitChanges();

                // set server generated information back to the business object to return.
                concreteDataObject.ConcreteDataId = concreteData.ConcreteDataId;
                concreteDataObject.CreatedBy = concreteData.CreatedBy;
                concreteDataObject.CreatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(concreteData.CreatedDate);
                concreteDataObject.LastUpdatedBy = concreteData.LastUpdatedBy;
                concreteDataObject.LastUpdatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(concreteData.LastUpdatedDate);

                // remove the object from cache.
                base.RemoveCache(concreteDataObject.ConcreteDataId);
            }
        }
 /// <summary>
 /// Validate data input of hierarchy data.
 /// </summary>
 /// <param name="hierarchyDataObjectId"></param>
 protected virtual void ValidateInput(Guid hierarchyDataObjectId)
 {
     using (ValidationScope validationScope = new ValidationScope())
     {
         if (Kit.IsEmpty(this.TextBoxName.Text.Trim()))
             validationScope.Error(Resources.HierarchyDataNameCannotBeEmpty);
         else
         {
             string hierarchyType = authenticationContext.TempVariables["HierarchyType"] as string;
             HierarchyDataObject hierarchyDataObject = hierarchyApi.GetHierarchyData(hierarchyType, this.TextBoxName.Text.Trim());
             if (hierarchyDataObject != null && hierarchyDataObject.HierarchyDataId != hierarchyDataObjectId)
                 validationScope.Error(Resources.DuplicateHierarchyDataName, this.TextBoxName.Text.Trim());
         }
     }
 }
        /// <summary>
        /// Validate whether the organization code, name and type are filled by the user correctly.
        /// Both the organization code and name should be unique in the application.
        /// </summary>
        /// <param name="organizationId"></param>
        protected virtual void ValidateDataInputForm(Guid? organizationId)
        {
            using (ValidationScope validationScope = new ValidationScope())
            {
                OrganizationObject org = null;
                if (this.TextBoxOrganizationCode != null && Kit.IsEmpty(this.TextBoxOrganizationCode.Text))
                    validationScope.Error(Resources.OrganizationCodeCannotBeEmpty);
                else
                {
                    org = organizationApi.GetOrganizationByCode(this.TextBoxOrganizationCode.Text);
                    if ((!organizationId.HasValue && org != null)
                        || (organizationId.HasValue && org != null && org.OrganizationId != organizationId.Value))
                        validationScope.Error(Resources.DuplicateOrganizationCode, this.TextBoxOrganizationCode.Text);
                }

                if (this.TextBoxOrganizationName != null && Kit.IsEmpty(this.TextBoxOrganizationName.Text))
                    validationScope.Error(Resources.OrganizationNameCannotBeEmpty);
                else
                {
                    org = organizationApi.GetOrganizationByCode(this.TextBoxOrganizationName.Text);
                    if ((!organizationId.HasValue && org != null)
                        || (organizationId.HasValue && org != null && org.OrganizationId != organizationId.Value))
                        validationScope.Error(Resources.DuplicateOrganizationName, this.TextBoxOrganizationName.Text);
                }

                if (this.DropDownListOrganizationType != null && Kit.IsEmpty(this.DropDownListOrganizationType.SelectedValue))
                    validationScope.Error(Resources.OrganizationTypeCannotBeEmpty);
            }
        }
 private void ThrowValidationScope()
 {
     using (ValidationScope scope = new ValidationScope(typeof(InvalidOperationException)))
     {
         scope.Error("Name cannot be empty!");
         scope.Error("Password cannot be empty!");
         scope.Throw();
     }
 }
 private void ThrowInvalidProgramException()
 {
     using (ValidationScope scope = new ValidationScope(typeof(InvalidOperationException)))
     {
         throw new InvalidProgramException();
     }
 }
        public void ThrowExceptionInNestedValidationScopeTest()
        {
            try
            {
                using (ValidationScope scope = new ValidationScope())
                {
                    ThrowValidationScope();

                    scope.Error("Error1.");
                    scope.Error("Error2.");
                }
            }
            catch (ValidationException exp)
            {
                string[] errorMessages = exp.Message.Split(';');
                Assert.AreEqual(2, errorMessages.Length);
            }
        }
 /// <summary>
 /// Validate data input
 /// </summary>
 /// <param name="concreteDataObjectId"></param>
 protected virtual void ValidateInput(Guid concreteDataObjectId)
 {
     using (ValidationScope validationScope = new ValidationScope())
     {
         if (Kit.IsEmpty(this.TextBoxName.Text.Trim()))
             validationScope.Error(Resources.ConcreteDataNameCannotBeEmpty);
         else
         {
             ConcreteDataObject concreteDataObject = concreteDataApi.GetByName(authenticationContext.TempVariables["ConcreteDataType"] as string, this.TextBoxName.Text.Trim());
             if (concreteDataObject != null && concreteDataObject.ConcreteDataId != concreteDataObjectId)
                 validationScope.Error(Resources.DuplicateConcreteDataName, this.TextBoxName.Text.Trim());
         }
     }
 }
        /// <summary>
        /// Sends changes that were made to retrieved objects to the underlying database, and specifies the action to be taken if the submission fails.
        /// </summary>
        /// <param name="failureMode">The action to be taken if the submission fails.</param>
        public override void SubmitChanges(ConflictMode failureMode)
        {
            ChangeSet changeSet = this.GetChangeSet();
            IEnumerable<object> entities = changeSet.Inserts.Union(changeSet.Updates);

            using (ValidationScope validationScope = new ValidationScope())
            {
                foreach (object entity in entities)
                {
                    IExtensionObject extensionObject = entity as IExtensionObject;
                    if (extensionObject != null && (extensionObject.HasChanged || extensionObject.ExtensionData == null))
                    {
                        IExtensionObjectSerializer serializer = SpringContext.Current.GetObject<IExtensionObjectSerializer>();
                        serializer.Serialize(extensionObject);
                    }
                }
            }

            base.SubmitChanges(failureMode);
        }
        public void ThrowExceptionInNestedMethodTest()
        {
            using (ValidationScope scope = new ValidationScope())
            {
                scope.Error("Error1.");
                scope.Error("Error2.");

                ThrowInvalidProgramException();
            }
        }
        /// <summary>
        /// Save role business object. 
        /// It does create/update based on roleObject.Id. If id is empty, the method will create a new role object.
        /// If the specified id is invalid, the method will throw an exception.
        /// </summary>
        /// <param name="roleObject">role object</param>
        /// <exception cref="ValidationException">Role name existed in system</exception>
        /// <exception cref="ArgumentException">Role id is invalid</exception>
        public void Save(RoleObject roleObject)
        {
            Kit.NotNull(roleObject, "roleObject");

            using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
            {
                try
                {
                    Role role = null;
                    using (ValidationScope validationScope = new ValidationScope(true))
                    {
                        var duplicateRoleNameCount = (from r in ctx.Roles
                                                      where r.ApplicationId == this.authenticationContext.ApplicationId
                                                         && r.RoleName == roleObject.RoleName
                                                         && r.Domain == roleObject.Domain
                                                         && r.RoleId != roleObject.RoleId
                                                      select r).Count();
                        if (duplicateRoleNameCount > 0)
                            validationScope.Error(Resources.ExistedRoleName, roleObject.RoleName);

                        if (roleObject.RoleId == Guid.Empty)
                        {
                            role = new Role()
                            {
                                ApplicationId = this.authenticationContext.ApplicationId,
                            };

                            ctx.Roles.InsertOnSubmit(role);
                        }
                        else
                        {
                            role = ctx.Roles.FirstOrDefault(r => r.RoleId == roleObject.RoleId);
                            if (role == null)
                                validationScope.Error(Resources.InvalidRoleID, "roleObject");

                            base.RemoveCache(FormatRoleNameCacheKey(role.RoleName));
                            base.RemoveCache(roleObject.RoleId);
                        }
                    }

                    role.Domain = roleObject.Domain;
                    role.RoleName = roleObject.RoleName;
                    role.LoweredRoleName = roleObject.RoleName.ToLowerInvariant();
                    role.Description = roleObject.Description;
                    role.LastUpdatedDate = DateTime.UtcNow;
                    role.Predefined = roleObject.Predefined;

                    ctx.SubmitChanges();
                    roleObject.RoleId = role.RoleId;
                }
                catch (ArgumentException)
                {
                    throw;
                }
                catch (ValidationException)
                {
                    throw;
                }
                catch (Exception exp)
                {
                    Logger.Instance(this).Error(exp);
                    throw;
                }
            }
        }
 private void ValidateInput(Guid roleId)
 {
     using (ValidationScope validationScope = new ValidationScope())
     {
         if (Kit.IsEmpty(this.TextBoxName.Text.Trim()))
             validationScope.Error(Resources.RoleNameCannotBeEmpty);
         else
         {
             var roleObject = roleApi.Get(this.TextBoxName.Text.Trim());
             if (roleObject != null && roleObject.RoleId != roleId)
                 validationScope.Error(Resources.DuplicateRoleName, this.TextBoxName.Text.Trim());
         }
     }
 }
 /// <summary>
 /// Validation on if there specifies parent organization to new created one, the status of new organization must be lower priority than its parent.
 /// Organization status priority: Enabled &gt; Pending &gt; Disabled.
 /// </summary>
 /// <param name="parentOrganizationObject"></param>
 /// <param name="status"></param>
 /// <param name="organizationName"></param>
 /// <param name="validationScope"></param>
 private void VerifyStatusAgainstParentOrganization(OrganizationObject parentOrganizationObject, OrganizationStatus status, string organizationName, ValidationScope validationScope)
 {
     OrganizationStatus parentStatus = parentOrganizationObject.Status;
     if ((int)parentStatus < (int)status)
         validationScope.Error(Resources.OrganizationStatusCannotBeHigherThanParent, parentOrganizationObject.OrganizationName, parentStatus, organizationName, status);
 }
        /// <summary>
        /// Save a hierarchy data object.
        /// </summary>
        /// <param name="hierarchyDataObject"></param>
        public void Save(HierarchyDataObject hierarchyDataObject)
        {
            Kit.NotNull(hierarchyDataObject, "hierarchyDataObject");
            Kit.NotNull(hierarchyDataObject.Name, "hierarchyDataObject.Name");
            Kit.NotNull(hierarchyDataObject.HierarchyType, "hierarchyDataObject.HierarchyType");

            using (MembershipDataContext ctx = DataContextFactory.Create<MembershipDataContext>())
            {
                using (ValidationScope validationScope = new ValidationScope(true))
                {
                    // check whether the hierarchy type of parent equals to current one's
                    if (hierarchyDataObject.ParentHierarchyDataId.HasValue)
                    {
                        HierarchyDataObject parentHierarchyDataObject = this.GetHierarchyData(hierarchyDataObject.ParentHierarchyDataId.Value);
                        if (parentHierarchyDataObject == null)
                            validationScope.Error(Resources.InvalidParentHierarchyDataId);
                    }

                    // whether to check cycle reference on parent hierarchy data id?
                    // TODO:

                    // check duplicate hierarchy data name in a hierarchy type.
                    HierarchyDataObject duplicateHierarchyDataObject = this.GetHierarchyData(hierarchyDataObject.HierarchyType, hierarchyDataObject.Name);
                    if (duplicateHierarchyDataObject != null && duplicateHierarchyDataObject.HierarchyDataId != hierarchyDataObject.HierarchyDataId)
                        validationScope.Error(Resources.DuplicateHierarchyDataName);

                    // check whether the hierarchy type has been changed.
                    if (hierarchyDataObject.HierarchyDataId != Guid.Empty)
                    {
                        var existedHierarchyDataObject = this.GetHierarchyData(hierarchyDataObject.HierarchyDataId);
                        if (existedHierarchyDataObject == null)
                            validationScope.Error(Resources.InvalidHierarchyDataId);

                        if (existedHierarchyDataObject.HierarchyType != hierarchyDataObject.HierarchyType)
                            validationScope.Error(Resources.HierarchyTypeCannotBeChanged);
                    }
                }

                HierarchyData hierarchyData = null;
                if (hierarchyDataObject.HierarchyDataId == Guid.Empty)
                {
                    hierarchyData = ExtensionObjectFactory.Create<HierarchyData>(hierarchyDataObject);
                    hierarchyData.ApplicationId = this.authenticationContext.ApplicationId;
                    hierarchyData.CreatedBy = this.authenticationContext.User.UserId;
                    hierarchyData.CreatedDate = DateTime.UtcNow;

                    ctx.HierarchyDatas.InsertOnSubmit(hierarchyData);
                }
                else
                {
                    hierarchyData = ctx.HierarchyDatas.FirstOrDefault(d => d.HierarchyDataId == hierarchyDataObject.HierarchyDataId);
                }

                hierarchyData.HierarchyType = hierarchyDataObject.HierarchyType;
                hierarchyData.ParentHierarchyDataId = hierarchyDataObject.ParentHierarchyDataId;
                hierarchyData.Code = hierarchyDataObject.Code;
                hierarchyData.Name = hierarchyDataObject.Name;
                hierarchyData.Description = hierarchyDataObject.Description;
                hierarchyData.LastUpdatedBy = this.authenticationContext.User.UserId;
                hierarchyData.LastUpdatedDate = DateTime.UtcNow;

                hierarchyData.ParseExtensionPropertiesFrom(hierarchyDataObject);
                ctx.SubmitChanges();

                hierarchyDataObject.HierarchyDataId = hierarchyData.HierarchyDataId;
                hierarchyDataObject.CreatedBy = hierarchyData.CreatedBy;
                hierarchyDataObject.CreatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(hierarchyData.CreatedDate);
                hierarchyDataObject.LastUpdatedBy = hierarchyData.LastUpdatedBy;
                hierarchyDataObject.LastUpdatedDate = LocalizationUtility.ConvertUtcTimeToClientTime(hierarchyData.LastUpdatedDate);

                base.RemoveCache(hierarchyDataObject.HierarchyDataId);
                base.RemoveCache(hierarchyData.HierarchyType);
            }
        }