Beispiel #1
0
        public Env(ValidationList validations, Class owner)
        {
            Contract.Requires(validations != null);

            this.validations = validations;
            Owner = owner;
        }
 public static FormItem<WysiwygHtmlEditor> GetBodyHtmlFormItem( this EmailMessage emailMessage, ValidationList vl, string value = "" )
 {
     return FormItem.Create(
         "Body",
         new WysiwygHtmlEditor( value ),
         validationGetter: control => new EwfValidation( ( pbv, validator ) => emailMessage.BodyHtml = control.GetPostBackValue( pbv ), vl ) );
 }
Beispiel #3
0
        Env(ValidationList validations, Dictionary<String, EnvItem> dictionary)
        {
            Contract.Requires(validations != null);

            this.validations = validations;
            dict = dictionary;
        }
Beispiel #4
0
 protected void AddModelStateValidations(ValidationList validations)
 {
     foreach (var item in validations.GetInvalidItems())
     {
         ModelState.AddModelError(item.Field, item.Error);
     }
 }
Beispiel #5
0
        /// <summary>
        /// Creates a form item with a change based check box list, which is a check box list that is based on changes to the selections rather than the absolute
        /// set of selected items.
        /// </summary>
        /// <typeparam name="ItemIdType"></typeparam>
        /// <param name="label"></param>
        /// <param name="items"></param>
        /// <param name="selectedItemIds"></param>
        /// <param name="modificationMethod">A method that executes the change handlers of the items that were selected or deselected on this post back.</param>
        /// <param name="caption"></param>
        /// <param name="includeSelectAndDeselectAllButtons"></param>
        /// <param name="numberOfColumns"></param>
        /// <param name="uiSelectedItemIds"></param>
        /// <param name="postBack"></param>
        /// <param name="cellSpan"></param>
        /// <param name="textAlignment"></param>
        /// <param name="validationPredicate"></param>
        /// <param name="validationList"></param>
        /// <returns></returns>
        public static FormItem GetFormItem <ItemIdType>(
            FormItemLabel label, IEnumerable <ChangeBasedListItem <ItemIdType> > items, IEnumerable <ItemIdType> selectedItemIds, out Action modificationMethod,
            string caption                = "", bool includeSelectAndDeselectAllButtons = false, byte numberOfColumns = 1, IEnumerable <ItemIdType> uiSelectedItemIds = null,
            PostBack postBack             = null, int?cellSpan = null, TextAlignment textAlignment = TextAlignment.NotSpecified, Func <bool> validationPredicate      = null,
            ValidationList validationList = null)
        {
            var checkBoxList = new ChangeBasedCheckBoxList <ItemIdType>(
                items,
                selectedItemIds,
                caption,
                includeSelectAndDeselectAllButtons,
                numberOfColumns,
                uiSelectedItemIds ?? selectedItemIds,
                postBack);

            modificationMethod = checkBoxList.ModifyData;
            return(FormItem.Create(
                       label,
                       checkBoxList,
                       cellSpan: cellSpan,
                       textAlignment: textAlignment,
                       validationGetter: control => new Validation(
                           (pbv, validator) => {
                if (validationPredicate != null && !validationPredicate())
                {
                    return;
                }
                control.Validate(pbv);
            },
                           validationList ?? EwfPage.Instance.DataUpdate)));
        }
        /// <summary>
        /// Validate person data against a list of specified validation and it will removed invalid data from collection
        /// </summary>
        /// <param name="persons"></param>
        /// <returns></returns>
        public IList <PersonDTO> Validate(IList <PersonDTO> persons)
        {
            List <PersonDTO> toRemove = new List <PersonDTO>();

            Messages = new List <string>();

            foreach (var person in persons)
            {
                _validationList = new ValidationList();
                //_validationList.Add(new LastNameValidation(person));
                _validationList.Add(new GivenNameValidation(person));

                _validationList.Validate();

                if (!_validationList.IsValid)
                {
                    toRemove.Add(person);
                    Messages = Messages.Concat(_validationList.Messages);
                }
            }

            foreach (var itemToBeDeleted in toRemove)
            {
                persons.Remove(itemToBeDeleted);
            }

            return(persons);
        }
        /// <summary>
        /// Sets up client-side logic for user log-in and returns a modification method that logs in a user. Do not call if the system does not implement the
        /// forms-authentication-capable user-management provider.
        /// </summary>
        public static Func <FormsAuthCapableUser> GetLogInMethod(
            Control etherealControlParent, DataValue <string> emailAddress, DataValue <string> password, string emailAddressErrorMessage, string passwordErrorMessage,
            ValidationList vl)
        {
            var utcOffset = new DataValue <string>();

            setUpClientSideLogicForLogIn(etherealControlParent, utcOffset, vl);

            return(() => {
                var errors = new List <string>();

                var user = SystemProvider.GetUser(emailAddress.Value);
                if (user != null)
                {
                    var authenticationSuccessful = false;
                    if (user.SaltedPassword != null)
                    {
                        // Trim the password if it is temporary; the user may have copied and pasted it from an email, which can add white space on the ends.
                        var hashedPassword = new Password(user.MustChangePassword ? password.Value.Trim() : password.Value, user.Salt).ComputeSaltedHash();
                        if (user.SaltedPassword.SequenceEqual(hashedPassword))
                        {
                            authenticationSuccessful = true;
                        }
                    }

                    var strictProvider = SystemProvider as StrictFormsAuthUserManagementProvider;
                    if (strictProvider != null)
                    {
                        strictProvider.PostAuthenticate(user, authenticationSuccessful);

                        // Re-retrieve the user in case PostAuthenticate modified it.
                        user = SystemProvider.GetUser(user.UserId);
                    }

                    if (authenticationSuccessful)
                    {
                        setFormsAuthCookieAndUser(user);
                    }
                    else
                    {
                        errors.Add(passwordErrorMessage);
                    }
                }
                else
                {
                    errors.Add(emailAddressErrorMessage);
                }

                errors.AddRange(verifyTestCookie());
                addStatusMessageIfClockNotSynchronized(utcOffset);

                if (errors.Any())
                {
                    throw new DataModificationException(errors.ToArray());
                }
                return user;
            });
        }
