private void ValidateObjects(IEnumerable targets)
        {
            //string validationContext = "Immediate";
            RuleSetValidationResult result = Validator.RuleSet.ValidateAllTargets(targets);   //, validationContext);

            List <ResultsHighlightController> resultsHighlightControllers = new List <ResultsHighlightController>();

            resultsHighlightControllers.Add(Frame.GetController <ResultsHighlightController>());
            if (View is DetailView)
            {
                foreach (ListPropertyEditor listPropertyEditor in ((DetailView)View).GetItems <ListPropertyEditor>())
                {
                    //if (listPropertyEditor.Frame.GetController<ResultsHighlightController>() == null) continue;
                    if (listPropertyEditor.Frame == null)
                    {
                        continue;
                    }
                    ResultsHighlightController nestedController = listPropertyEditor.Frame.GetController <ResultsHighlightController>();
                    if (nestedController != null)
                    {
                        resultsHighlightControllers.Add(nestedController);
                    }
                }
            }

            foreach (ResultsHighlightController resultsHighlightController in resultsHighlightControllers)
            {
                //resultsHighlightController.View.ObjectSpace.ModifiedObjects[0]
                resultsHighlightController.ClearHighlighting();
                if (result.State == ValidationState.Invalid)
                {
                    resultsHighlightController.HighlightResults(result);
                }
            }
        }
Example #2
0
        void RuleSetOnValidationCompleted(object sender, ValidationCompletedEventArgs args)
        {
            Validator.RuleSet.ValidationCompleted -= RuleSetOnValidationCompleted;
            var ruleSetValidationResult = new RuleSetValidationResult();
            var validationException     = args.Exception;

            if (validationException != null)
            {
                ruleSetValidationResult = validationException.Result;
            }
            foreach (var modelMemberPasswordScore in _modelMemberPasswordScores)
            {
                var password      = View.ObjectTypeInfo.FindMember(modelMemberPasswordScore.Name).GetValue(View.CurrentObject);
                var passwordScore = PasswordAdvisor.CheckStrength(password + "");
                if (passwordScore < modelMemberPasswordScore.PasswordScore)
                {
                    var messageTemplate  = String.Format(CaptionHelper.GetLocalizedText(XpandValidationModule.XpandValidation, "PasswordScoreFailed"), modelMemberPasswordScore.Name, passwordScore, modelMemberPasswordScore.PasswordScore);
                    var validationResult = Validator.RuleSet.NewRuleSetValidationMessageResult(ObjectSpace, messageTemplate, ContextIdentifier.Save, View.CurrentObject, View.ObjectTypeInfo.Type);
                    ruleSetValidationResult.AddResult(validationResult.Results.First());
                    args.Handled = true;
                }
            }
            if (args.Handled)
            {
                throw validationException ?? new ValidationException(ruleSetValidationResult);
            }
        }
        public void EntaoOPlanejamentoDeFeriasParaOColaboradorColab1Iniciado15072012EstaraAptoASalvar(string colaborador, string dtInicio)
        {
            RuleSetValidationResult rsvr = (new RuleSet()).ValidateTarget(
                PlanejamentoFeriasDic[String.Format("{0}_{1}", colaborador, dtInicio)], DefaultContexts.Save);

            foreach (RuleSetValidationResultItem item in rsvr.Results)
            {
                Assert.AreEqual(ValidationState.Valid, item.State);
            }
        }
Example #4
0
        public void EntaoASolicitacaoDeOrcamentoEstaraAptaASalvar()
        {
            RuleSetValidationResult rsvr = (new RuleSet()).ValidateTarget(
                seotsDic.Last(), DefaultContexts.Save);

            foreach (RuleSetValidationResultItem item in rsvr.Results)
            {
                Assert.AreEqual(ValidationState.Valid, item.State);
            }
        }