Beispiel #8
0
        public Env(ValidationList validations, Class owner, Env parent)
        {
            Contract.Requires(validations != null);
            Contract.Requires(parent != null);

            this.validations = validations;
            Owner = owner;
            this.parent = parent;
        }
 /// <summary>
 /// Creates a hidden field. Do not pass null for value.
 /// </summary>
 public static void Create(
     Control parent, string value, Action<string> postBackValueHandler, ValidationList vl, out Func<PostBackValueDictionary, string> valueGetter,
     out Func<string> clientIdGetter)
 {
     var control = new EwfHiddenField( value );
     EwfPage.Instance.AddEtherealControl( parent, control );
     new EwfValidation( ( postBackValues, validator ) => postBackValueHandler( control.getPostBackValue( postBackValues ) ), vl );
     valueGetter = control.getPostBackValue;
     clientIdGetter = () => control.ClientID;
 }
        /// <summary>
        /// Creates a hidden field. Do not pass null for value.
        /// </summary>
        public static void Create(
            Control parent, string value, Action <string> postBackValueHandler, ValidationList vl, out Func <PostBackValueDictionary, string> valueGetter,
            out Func <string> clientIdGetter)
        {
            var control = new EwfHiddenField(value);

            EwfPage.Instance.AddEtherealControl(parent, control);
            new EwfValidation((postBackValues, validator) => postBackValueHandler(control.getPostBackValue(postBackValues)), vl);
            valueGetter    = control.getPostBackValue;
            clientIdGetter = () => control.ClientID;
        }
Beispiel #11
0
        static void init()
        {
            DefaultPrinter = new Printer();

            ValidationList = ValidationList.InitFrom(
                File.ReadAllLines(resPath + "validations.en-US.ef"));

            var severities = ValidationList.LoadSeverities(
                File.ReadAllLines(resPath + "severity-normal.ef"));

            ValidationList.UseSeverities(severities);
        }
 // Log-In
 /// <summary>
 /// Gets an email address form item for use on log-in pages. The validation sets this data value to the post back value of the text box, if valid, or adds
 /// the specified error message to the form item.
 /// </summary>
 public static FormItem<EwfTextBox> GetEmailAddressFormItem( this DataValue<string> emailAddress, FormItemLabel label, string errorMessage, ValidationList vl )
 {
     return FormItem.Create(
         label,
         new EwfTextBox( "" ),
         validationGetter:
             control =>
             new EwfValidation(
                 ( pbv, validator ) =>
                 emailAddress.Value =
                 validator.GetEmailAddress( new ValidationErrorHandler( ( v, ec ) => v.NoteErrorAndAddMessage( errorMessage ) ), control.GetPostBackValue( pbv ), false ),
                 vl ) );
 }
 public static FormItem<EwfTextBox> GetSubjectFormItem( this EmailMessage emailMessage, ValidationList vl, string value = "" )
 {
     return FormItem.Create(
         "Subject",
         new EwfTextBox( value ),
         validationGetter: control => new EwfValidation(
                                          ( pbv, validator ) => {
                                              emailMessage.Subject = validator.GetString( new ValidationErrorHandler( "subject" ), control.GetPostBackValue( pbv ), false );
                                              if( Regex.Match( emailMessage.Subject, RegularExpressions.HtmlTag, RegexOptions.IgnoreCase ).Success )
                                                  validator.NoteErrorAndAddMessage( "HTML is not allowed in the subject field." );
                                          },
                                          vl ) );
 }
Beispiel #14
0
 /// <summary>
 /// Gets the validation errors for the defined property.
 /// </summary>
 /// <param name="propertyName"></param>
 /// <returns></returns>
 public string this [string propertyName]
 {
     get
     {
         if (ValidationList.ContainsKey(propertyName))
         {
             return(ValidationList[propertyName]);
         }
         else
         {
             return(null);
         }
     }
 }
Beispiel #15
0
        public static ProcessResult FillProcessResult(ValidationList validations = null)
        {
            if (validations == null)
            {
                return new ProcessResult {
                           Result = ProcessResultEnum.Success
                }
            }
            ;

            return(new ProcessResult
            {
                Result = validations.IsValid ?
                         ProcessResultEnum.Success : ProcessResultEnum.Validation,
                Validations = validations
            });
        }
        /// <summary>
        /// Ejecuta la generación del sello digital.
        /// </summary>
        /// <param name="rutaArchivoLlave">
        /// Ruta del archivo que contiene la llave primaria (.key) en formato DER y encriptada.</param>
        /// <param name="rutaArchivoCertificado">
        /// Ruta del archivo que contiene la llave publica (.cer)</param>
        /// <param name="password">
        /// Contraseña o frase secreta que se necesita para decodificar la llave primaria.</param>
        /// <returns>
        /// Un objeto de tipo Resultado que contiene el xml generado, la cadena original y el sello digital.</returns>
        /// <exception cref="ComprobanteFiscalDigitalException"></exception>
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        public Resultado Generar(string rutaArchivoLlave, string rutaArchivoCertificado, string password)
        {
            _resultado       = new Resultado();
            _stackValidation = new ValidationList();

            ValidarCertificado(rutaArchivoCertificado);

            ConstruirXML();

            ValidarEsquema();

            GenerarCadenaOriginal();

            GenerarSelloDigital(rutaArchivoLlave, password);

            VerificarSelloDigital();

            return(_resultado);
        }
        /// <summary>
        /// Sets up client-side logic for user log-in and returns a modification method that logs in the specified user. Do not call if the system does not
        /// implement the forms-authentication-capable user-management provider.
        /// This method should be called in LoadData. The method returned should be called in an event handler.
        /// </summary>
        public static Action <int> GetSpecifiedUserLogInMethod(ValidationList vl)
        {
            var utcOffset = new DataValue <string>();

            setUpClientSideLogicForLogIn(utcOffset, vl);

            return(userId => {
                var user = SystemProvider.GetUser(userId);
                setFormsAuthCookieAndUser(user);

                var errors = new List <string>();
                errors.AddRange(verifyTestCookie());
                addStatusMessageIfClockNotSynchronized(utcOffset);
                if (errors.Any())
                {
                    throw new DataModificationException(errors.ToArray());
                }
            });
        }
 public ValidationList<IMedia> List(bool isLite, int skip, int top, DataContext context) {
     if (context == null) { context = new DataContext(); }
     var query = context.Medias.Where(x => x.DeletedOn == null);
     List<Media> results;
     if (skip > 0 || top > 0) {
         if (top > 0) {
             if (skip < 0) { skip = 0; }
             results = query.OrderBy(x => x.ID).Skip(skip).Take(top).ToList();
         } else {
             results = query.OrderBy(x => x.ID).Skip(skip).ToList();
         }
     } else {
         results = query.OrderBy(x => x.ID).ToList();
     }
     var finalResult = new ValidationList<IMedia>(new List<IMedia>());
     foreach (var result in results) {
         result.IsLite = isLite;
         finalResult.Source.Add(result);
     }
     return finalResult;
 }
Beispiel #19
0
        protected void AddValueList(string[] fields, string[] columns, int rowIndex)
        {
            dynamic expandoObject     = new ExpandoObject();
            var     validationManager = FileReaderContext.Get <IValidationManager>();
            var     isValid           = true;

            //for loop is used for each column name
            for (var index = 0; index < columns.Length; index++)
            {
                //find column from fields index
                var column = columns[index];
                //find data from fields index
                var data = fields[index];
                //create expando object
                var validationItems = ValidationList.Where(i => i.PropertyName == column).ToArray();
                //if exist a validation for the property
                if (validationItems != null && validationItems.Length > 0)
                {
                    foreach (var validationItem in validationItems)
                    {
                        isValid = validationManager.ValidateData(validationItem.ValidationName, data, validationItem.Parameter);

                        if (!isValid)
                        {
                            var validationError = new ValidationError();
                            validationError.RowNumber         = rowIndex;
                            validationError.ColumnName        = column;
                            validationError.Data              = data;
                            validationError.ValidationMessage = validationItem.ValidationMessage;
                            ErrorList.Add(validationError);
                            expandoObject = null;
                            return;
                        }
                    }
                }
                ((IDictionary <string, object>)expandoObject).Add(column, data);
            }
            ValueList.Add(expandoObject);
            expandoObject = null;
        }
        public PartidasModel CreateSinglePartida(PartidasModel par)
        {
            centroCostoService   = centroCostoService ?? new CentroCostoService();
            partidaService       = partidaService ?? new PartidasService();
            conceptoCostoService = conceptoCostoService ?? new ConceptoCostoService();
            contableService      = contableService ?? new CuentaContableService();
            empresaService       = empresaService ?? new EmpresaService();
            monedaService        = monedaService ?? new  MonedaService();

            IFormatProvider culture    = new CultureInfo("en-US", true);
            string          dateFormat = "MMddyyyy";
            //Counting number of record already exist.
            var counterRecords = partidaService.Count();

            var centroCostos   = centroCostoService.GetAll();
            var conceptoCostos = conceptoCostoService.GetAll();
            var cuentas        = contableService.GetAll();
            var empresa        = empresaService.GetAll();

            var context           = new System.ComponentModel.DataAnnotations.ValidationContext(par, serviceProvider: null, items: null);
            var validationResults = new List <ValidationResult>();

            bool           isValid = Validator.TryValidateObject(par, context, validationResults, true);
            ValidationList rules   = new ValidationList();

            rules.Add(new FTSFOValidation(par, null));
            rules.Add(new FTFCIFOValidation(par, null));
            rules.Add(new COValidation(par, cuentas));
            rules.Add(new CEValidation(par, empresa));
            rules.Add(new CONCEPCOSValidation(par, conceptoCostos));
            rules.Add(new IImporteValidation(par, null));
            if (!rules.IsValid)
            {
                throw new Exception("No se cumple con la entrada de datos y las reglas de negocios");
            }
            par.PA_STATUS_PARTIDA = Convert.ToInt16(BusinessEnumerations.EstatusCarga.POR_APROBAR);
            par.PA_REFERENCIA     = System.DateTime.Now.Date.ToString(dateFormat) + counterRecords;
            return(base.Insert(par, true));
        }