Example #5
0
 protected override void OnValidationFail(ValidationCompletedEventArgs validationCompletedEventArgs) {
     base.OnValidationFail(validationCompletedEventArgs);
     if (!validationCompletedEventArgs.Handled) {
         validationCompletedEventArgs.Handled = true;
         var ruleSetValidationResult = new RuleSetValidationResult();
         foreach (var result in validationCompletedEventArgs.Exception.Result.Results.Where(item => GetRuleType(item.Rule)==RuleType.Critical)) {
             ruleSetValidationResult.AddResult(result);
         }
         throw new ValidationException(ruleSetValidationResult.GetFormattedErrorMessage(), ruleSetValidationResult);
     }
 }
        /// <summary>
        /// This method adds imported objects into the required ListView.
        /// </summary>
        /// <typeparam name="T">Any persistent object type supporting the IXPSimpleObject interface.</typeparam>
        /// <param name="count">The count of of objects to be imported.</param>
        /// <param name="importDataDelegate">A function of the ImportDataDelegate type that can create persistent objects.</param>
        /// <param name="customValidateDataDelegate">A function of the ValidateDataDelegate type that can be used to additionally validated created persistent objects. Note that by default, the created objects are already validated using the XAF's Validation system. So, you can set this parameter to null or Nothing in VB.NET</param>
        /// <param name="targetListView">A ListView to which objects will be imported.</param>
        /// <returns>The real count of imported objects.</returns>
        /// Dennis: This method reuses the UnitOfWork/NestedUnitOfWork classes, but it's also correct to use independent (that doesn't belong to a View) ObjectSpace/NestedObjectSpace classes here.
        public int ImportData <T>(int count, ImportDataDelegate <T> importDataDelegate, ValidateDataDelegate <T> customValidateDataDelegate, ListView targetListView) where T : IXPSimpleObject
        {
            if (targetListView == null)
            {
                throw new ArgumentNullException("targetlistView");
            }
            IObjectSpace importObjectSpace = null;
            int          countOK           = 0;

            try {
                importObjectSpace = Application.CreateObjectSpace(targetListView.CollectionSource.ObjectTypeInfo.Type);
                for (int i = 0; i < count; i++)
                {
                    using (IObjectSpace nestedImportObjectSpace = importObjectSpace.CreateNestedObjectSpace()) {
                        PropertyCollectionSource pcs = targetListView.CollectionSource as PropertyCollectionSource;
                        object masterObject          = pcs != null?nestedImportObjectSpace.GetObjectByKey(pcs.MasterObjectType, nestedImportObjectSpace.GetKeyValue(pcs.MasterObject)) : null;

                        T obj = importDataDelegate(nestedImportObjectSpace, masterObject, i);
                        if (obj != null)
                        {
                            bool isValid = false;
                            try {
                                RuleSetValidationResult validationResult = Validator.RuleSet.ValidateTarget(null, obj, new ContextIdentifiers(DefaultContexts.Save.ToString()));
                                isValid = validationResult.State != ValidationState.Invalid && (customValidateDataDelegate != null ? customValidateDataDelegate(obj, masterObject, i) : true);
                                if (isValid)
                                {
                                    nestedImportObjectSpace.CommitChanges();
                                }
                            } catch (Exception) {
                                isValid = false;
                            } finally {
                                if (isValid)
                                {
                                    countOK++;
                                }
                            }
                        }
                    }
                }
                importObjectSpace.CommitChanges();
                targetListView.ObjectSpace.Refresh();
            } catch (Exception commitException) {
                try {
                    importObjectSpace.Rollback();
                } catch (Exception rollBackException) {
                    throw new Exception(String.Format("An exception of type {0} was encountered while attempting to roll back the transaction while importing the data of the {1} type.\nError Message:{2}\nStackTrace:{3}", rollBackException.GetType(), typeof(T), rollBackException.Message, rollBackException.StackTrace), rollBackException);
                }
                throw new UserFriendlyException(String.Format("Importing can't be finished!\nAn exception of type {0} was encountered while importing the data of the {1} type.\nError message = {2}\nStackTrace:{3}\nNo records were imported.", commitException.GetType(), typeof(T), commitException.Message, commitException.StackTrace));
            } finally {
                importObjectSpace.Dispose();
                importObjectSpace = null;
            }
            return(countOK);
        }
Example #7
0
        public void Approve()
        {
            RuleSetValidationResult check_result = Validator.RuleSet.ValidateTarget(this, "Approve");

            if (check_result.State == ValidationState.Invalid)
            {
                throw new ValidationException(check_result);
            }
//            Validator.RuleSet.ValidateTarget(this, "Approve");
            State = TrwPartyState.CONFIRMED;
            ObjectSpace.FindObjectSpaceByObject(this).CommitChanges();
        }
Example #8
0
 protected override void OnValidationFail(ValidationCompletedEventArgs validationCompletedEventArgs)
 {
     base.OnValidationFail(validationCompletedEventArgs);
     if (!validationCompletedEventArgs.Handled)
     {
         validationCompletedEventArgs.Handled = true;
         var ruleSetValidationResult = new RuleSetValidationResult();
         foreach (var result in validationCompletedEventArgs.Exception.Result.Results.Where(item => GetRuleType(item.Rule) == Validation.RuleType.RuleType.Critical))
         {
             ruleSetValidationResult.AddResult(result);
         }
         throw new ValidationException(ruleSetValidationResult.GetFormattedErrorMessage(), ruleSetValidationResult);
     }
 }
Example #9
0
        void SimpleActionOnExecute(object sender, SimpleActionExecuteEventArgs simpleActionExecuteEventArgs)
        {
            if (((ActionBase)sender).Id == "Throw Exception")
            {
                throw new Exception("Exception was thrown");
            }

            var          result          = new RuleSetValidationResult();
            const string messageTemplate = "This exception will not be logged see FeatureCenterWindowsFormsModule ExceptionHandlingWinModuleOnCustomHandleException method ";

            result.AddResult(new RuleSetValidationResultItem(View.CurrentObject, ContextIdentifier.Delete, null,
                                                             new RuleValidationResult(null, this, ValidationState.Invalid,
                                                                                      messageTemplate)));

            throw new ValidationException(messageTemplate, result);
        }