Beispiel #21
0
        public void Example1()
        {
            var age             = 16;
            var consumesAlcohol = true;

            var person = new Person {
                Age = age, ConsumesAlcohol = consumesAlcohol
            };

            IValidationList validationList = new ValidationList
            {
                new Age0OrHigherValidation(person),
                new OnlyAdultsCanConsumeAlcoholValidation(person)
            };

            var alcoholSeller = new AlcoholSeller(validationList);

            Console.WriteLine(alcoholSeller.IsValid);

            foreach (var message in alcoholSeller.Messages)
            {
                Console.WriteLine(message);
            }
        }
Beispiel #22
0
 public void AddRule(IRule rule)
 {
     ValidationList.Add(rule);
 }
        /// <summary>
        /// Call this during LoadData.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="vl"></param>
        /// <param name="availableRoles">Pass a restricted list of <see cref="Role"/>s the user may select. Otherwise, Roles available
        /// in the System Provider are used.</param>
        /// <param name="validationPredicate">If the function returns true, validation continues.</param>
        public void LoadData(int?userId, ValidationList vl, List <Role> availableRoles = null, Func <bool> validationPredicate = null)
        {
            availableRoles = (availableRoles != null ? availableRoles.OrderBy(r => r.Name) : UserManagementStatics.SystemProvider.GetRoles()).ToList();

            user = userId.HasValue ? UserManagementStatics.GetUser(userId.Value, true) : null;
            if (includePasswordControls() && user != null)
            {
                facUser = FormsAuthStatics.GetUser(user.UserId, true);
            }

            Func <bool> validationShouldRun = () => validationPredicate == null || validationPredicate();

            var b = FormItemBlock.CreateFormItemTable(heading: "Security Information");

            b.AddFormItems(
                FormItem.Create(
                    "Email address",
                    new EwfTextBox(user != null ? user.Email : ""),
                    validationGetter: control => new Validation(
                        (pbv, validator) => {
                if (validationShouldRun())
                {
                    Email = validator.GetEmailAddress(new ValidationErrorHandler("email address"), control.GetPostBackValue(pbv), false);
                }
            },
                        vl)));

            if (includePasswordControls())
            {
                var group = new RadioButtonGroup(false);

                var keepPassword = FormItem.Create(
                    "",
                    group.CreateInlineRadioButton(true, label: userId.HasValue ? "Keep the current password" : "Do not create a password"),
                    validationGetter: control => new Validation(
                        (pbv, validator) => {
                    if (!validationShouldRun() || !control.IsCheckedInPostBack(pbv))
                    {
                        return;
                    }
                    if (user != null)
                    {
                        Salt               = facUser.Salt;
                        SaltedPassword     = facUser.SaltedPassword;
                        MustChangePassword = facUser.MustChangePassword;
                    }
                    else
                    {
                        genPassword(false);
                    }
                },
                        vl));

                var generatePassword = FormItem.Create(
                    "",
                    group.CreateInlineRadioButton(false, label: "Generate a " + (userId.HasValue ? "new, " : "") + "random password and email it to the user"),
                    validationGetter: control => new Validation(
                        (pbv, validator) => {
                    if (validationShouldRun() && control.IsCheckedInPostBack(pbv))
                    {
                        genPassword(true);
                    }
                },
                        vl));

                var newPassword      = new DataValue <string>();
                var confirmPassword  = new DataValue <string>();
                var newPasswordTable = EwfTable.Create(style: EwfTableStyle.StandardExceptLayout);
                newPasswordTable.AddItem(
                    new EwfTableItem(
                        "Password",
                        FormItem.Create(
                            "",
                            new EwfTextBox("", masksCharacters: true, disableBrowserAutoComplete: true)
                {
                    Width = Unit.Pixel(200)
                },
                            validationGetter: control => new Validation((pbv, v) => newPassword.Value = control.GetPostBackValue(pbv), vl)).ToControl()));
                newPasswordTable.AddItem(
                    new EwfTableItem(
                        "Password again",
                        FormItem.Create(
                            "",
                            new EwfTextBox("", masksCharacters: true, disableBrowserAutoComplete: true)
                {
                    Width = Unit.Pixel(200)
                },
                            validationGetter: control => new Validation((pbv, v) => confirmPassword.Value = control.GetPostBackValue(pbv), vl)).ToControl()));

                var providePasswordRadio = group.CreateBlockRadioButton(false, label: "Provide a " + (userId.HasValue ? "new " : "") + "password");
                providePasswordRadio.NestedControls.Add(newPasswordTable);
                var providePassword = FormItem.Create(
                    "",
                    providePasswordRadio,
                    validationGetter: control => new Validation(
                        (pbv, validator) => {
                    if (!validationShouldRun() || !control.IsCheckedInPostBack(pbv))
                    {
                        return;
                    }
                    FormsAuthStatics.ValidatePassword(validator, newPassword, confirmPassword);
                    var p              = new Password(newPassword.Value);
                    Salt               = p.Salt;
                    SaltedPassword     = p.ComputeSaltedHash();
                    MustChangePassword = false;
                },
                        vl));

                b.AddFormItems(
                    FormItem.Create("Password", ControlStack.CreateWithControls(true, keepPassword.ToControl(), generatePassword.ToControl(), providePassword.ToControl())));
            }

            b.AddFormItems(
                FormItem.Create(
                    "Role",
                    SelectList.CreateDropDown(
                        from i in availableRoles select SelectListItem.Create(i.RoleId as int?, i.Name),
                        user != null ? user.Role.RoleId as int? : null),
                    validationGetter: control => new Validation(
                        (pbv, validator) => {
                if (validationShouldRun())
                {
                    RoleId = control.ValidateAndGetSelectedItemIdInPostBack(pbv, validator) ?? default(int);
                }
            },
                        vl)));

            Controls.Add(b);
        }
        /// <summary>
        /// Call this during LoadData.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="vl"></param>
        /// <param name="availableRoles">Pass a restricted list of <see cref="Role"/>s the user may select. Otherwise, Roles available 
        /// in the System Provider are used.</param>
        /// <param name="validationPredicate">If the function returns true, validation continues.</param>
        public void LoadData( int? userId, ValidationList vl, List<Role> availableRoles = null, Func<bool> validationPredicate = null )
        {
            availableRoles = ( availableRoles != null ? availableRoles.OrderBy( r => r.Name ) : UserManagementStatics.SystemProvider.GetRoles() ).ToList();

            user = userId.HasValue ? UserManagementStatics.GetUser( userId.Value, true ) : null;
            if( includePasswordControls() && user != null )
                facUser = FormsAuthStatics.GetUser( user.UserId, true );

            Func<bool> validationShouldRun = () => validationPredicate == null || validationPredicate();

            var b = FormItemBlock.CreateFormItemTable( heading: "Security Information" );

            b.AddFormItems(
                FormItem.Create(
                    "Email address",
                    new EwfTextBox( user != null ? user.Email : "" ),
                    validationGetter: control => new EwfValidation(
                                                     ( pbv, validator ) => {
                                                         if( validationShouldRun() )
                                                             Email = validator.GetEmailAddress( new ValidationErrorHandler( "email address" ), control.GetPostBackValue( pbv ), false );
                                                     },
                                                     vl ) ) );

            if( includePasswordControls() ) {
                var group = new RadioButtonGroup( false );

                var keepPassword = FormItem.Create(
                    "",
                    group.CreateInlineRadioButton( true, label: userId.HasValue ? "Keep the current password" : "Do not create a password" ),
                    validationGetter: control => new EwfValidation(
                                                     ( pbv, validator ) => {
                                                         if( !validationShouldRun() || !control.IsCheckedInPostBack( pbv ) )
                                                             return;
                                                         if( user != null ) {
                                                             Salt = facUser.Salt;
                                                             SaltedPassword = facUser.SaltedPassword;
                                                             MustChangePassword = facUser.MustChangePassword;
                                                         }
                                                         else
                                                             genPassword( false );
                                                     },
                                                     vl ) );

                var generatePassword = FormItem.Create(
                    "",
                    group.CreateInlineRadioButton( false, label: "Generate a " + ( userId.HasValue ? "new, " : "" ) + "random password and email it to the user" ),
                    validationGetter: control => new EwfValidation(
                                                     ( pbv, validator ) => {
                                                         if( validationShouldRun() && control.IsCheckedInPostBack( pbv ) )
                                                             genPassword( true );
                                                     },
                                                     vl ) );

                var newPassword = new DataValue<string>();
                var confirmPassword = new DataValue<string>();
                var newPasswordTable = EwfTable.Create( style: EwfTableStyle.StandardExceptLayout );
                newPasswordTable.AddItem(
                    new EwfTableItem(
                        "Password",
                        FormItem.Create(
                            "",
                            new EwfTextBox( "", masksCharacters: true, disableBrowserAutoComplete: true ) { Width = Unit.Pixel( 200 ) },
                            validationGetter: control => new EwfValidation( ( pbv, v ) => newPassword.Value = control.GetPostBackValue( pbv ), vl ) ).ToControl() ) );
                newPasswordTable.AddItem(
                    new EwfTableItem(
                        "Password again",
                        FormItem.Create(
                            "",
                            new EwfTextBox( "", masksCharacters: true, disableBrowserAutoComplete: true ) { Width = Unit.Pixel( 200 ) },
                            validationGetter: control => new EwfValidation( ( pbv, v ) => confirmPassword.Value = control.GetPostBackValue( pbv ), vl ) ).ToControl() ) );

                var providePasswordRadio = group.CreateBlockRadioButton( false, label: "Provide a " + ( userId.HasValue ? "new " : "" ) + "password" );
                providePasswordRadio.NestedControls.Add( newPasswordTable );
                var providePassword = FormItem.Create(
                    "",
                    providePasswordRadio,
                    validationGetter: control => new EwfValidation(
                                                     ( pbv, validator ) => {
                                                         if( !validationShouldRun() || !control.IsCheckedInPostBack( pbv ) )
                                                             return;
                                                         FormsAuthStatics.ValidatePassword( validator, newPassword, confirmPassword );
                                                         var p = new Password( newPassword.Value );
                                                         Salt = p.Salt;
                                                         SaltedPassword = p.ComputeSaltedHash();
                                                         MustChangePassword = false;
                                                     },
                                                     vl ) );

                b.AddFormItems(
                    FormItem.Create( "Password", ControlStack.CreateWithControls( true, keepPassword.ToControl(), generatePassword.ToControl(), providePassword.ToControl() ) ) );
            }

            b.AddFormItems(
                FormItem.Create(
                    "Role",
                    SelectList.CreateDropDown(
                        from i in availableRoles select SelectListItem.Create( i.RoleId as int?, i.Name ),
                        user != null ? user.Role.RoleId as int? : null ),
                    validationGetter: control => new EwfValidation(
                                                     ( pbv, validator ) => {
                                                         if( validationShouldRun() )
                                                             RoleId = control.ValidateAndGetSelectedItemIdInPostBack( pbv, validator ) ?? default ( int );
                                                     },
                                                     vl ) ) );

            Controls.Add( b );
        }
        /// <summary>
        /// Sets up client-side logic for user log-in and returns a modification method that logs in the specified user. Do not call if the system does not
        /// implement the forms-authentication-capable user-management provider.
        /// This method should be called in LoadData. The method returned should be called in an event handler.
        /// </summary>
        public static Action<int> GetSpecifiedUserLogInMethod( Control etherealControlParent, ValidationList vl )
        {
            var utcOffset = new DataValue<string>();
            setUpClientSideLogicForLogIn( etherealControlParent, utcOffset, vl );

            return userId => {
                var user = SystemProvider.GetUser( userId );
                setFormsAuthCookieAndUser( user );

                var errors = new List<string>();
                errors.AddRange( verifyTestCookie() );
                addStatusMessageIfClockNotSynchronized( utcOffset );
                if( errors.Any() )
                    throw new DataModificationException( errors.ToArray() );
            };
        }
Beispiel #26
0
 public Builtins(ValidationList validations)
 {
     this.validations = validations;
 }
		protected Validator()
		{
			ValidationList = new ValidationList();
		}
 public static FormItem <EwfTextBox> GetSubjectFormItem(this EmailMessage emailMessage, ValidationList vl, string value = "")
 {
     return(FormItem.Create(
                "Subject",
                new EwfTextBox(value),
                validationGetter: control => new EwfValidation(
                    (pbv, validator) => {
         emailMessage.Subject = validator.GetString(new ValidationErrorHandler("subject"), control.GetPostBackValue(pbv), false);
         if (Regex.Match(emailMessage.Subject, RegularExpressions.HtmlTag, RegexOptions.IgnoreCase).Success)
         {
             validator.NoteErrorAndAddMessage("HTML is not allowed in the subject field.");
         }
     },
                    vl)));
 }
 /// <summary>
 /// Inicializa una nueva instancia de la clase DPS.ComprobanteFiscalDigital.ComprobanteFiscalDigitalException
 /// con un mensaje de error especificado y una referencia a la excepción interior que es la
 /// causa de esta excepción y una referencia a la pila de validaciones del esquema del archivo
 /// xml.
 /// </summary>
 /// <param name="message">
 /// El mensaje que describe al error.</param>
 /// <param name="innerException">
 /// La excepción que es la causa de la excepción actual, o una referencia nula.</param>
 /// <param name="stackValidation">
 /// La pila de validaciones, resultado de la revision del esquema del archivo xml generado.</param>
 public ComprobanteFiscalDigitalException(string message, Exception innerException, ValidationList stackValidation)
     : this(message, innerException)
 {
     _stackValidation = stackValidation;
 }
        private static void setUpClientSideLogicForLogIn( Control etherealControlParent, DataValue<string> utcOffset, ValidationList vl )
        {
            EwfPage.Instance.PreRender += delegate { setCookie( testCookieName, "No data" ); };

            Func<PostBackValueDictionary, string> utcOffsetHiddenFieldValueGetter; // unused
            Func<string> utcOffsetHiddenFieldClientIdGetter;
            EwfHiddenField.Create(
                etherealControlParent,
                "",
                postBackValue => utcOffset.Value = postBackValue,
                vl,
                out utcOffsetHiddenFieldValueGetter,
                out utcOffsetHiddenFieldClientIdGetter );
            EwfPage.Instance.PreRender +=
                delegate {
                    EwfPage.Instance.ClientScript.RegisterOnSubmitStatement(
                        typeof( UserManagementStatics ),
                        "formSubmitEventHandler",
                        "getClientUtcOffset( '" + utcOffsetHiddenFieldClientIdGetter() + "' )" );
                };
        }
 /// <summary>
 /// Creates a validation with the specified method and adds it to the specified validation list.
 /// </summary>
 /// <param name="method">The method that will be called by the data modification(s) to which this validation is added. Within the method, do not add
 /// modification methods to outside lists; this adds confusion and commonly leads to modification methods being skipped or executing in the wrong order.
 /// </param>
 /// <param name="validationList">The DataModification or BasicValidationList to which this validation will be added.</param>
 public EwfValidation( Action<PostBackValueDictionary, Validator> method, ValidationList validationList )
 {
     this.method = method;
     ( (ValidationListInternal)validationList ).AddValidation( this );
 }
        /// <summary>
        /// Sets up client-side logic for user log-in and returns a modification method that logs in a user. Do not call if the system does not implement the
        /// forms-authentication-capable user-management provider.
        /// </summary>
        public static Func<FormsAuthCapableUser> GetLogInMethod(
            Control etherealControlParent, DataValue<string> emailAddress, DataValue<string> password, string emailAddressErrorMessage, string passwordErrorMessage,
            ValidationList vl)
        {
            var utcOffset = new DataValue<string>();
            setUpClientSideLogicForLogIn( etherealControlParent, utcOffset, vl );

            return () => {
                var errors = new List<string>();

                var user = SystemProvider.GetUser( emailAddress.Value );
                if( user != null ) {
                    var authenticationSuccessful = false;
                    if( user.SaltedPassword != null ) {
                        // Trim the password if it is temporary; the user may have copied and pasted it from an email, which can add white space on the ends.
                        var hashedPassword = new Password( user.MustChangePassword ? password.Value.Trim() : password.Value, user.Salt ).ComputeSaltedHash();
                        if( user.SaltedPassword.SequenceEqual( hashedPassword ) )
                            authenticationSuccessful = true;
                    }

                    var strictProvider = SystemProvider as StrictFormsAuthUserManagementProvider;
                    if( strictProvider != null ) {
                        strictProvider.PostAuthenticate( user, authenticationSuccessful );

                        // Re-retrieve the user in case PostAuthenticate modified it.
                        user = SystemProvider.GetUser( user.UserId );
                    }

                    if( authenticationSuccessful )
                        setFormsAuthCookieAndUser( user );
                    else
                        errors.Add( passwordErrorMessage );
                }
                else
                    errors.Add( emailAddressErrorMessage );

                errors.AddRange( verifyTestCookie() );
                addStatusMessageIfClockNotSynchronized( utcOffset );

                if( errors.Any() )
                    throw new DataModificationException( errors.ToArray() );
                return user;
            };
        }
        void AttemptToStartProcessing(string line)
        {
            debugLogger.Log("attempting to start processing creature due to line: " + line);
            // Apply previous processing, if still active.
            VerifyAndApplyProcessing();

            try
            {
                debugLogger.Log("extracting object name");

                // [20:48:42] You smile at the Adolescent diseased Mountainheart.
                // This regex preserves condition from before WO Rift update, where determiner was not present.
                // This is kept, because WU servers cannot be guaranteed to have been updated by their administrators.
                Match match = Regex.Match(line,
                                          @"You smile at (a|an|the) (?<g>.+)\.|You smile at (?<g>.+)\.",
                                          RegexOptions.IgnoreCase | RegexOptions.Compiled);
                string objectNameWithPrefixes = string.Empty;
                if (match.Success)
                {
                    objectNameWithPrefixes = match.Groups["g"].Value;
                }

                if (GrangerHelpers.HasAgeInName(objectNameWithPrefixes, ignoreCase: true))
                {
                    debugLogger.Log("object assumed to be a creature");
                    var server = playerMan.CurrentServer;
                    var skill  = playerMan.CurrentServerAhSkill;

                    if (grangerSettings.RequireServerAndSkillToBeKnownForSmilexamine &&
                        (server == null || skill == null))
                    {
                        trayPopups.Schedule(
                            "Server or AH skill level unknown for " + playerMan.PlayerName +
                            ". If WA was just started, give it a few seconds. (This check can be disabled in Granger options)", "CAN'T PROCESS CREATURE", 5000);
                        debugLogger.Log(string.Format(
                                            "processing creature cancelled, AH skill or server group unknown for player {0} (skill: {1} ; server: {2}",
                                            playerMan.PlayerName, skill, server));
                    }
                    else
                    {
                        debugLogger.Log("building new creature object and moving to processor");

                        isProcessing        = true;
                        startedProcessingOn = DateTime.Now;
                        verifyList          = new ValidationList();
                        creatureBuffer      = new CreatureBuffer
                        {
                            Name         = GrangerHelpers.ExtractCreatureName(objectNameWithPrefixes),
                            Age          = GrangerHelpers.ExtractCreatureAge(objectNameWithPrefixes),
                            Server       = server,
                            InspectSkill = skill ?? 0,
                        };

                        var fat = GrangerHelpers.TryParseCreatureNameIfLineContainsFat(objectNameWithPrefixes);
                        if (fat != null)
                        {
                            creatureBuffer.SecondaryInfo = CreatureEntity.SecondaryInfoTag.Fat;
                        }

                        var starving = GrangerHelpers.TryParseCreatureNameIfLineContainsStarving(objectNameWithPrefixes);
                        if (starving != null)
                        {
                            creatureBuffer.SecondaryInfo = CreatureEntity.SecondaryInfoTag.Starving;
                        }

                        var diseased = GrangerHelpers.TryParseCreatureNameIfLineContainsDiseased(objectNameWithPrefixes);
                        if (diseased != null)
                        {
                            creatureBuffer.SecondaryInfo = CreatureEntity.SecondaryInfoTag.Diseased;
                        }

                        verifyList.Name = true;
                        debugLogger.Log("finished building");
                    }
                }
                else
                {
                    debugLogger.Log(objectNameWithPrefixes + " was not recognized as a named creature.");
                }
            }
            catch (Exception exception)
            {
                debugLogger.Log("! Granger: error while BeginProcessing, event: " + line, true, exception);
            }
        }
 private string GetVerifyListData(ValidationList verifyList)
 {
     return(string.Format("(name: {0}, Gender: {1}, Parents: {2}, Traits: {3}, CaredBy: {4})",
                          verifyList.Name, verifyList.Gender, verifyList.Parents, verifyList.Traits, verifyList.CaredBy));
 }