Example #10
0
 private void ObjectSpace_OnObjectDeleting(object sender, ObjectsManipulatingEventArgs e)
 {
     foreach (var o in e.Objects)
     {
         var count = ((XPObjectSpace)ObjectSpace).Session.CollectReferencingObjects(o).Count;
         if (count > 0)
         {
             var result          = new RuleSetValidationResult();
             var messageTemplate = "Cannot be deleted " + count + " references found";
             result.AddResult(new RuleSetValidationResultItem(o, ContextIdentifier.Delete, null,
                                                              new RuleValidationResult(null, this, ValidationState.Invalid,
                                                                                       messageTemplate)));
             throw new ValidationException(messageTemplate, result);
         }
     }
 }
 private void ObjectSpace_OnObjectDeleting(object sender, ObjectsManipulatingEventArgs e)
 {
     foreach (var o in e.Objects)
     {
         var count = ObjectSpace.Session.CollectReferencingObjects(o).Count;
         if (count > 0)
         {
             var result = new RuleSetValidationResult();
             var messageTemplate = "Cannot be deleted " + count + " referemces found";
             result.AddResult(new RuleSetValidationResultItem(o, ContextIdentifier.Delete, null,
                                                              new RuleValidationResult(null, this, false,
                                                                                       messageTemplate)));
             throw new ValidationException(messageTemplate, result);
         }    
     }
     
 }
Example #12
0
 void RuleSetOnValidationCompleted(object sender, ValidationCompletedEventArgs args) {
     Validator.RuleSet.ValidationCompleted -= RuleSetOnValidationCompleted;
     var ruleSetValidationResult = new RuleSetValidationResult();
     var validationException = args.Exception;
     if (validationException != null)
         ruleSetValidationResult = validationException.Result;
     foreach (var modelMemberPasswordScore in _modelMemberPasswordScores) {
         var password = View.ObjectTypeInfo.FindMember(modelMemberPasswordScore.Name).GetValue(View.CurrentObject);
         var passwordScore = PasswordAdvisor.CheckStrength(password +"");
         if (passwordScore<modelMemberPasswordScore.PasswordScore) {
             var messageTemplate = String.Format(CaptionHelper.GetLocalizedText(XpandValidationModule.XpandValidation, "PasswordScoreFailed"), modelMemberPasswordScore.Name, passwordScore, modelMemberPasswordScore.PasswordScore);
             var ruleValidationResult = new RuleValidationResult(null, View.CurrentObject, ValidationState.Invalid, messageTemplate);
             ruleSetValidationResult.AddResult(new RuleSetValidationResultItem(View.CurrentObject, ContextIdentifier.Save, null,ruleValidationResult));
             args.Handled = true;
         }
     }
     if (args.Handled)
         throw validationException??new ValidationException(ruleSetValidationResult);
 }