Beispiel #35
0
 /// <summary>
 /// Creates a validation with the specified method and adds it to the specified validation list.
 /// </summary>
 /// <param name="method">The method that will be called by the data modification(s) to which this validation is added. Within the method, do not add
 /// modification methods to outside lists; this adds confusion and commonly leads to modification methods being skipped or executing in the wrong order.
 /// </param>
 /// <param name="validationList">The DataModification or BasicValidationList to which this validation will be added.</param>
 public Validation(Action <PostBackValueDictionary, Validator> method, ValidationList validationList)
 {
     this.method = method;
     ((ValidationListInternal)validationList).AddValidation(this);
 }
        private static void setUpClientSideLogicForLogIn(DataValue <string> utcOffset, ValidationList vl)
        {
            EwfPage.Instance.PreRender += delegate { setCookie(testCookieName, "No data"); };

            Func <PostBackValueDictionary, string> utcOffsetHiddenFieldValueGetter;            // unused
            Func <string> utcOffsetHiddenFieldClientIdGetter;

            EwfHiddenField.Create(
                "",
                postBackValue => utcOffset.Value = postBackValue,
                vl,
                out utcOffsetHiddenFieldValueGetter,
                out utcOffsetHiddenFieldClientIdGetter);
            EwfPage.Instance.PreRender +=
                delegate {
                EwfPage.Instance.ClientScript.RegisterOnSubmitStatement(
                    typeof(UserManagementStatics),
                    "formSubmitEventHandler",
                    "getClientUtcOffset( '" + utcOffsetHiddenFieldClientIdGetter() + "' )");
            };
        }
 public static FormItem <WysiwygHtmlEditor> GetBodyHtmlFormItem(this EmailMessage emailMessage, ValidationList vl, string value = "")
 {
     return(FormItem.Create(
                "Body",
                new WysiwygHtmlEditor(value),
                validationGetter: control => new EwfValidation((pbv, validator) => emailMessage.BodyHtml = control.GetPostBackValue(pbv), vl)));
 }
        // Log-In

        /// <summary>
        /// Gets an email address form item for use on log-in pages. The validation sets this data value to the post back value of the text box, if valid, or adds
        /// the specified error message to the form item.
        /// </summary>
        public static FormItem <EwfTextBox> GetEmailAddressFormItem(this DataValue <string> emailAddress, FormItemLabel label, string errorMessage, ValidationList vl)
        {
            return(FormItem.Create(
                       label,
                       new EwfTextBox(""),
                       validationGetter:
                       control =>
                       new EwfValidation(
                           (pbv, validator) =>
                           emailAddress.Value =
                               validator.GetEmailAddress(new ValidationErrorHandler((v, ec) => v.NoteErrorAndAddMessage(errorMessage)), control.GetPostBackValue(pbv), false),
                           vl)));
        }
 /// <summary>
 /// Inicializa una nueva instancia de la clase DPS.ComprobanteFiscalDigital.ComprobanteFiscalDigitalException
 /// con una referencia a la pila de validaciones del esquema del archivo xml.
 /// </summary>
 /// <param name="stackValidation">
 /// La pila de validaciones, resultado de la revision del esquema del archivo xml generado.</param>
 public ComprobanteFiscalDigitalException(ValidationList stackValidation)
     : this()
 {
     _stackValidation = stackValidation;
 }