Example #13
0
        public void InvalidIfNoCounterparty()
        {
            var ccyAUD = ObjectSpace.CreateObject <Currency>();
            var ccyUSD = ObjectSpace.CreateObject <Currency>();

            // create counterparty

            var ft = ObjectSpace.CreateObject <ForexTrade>();

            ft.CalculateEnabled = true;
            ft.PrimaryCcy       = ccyAUD;
            ft.CounterCcy       = ccyUSD;
            ft.Rate             = 0.9M;
            ft.CounterCcyAmt    = 1000;
            ft.ValueDate        = DateTime.Now;

            RuleSetValidationResult result = Validator.RuleSet.ValidateTarget(ObjectSpace, ft, DefaultContexts.Save);

            Assert.AreEqual(ValidationState.Invalid, result.State);
        }
        private void ValidateObjects(IEnumerable targets)
        {
            if (targets == null)
            {
                return;
            }
            ResultsHighlightController resultsHighlightController = Frame.GetController <ResultsHighlightController>();

            if (resultsHighlightController != null)
            {
                RuleSetValidationResult result = Validator.RuleSet.ValidateAllTargets(ObjectSpace, targets, DefaultContexts.Save);
                if (result.ValidationOutcome == ValidationOutcome.Error || result.ValidationOutcome == ValidationOutcome.Warning || result.ValidationOutcome == ValidationOutcome.Information)
                {
                    resultsHighlightController.HighlightResults(result);
                }
                else
                {
                    resultsHighlightController.ClearHighlighting();
                }
            }
        }
        void selectAcception_AcceptingAdmin(object sender, DialogControllerAcceptingEventArgs e)
        {
            Dictionary <string, int> dicLessonCurrentRegNum = new Dictionary <string, int>();
            ObjectSpace         objectSpace = Application.CreateObjectSpace();
            ListView            lv          = ((ListView)((WindowController)sender).Window.View);
            User                u           = (User)SecuritySystem.CurrentUser;
            XPCollection <Role> xpc         = new XPCollection <Role>(u.Roles,
                                                                      new BinaryOperator("Name", "Administrators"));
            XPCollection <Role> xpc2 = new XPCollection <Role>(u.Roles,
                                                               new BinaryOperator("Name", "DataAdmins"));

            if (xpc.Count + xpc2.Count > 0)
            {
                objectSpace.Session.BeginTransaction();

                Student currentStudent;
                Lesson  curLesson;
                Dictionary <string, List <string> > errorstudent = new Dictionary <string, List <string> >();
                int numregok = 0;
                foreach (string studentCode in dicStudentRegDetail.Keys)
                {
                    currentStudent = objectSpace.FindObject <Student>(
                        new BinaryOperator("StudentCode", studentCode));
                    foreach (Lesson lesson in lv.SelectedObjects)
                    {
                        if (!dicLessonCurrentRegNum.ContainsKey(lesson.LessonName))
                        {
                            dicLessonCurrentRegNum[lesson.LessonName] = 0;
                        }
                        //si so chon chua vuot qua
                        if (lesson.NumExpectation > dicLessonCurrentRegNum[lesson.LessonName] + lesson.NumRegistration)
                        {
                            curLesson = objectSpace.FindObject <Lesson>(
                                new BinaryOperator("Oid", lesson.Oid));
                            RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                            {
                                Student       = currentStudent,
                                Lesson        = curLesson,
                                RegisterState = objectSpace.FindObject <RegisterState>(
                                    new BinaryOperator("Code", "SELECTED")),
                                CheckState = objectSpace.FindObject <RegisterState>(
                                    new BinaryOperator("Code", "NOTCHECKED"))
                            };
                            RuleSet ruleSet = new RuleSet();

                            RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                            if (ValidationState.Invalid ==
                                result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                            {
                                if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                {
                                    errorstudent.Add(currentStudent.StudentCode, new List <string>());
                                }
                                if (!errorstudent[currentStudent.StudentCode].Contains(curLesson.Subject.SubjectCode))
                                {
                                    errorstudent[currentStudent.StudentCode].Add(curLesson.Subject.SubjectCode);
                                }
                                regdetail.Delete();
                            }
                            else
                            {
                                numregok++;
                                dicLessonCurrentRegNum[lesson.LessonName]++;
                                regdetail.Save();
                            }
                        }
                        else
                        {
                            if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                            {
                                errorstudent.Add(currentStudent.StudentCode, new List <string>());
                            }
                            if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                            {
                                errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode);
                            }
                        }
                    }
                }
                objectSpace.Session.CommitTransaction();
                PopUpMessage ms = objectSpace.CreateObject <PopUpMessage>();
                if (errorstudent.Count > 0)
                {
                    ms.Title   = "Có lỗi khi chọn nhóm MH đăng ký!";
                    ms.Message = string.Format("Đã chọn được cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                    string strmessage = "Không chọn được nhóm môn học do trùng môn đã đăng ký hoặc hết chỗ: ";
                    foreach (KeyValuePair <string, List <string> > keypair in errorstudent)
                    {
                        strmessage += string.Format("Sinh viên:[{0}] - Môn:[", keypair.Key);
                        foreach (string str in keypair.Value)
                        {
                            strmessage += str + ",";
                        }
                        strmessage  = strmessage.TrimEnd(',');
                        strmessage += "]\r\n";
                    }
                    ms.Message += strmessage;
                }
                else
                {
                    ms.Title   = "Chọn nhóm MH thành công";
                    ms.Message = string.Format("Chọn nhóm MH thành công cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                }
                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView = Application.CreateDetailView(
                    objectSpace, ms);
                svp.TargetWindow        = TargetWindow.NewModalWindow;
                svp.CreatedView.Caption = "Thông báo";
                DialogController dc = Application.CreateController <DialogController>();
                svp.Controllers.Add(dc);

                dc.SaveOnAccept = false;
                Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
            }
        }
Example #16
0
        /// <summary>
        /// Retorna verdeiro se a Rule passada como parâmetro
        /// estiver válida.
        /// </summary>
        /// <param name="entity">Nome da Entidade</param>
        /// <param name="ruleID">ID da Regra</param>
        /// <param name="contextIDs">Identificação do contexto onde a validação será aplicada</param>
        /// <returns>Verdadeiro se a regra estiver válida</returns>
        public static ValidationState GetRuleStateID(BaseObject entity, string ruleID, ContextIdentifiers contextIDs)
        {
            RuleSetValidationResult rsvr = (new RuleSet()).ValidateTarget(entity, contextIDs);

            return(GetResultValidationItemID(rsvr.Results, ruleID).State);
        }
Example #17
0
        /// <summary>
        /// Fires after the next button has been clicked
        /// </summary>
        private bool Validate(XafWizardPage page)
        {
            RuleValidationResult result;
            var validationResults           = new RuleSetValidationResult();
            var usedProperties              = new List <string>();
            var resultsHighlightControllers = new List <ResultsHighlightController> {
                Frame.GetController <ResultsHighlightController>()
            };

            foreach (var item in page.View.GetItems <PropertyEditor>())
            {
                if (item.Control != null && ((Control)item.Control).Visible)
                {
                    usedProperties.Add(item.PropertyName);
                    if (item is ListPropertyEditor)
                    {
                        usedProperties.AddRange(((ListPropertyEditor)item).ListView.Editor.RequiredProperties.Select(property => property.TrimEnd('!')));

                        var nestedController = ((ListPropertyEditor)item).Frame.GetController <ResultsHighlightController>();
                        if (nestedController != null)
                        {
                            resultsHighlightControllers.Add(nestedController);
                        }
                    }
                }
            }

            var modifiedObjects = page.View.ObjectTypeInfo.IsPersistent ? ObjectSpace.ModifiedObjects : new List <object> {
                page.View.CurrentObject
            };

            foreach (var obj in modifiedObjects)
            {
                IList <IRule> rules = Validator.RuleSet.GetRules(obj, ContextIdentifier.Save);
                foreach (IRule rule in rules)
                {
                    bool ruleInUse = rule.UsedProperties.Any(property => usedProperties.Contains(property) || !string.IsNullOrEmpty(usedProperties.Where(p => p.EndsWith(String.Format(".{0}", property))).FirstOrDefault()));

                    string reason;
                    if (ruleInUse && RuleSet.NeedToValidateRule(rule, obj, out reason))
                    {
                        result = rule.Validate(obj);

                        if (result.State == ValidationState.Invalid)
                        {
                            validationResults.AddResult(new RuleSetValidationResultItem(obj, ContextIdentifier.Save, rule, result));
                        }
                    }
                }
            }

            foreach (ResultsHighlightController resultsHighlightController in resultsHighlightControllers)
            {
                resultsHighlightController.ClearHighlighting();
                if (validationResults.State == ValidationState.Invalid)
                {
                    resultsHighlightController.HighlightResults(validationResults);
                }
            }

            return(validationResults.State == ValidationState.Valid);
        }
Example #18
0
        /// <summary>
        /// Fires after the next button has been clicked
        /// </summary>
        private bool Validate(XafWizardPage page)
        {
            if (page == null)
            {
                return(true);
            }
            var validationResults = new RuleSetValidationResult();
            var usedProperties = new List <string>();
            var resultsHighlightControllers = new List <ResultsHighlightController> {
                Frame.GetController <ResultsHighlightController>()
            }.Where(controller => controller != null).ToList();

            foreach (var item in page.View.GetItems <PropertyEditor>())
            {
                if (item.Control != null && ((Control)item.Control).Visible)
                {
                    usedProperties.Add(item.PropertyName);
                    var editor = item as ListPropertyEditor;
                    if (editor != null)
                    {
                        usedProperties.AddRange(editor.ListView.Editor.RequiredProperties.Select(property => property.TrimEnd('!')));

                        var nestedController = editor.Frame.GetController <ResultsHighlightController>();
                        if (nestedController != null)
                        {
                            resultsHighlightControllers.Add(nestedController);
                        }
                    }
                }
            }

            var modifiedObjects = ModifiedObjects(page);

            foreach (var obj in modifiedObjects)
            {
                IList <IRule> rules = Validator.RuleSet.GetRules(obj, ContextIdentifier.Save);
                foreach (IRule rule in rules)
                {
                    bool ruleInUse = rule.UsedProperties.Any(property => usedProperties.Contains(property) || !string.IsNullOrEmpty(usedProperties.FirstOrDefault(p => p.EndsWith(
                                                                                                                                                                      $".{property}"))));
                    string reason;
                    if (ruleInUse && RuleSet.NeedToValidateRule(ObjectSpace, rule, obj, out reason))
                    {
                        var objectSpaceLink = rule as IObjectSpaceLink;
                        if (objectSpaceLink != null)
                        {
                            objectSpaceLink.ObjectSpace = ObjectSpace;
                        }
                        RuleValidationResult result = rule.Validate(obj);
                        if (result.State == ValidationState.Invalid)
                        {
                            validationResults.AddResult(new RuleSetValidationResultItem(obj, ContextIdentifier.Save, rule, result));
                        }
                    }
                }
            }

            foreach (ResultsHighlightController resultsHighlightController in resultsHighlightControllers)
            {
                resultsHighlightController.ClearHighlighting();
                if (validationResults.State == ValidationState.Invalid)
                {
                    resultsHighlightController.HighlightResults(validationResults);
                }
            }

            return(validationResults.State != ValidationState.Invalid);
        }
Example #19
0
        /// <summary>
        /// Fires after the next button has been clicked
        /// </summary>
        /// <param name="sender">Wizard Control</param>
        /// <param name="e">WizardCommandButtonClick EventArgs</param>
        private void WizardControl_NextClick(object sender, WizardCommandButtonClickEventArgs e){
            RuleValidationResult result;
            var validationResults = new RuleSetValidationResult();
            var usedProperties = new List<string>();
            var resultsHighlightControllers = new List<ResultsHighlightController>
                                              {Frame.GetController<ResultsHighlightController>()};

            foreach (PropertyEditor item in ((XafWizardPage) e.Page).View.GetItems<PropertyEditor>()){
                if (((Control) item.Control).Visible){
                    usedProperties.Add(item.PropertyName);
                    if (item is ListPropertyEditor){
                        foreach (string property in ((ListPropertyEditor) item).ListView.Editor.RequiredProperties){
                            usedProperties.Add(property.TrimEnd('!'));
                        }

                        var nestedController =
                            ((ListPropertyEditor) item).Frame.GetController<ResultsHighlightController>();
                        if (nestedController != null){
                            resultsHighlightControllers.Add(nestedController);
                        }
                    }
                }
            }

            foreach (object obj in ObjectSpace.ModifiedObjects){
                IList<IRule> rules = Validator.RuleSet.GetRules(obj, ContextIdentifier.Save);
                foreach (IRule rule in rules){
                    bool ruleInUse = false;
                    foreach (string property in rule.UsedProperties){
                        if (usedProperties.Contains(property)){
                            ruleInUse = true;
                            break;
                        }
                    }

                    if (ruleInUse){
                        result = rule.Validate(obj);
                        if (result.State == ValidationState.Invalid){
                            validationResults.AddResult(new RuleSetValidationResultItem(obj, ContextIdentifier.Save,
                                                                                        rule, result));
                        }
                    }
                }
            }

            foreach (ResultsHighlightController resultsHighlightController in resultsHighlightControllers){
                resultsHighlightController.ClearHighlighting();
                if (validationResults.State == ValidationState.Invalid){
                    resultsHighlightController.HighlightResults(validationResults);
                }
            }

            if (validationResults.State == ValidationState.Invalid){
                e.Handled = true;
            }
        }
Example #20
0
        public void ForexTradeIsValid()
        {
            #region Prepare
            var ccyAUD = ObjectSpace.FindObject <Currency>(CriteriaOperator.Parse("Name = ?", "AUD"));
            var ccyUSD = ObjectSpace.FindObject <Currency>(CriteriaOperator.Parse("Name = ?", "USD"));

            // create counterparty
            var fxCounterparty = ObjectSpace.CreateObject <ForexCounterparty>();
            fxCounterparty.Name = "ANZ";
            var counterparty = ObjectSpace.FindObject <Counterparty>(CriteriaOperator.Parse("Name = ?", "ANZ"));
            if (counterparty == null)
            {
                counterparty      = ObjectSpace.CreateObject <Counterparty>();
                counterparty.Name = "ANZ";
            }
            fxCounterparty.CashFlowCounterparty = counterparty;

            // create accounts
            var usdAccount = ObjectSpace.CreateObject <Account>();
            usdAccount.Name     = "VHA ANZ USD";
            usdAccount.Currency = ccyUSD;

            var audAccount = ObjectSpace.CreateObject <Account>();
            audAccount.Name     = "VHA ANZ AUD";
            audAccount.Currency = ccyAUD;

            // create standard settlement accounts
            var usdSsa = ObjectSpace.CreateObject <ForexStdSettleAccount>();
            usdSsa.Account      = usdAccount;
            usdSsa.Counterparty = fxCounterparty;
            usdSsa.Currency     = ccyUSD;

            var audSsa = ObjectSpace.CreateObject <ForexStdSettleAccount>();
            audSsa.Account      = audAccount;
            audSsa.Counterparty = fxCounterparty;
            audSsa.Currency     = ccyAUD;

            ObjectSpace.CommitChanges();

            #endregion

            #region Act
            // create forex trade 1
            var ft1 = ObjectSpace.CreateObject <ForexTrade>();
            ft1.CalculateEnabled = true;
            ft1.ValueDate        = new DateTime(2013, 12, 31);
            ft1.PrimaryCcy       = ccyAUD;
            ft1.CounterCcy       = ccyUSD;
            ft1.Rate             = 0.9M;
            ft1.CounterCcyAmt    = 1000;
            ft1.Counterparty     = fxCounterparty;

            ObjectSpace.CommitChanges();

            #endregion

            #region Assert
            RuleSetValidationResult result = Validator.RuleSet.ValidateTarget(ObjectSpace, ft1, DefaultContexts.Save);
            Assert.AreEqual(ValidationState.Valid, result.State);
            #endregion
        }
Example #21
0
        private void DefaultRegister_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();

            dicStudentRegDetail = new Dictionary <string, List <string> >();
            Student currentStudent;
            Lesson  curLesson;
            Dictionary <string, List <string> > errorstudent           = new Dictionary <string, List <string> >();
            Dictionary <string, int>            dicLessonCurrentRegNum = new Dictionary <string, int>();
            int     numregok = 0;
            Vacancy vc;
            bool    isConflictTKB = false;

            using (XPCollection <Lesson> newCollectionSource = new XPCollection <Lesson>(objectSpace.Session))
            {
                objectSpace.Session.BeginTransaction();
                foreach (StudentClass studentClass in View.SelectedObjects)
                {
                    newCollectionSource.Criteria = CriteriaOperator.Parse(
                        "ClassIDs like ?", string.Format("%{0}%", studentClass.ClassCode));

                    foreach (Student student in studentClass.Students)
                    {
                        listVacancies  = new List <Vacancy>();
                        currentStudent = objectSpace.FindObject <Student>(
                            new BinaryOperator("StudentCode", student.StudentCode));

                        foreach (Lesson lesson in newCollectionSource)
                        {
                            isConflictTKB = false;
                            if (!dicLessonCurrentRegNum.ContainsKey(lesson.LessonName))
                            {
                                dicLessonCurrentRegNum[lesson.LessonName] = 0;
                            }
                            foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                            {
                                vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                if (Utils.IsConfictTKB(listVacancies, vc))
                                {
                                    isConflictTKB = true;
                                    break;
                                }
                            }

                            if (isConflictTKB)
                            {
                                if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                {
                                    errorstudent.Add(currentStudent.StudentCode, new List <string>());
                                }
                                if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                                {
                                    errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode + "{T}");
                                }
                            }
                            else
                            {
                                //si so chon chua vuot qua
                                if (lesson.NumExpectation > dicLessonCurrentRegNum[lesson.LessonName] + lesson.NumRegistration)
                                {
                                    curLesson = objectSpace.FindObject <Lesson>(
                                        new BinaryOperator("Oid", lesson.Oid));
                                    RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                                    {
                                        Student       = currentStudent,
                                        Lesson        = curLesson,
                                        RegisterState = objectSpace.FindObject <RegisterState>(
                                            new BinaryOperator("Code", "SELECTED")),
                                        CheckState = objectSpace.FindObject <RegisterState>(
                                            new BinaryOperator("Code", "NOTCHECKED"))
                                    };
                                    RuleSet ruleSet = new RuleSet();

                                    RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                                    if (ValidationState.Invalid ==
                                        result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                                    {
                                        if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                        {
                                            errorstudent.Add(currentStudent.StudentCode, new List <string>());
                                        }
                                        if (!errorstudent[currentStudent.StudentCode].Contains(curLesson.Subject.SubjectCode))
                                        {
                                            errorstudent[currentStudent.StudentCode].Add(curLesson.Subject.SubjectCode + "{D}");
                                        }
                                        regdetail.Delete();
                                        //regdetail.Reload();
                                    }
                                    else
                                    {
                                        numregok++;
                                        if (!dicStudentRegDetail.ContainsKey(student.StudentCode))
                                        {
                                            dicStudentRegDetail.Add(student.StudentCode, new List <string>());
                                        }
                                        dicStudentRegDetail[student.StudentCode].Add(curLesson.LessonName);

                                        dicLessonCurrentRegNum[lesson.LessonName]++;
                                        foreach (TkbSemester tkbsem in curLesson.TKBSemesters)
                                        {
                                            vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                            listVacancies.Add(vc);
                                        }
                                        regdetail.Save();
                                    }
                                }
                                else
                                {
                                    if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                    {
                                        errorstudent.Add(currentStudent.StudentCode, new List <string>());
                                    }
                                    if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                                    {
                                        errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode + "{H}");
                                    }
                                }
                            }
                        }
                    }
                }
                objectSpace.Session.CommitTransaction();
                PopUpMessage ms = objectSpace.CreateObject <PopUpMessage>();
                if (errorstudent.Count > 0)
                {
                    ms.Title   = "Có lỗi khi chọn nhóm MH đăng ký!";
                    ms.Message = string.Format("Đã chọn được cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                    string strmessage = "Không chọn được nhóm môn học do trùng môn đã đăng ký, trùng lịch hoặc hết chỗ: ";
                    foreach (KeyValuePair <string, List <string> > keypair in errorstudent)
                    {
                        strmessage += string.Format("Sinh viên:[{0}] - Môn:[", keypair.Key);
                        foreach (string str in keypair.Value)
                        {
                            strmessage += str + ",";
                        }
                        strmessage  = strmessage.TrimEnd(',');
                        strmessage += "]\r\n";
                    }
                    ms.Message += strmessage;
                }
                else
                {
                    ms.Title   = "Chọn nhóm MH thành công";
                    ms.Message = string.Format("Chọn nhóm MH thành công cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                }
                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView = Application.CreateDetailView(
                    objectSpace, ms);
                svp.TargetWindow        = TargetWindow.NewModalWindow;
                svp.CreatedView.Caption = "Thông báo";
                DialogController dc = Application.CreateController <DialogController>();
                svp.Controllers.Add(dc);

                dc.SaveOnAccept = false;
                Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
            }
        }
Example #22
0
        /// <summary>
        /// Fires after the next button has been clicked
        /// </summary>
        private bool Validate(XafWizardPage page) {
            RuleValidationResult result;
            var validationResults = new RuleSetValidationResult();
            var usedProperties = new List<string>();
            var resultsHighlightControllers = new List<ResultsHighlightController> { Frame.GetController<ResultsHighlightController>() };

            foreach (var item in page.View.GetItems<PropertyEditor>()) {
                if (item.Control != null && ((Control)item.Control).Visible) {
                    usedProperties.Add(item.PropertyName);
                    if (item is ListPropertyEditor) {
                        usedProperties.AddRange(((ListPropertyEditor)item).ListView.Editor.RequiredProperties.Select(property => property.TrimEnd('!')));

                        var nestedController = ((ListPropertyEditor)item).Frame.GetController<ResultsHighlightController>();
                        if (nestedController != null) {
                            resultsHighlightControllers.Add(nestedController);
                        }
                    }
                }
            }

            var modifiedObjects = page.View.ObjectTypeInfo.IsPersistent ? ObjectSpace.ModifiedObjects : new List<object> { page.View.CurrentObject };
            foreach (var obj in modifiedObjects) {
                IList<IRule> rules = Validator.RuleSet.GetRules(obj, ContextIdentifier.Save);
                foreach (IRule rule in rules) {
                    bool ruleInUse = rule.UsedProperties.Any(property => usedProperties.Contains(property) || !string.IsNullOrEmpty(usedProperties.Where(p => p.EndsWith(String.Format(".{0}", property))).FirstOrDefault()));

                    string reason;
                    if (ruleInUse && RuleSet.NeedToValidateRule(rule, obj, out reason)) {
                        result = rule.Validate(obj);

                        if (result.State == ValidationState.Invalid) {
                            validationResults.AddResult(new RuleSetValidationResultItem(obj, ContextIdentifier.Save, rule, result));
                        }
                    }
                }
            }

            foreach (ResultsHighlightController resultsHighlightController in resultsHighlightControllers) {
                resultsHighlightController.ClearHighlighting();
                if (validationResults.State == ValidationState.Invalid) {
                    resultsHighlightController.HighlightResults(validationResults);
                }
            }

            return validationResults.State == ValidationState.Valid;
        }
Example #23
0
        void selectAcception_AcceptingAdmin(object sender, DialogControllerAcceptingEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();

            DevExpress.ExpressApp.ListView lv = ((DevExpress.ExpressApp.ListView)((WindowController)sender).Window.View);
            User u = (User)SecuritySystem.CurrentUser;
            XPCollection <Role> xpc = new XPCollection <Role>(u.Roles,
                                                              new BinaryOperator("Name", "Administrators"));
            XPCollection <Role> xpc2 = new XPCollection <Role>(u.Roles,
                                                               new BinaryOperator("Name", "DataAdmins"));

            if (xpc.Count + xpc2.Count > 0)
            {
                objectSpace.Session.BeginTransaction();

                Student currentStudent;
                Lesson  curLesson;
                foreach (string studentCode in listStudentCode)
                {
                    currentStudent = objectSpace.FindObject <Student>(
                        new BinaryOperator("StudentCode", studentCode));
                    foreach (Lesson lesson in lv.SelectedObjects)
                    {
                        curLesson = objectSpace.FindObject <Lesson>(
                            new BinaryOperator("Oid", lesson.Oid));
                        RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                        {
                            Student       = currentStudent,
                            Lesson        = curLesson,
                            RegisterState = objectSpace.FindObject <RegisterState>(
                                new BinaryOperator("Code", "SELECTED")),
                            CheckState = objectSpace.FindObject <RegisterState>(
                                new BinaryOperator("Code", "NOTCHECKED"))
                        };
                        RuleSet ruleSet = new RuleSet();

                        RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                        if (ValidationState.Invalid ==
                            result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                        {
                            regdetail.Delete();
                        }
                        else
                        {
                            regdetail.Save();
                        }
                    }
                }
                objectSpace.Session.CommitTransaction();

                PopUpMessage ms = objectSpace.CreateObject <PopUpMessage>();
                ms.Title   = "Lỗi đăng ký";
                ms.Message = string.Format("Error");
                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView = Application.CreateDetailView(
                    objectSpace, ms);
                svp.TargetWindow        = TargetWindow.NewModalWindow;
                svp.CreatedView.Caption = "Thông báo";
                DialogController dc = Application.CreateController <DialogController>();
                svp.Controllers.Add(dc);

                dc.SaveOnAccept = false;
                Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
                ////               View.ObjectSpace.CommitChanges();
                //View.ObjectSpace.Refresh();
                //ListView view = null;
                //Frame currentFrame = ((ActionBase)sender).Controller.Frame;
                //switch (currentFrame.View.ObjectTypeInfo.Name)
                //{
                //    case "Student":
                //        view = Application.CreateListView(objectSpace,typeof(RegisterDetail),true);
                //        break;
                //}
                //currentFrame.SetView(view);
                //e.Cancel = true;
            }
        }