Beispiel #1
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     if (BaseValidator.IsFormValid(this.components))
     {
         if (rbPay.Checked || rbResive.Checked)
         {
             db = new UnitOfWork();
             DateLayer.Acconting acconting = new DateLayer.Acconting()
             {
                 Amount      = int.Parse(txtAmount.Value.ToString()),
                 CustomerID  = db.customerRepository.GetCustomerIDByName(txtName.Text),
                 TypeID      = (rbResive.Checked) ? 1 : 2,
                 DateTime    = DateTime.Now,
                 Description = txtDescription.Text
             };
             if (AccontID == 0)
             {
                 db.AccontingRepository.Insert(acconting);
             }
             else
             {
                 acconting.ID = AccontID;
                 db.AccontingRepository.Update(acconting);
             }
             db.Save();
             db.Dispose();
             DialogResult = DialogResult.OK;
         }
         else
         {
             RtlMessageBox.Show("لطفا نوع تراکنش را انتخاب کنید ");
         }
     }
 }
Beispiel #2
0
        public static InputData Parse(string[] args)
        {
            if (!BaseValidator.IsNotEmptyArgs(args))
            {
                throw new NullReferenceException("Array of parameters is null"); //81
            }
            if (!BaseValidator.IsCorrectLength(args
                                               , InputData.MinCountParams, InputData.MaxCountParams))
            {
                throw new ArgumentException(
                          "The number of parameters is incorrect. " +
                          "There must be: " + InputData.MinCountParams + " " +
                          "or " + InputData.MaxCountParams);
            }
            if (BaseValidator.DoesFileExist(args[0]))
            {
                throw new FileNotFoundException();
            }

            return(new InputData
            {
                PathToFile = args[0],
                TargetStr = args[1],
                ReplaceStr = args.Length > InputData.MinCountParams ?
                             args[2] : null,
                Mode = args.Length == InputData.MaxCountParams ?
                       InputData.ProgramMode.ReplaceStr :
                       InputData.ProgramMode.SearchStr
            });
        }
Beispiel #3
0
        public void Store(CourseDto courseDto)
        {
            var savedCourse = _courseRepository.GetByName(courseDto.Name);

            BaseValidator.New()
            .When(savedCourse != null && savedCourse.Id != courseDto.Id, Resource.CourseAlreadyExists)
            .TriggersIfExceptionExists();

            var publicoAlvo = _targetAudienceConverter.Converter(courseDto.TargetAudience);

            var course =
                new Course(courseDto.Name, courseDto.Description, courseDto.Hours, publicoAlvo, courseDto.Amount);

            if (courseDto.Id > 0)
            {
                course = _courseRepository.GetById(courseDto.Id);
                course.ChangeName(courseDto.Name);
                course.ChangeAmount(courseDto.Amount);
                course.ChangeHours(courseDto.Hours);
            }

            if (courseDto.Id == 0)
            {
                _courseRepository.Add(course);
            }
        }
Beispiel #4
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     if (BaseValidator.IsFormValid(this.components))
     {
         if (rbPay.Checked || rbRecieve.Checked)
         {
             db = new UnitOfWork();
             DataLayer.Accounting accounting = new DataLayer.Accounting()
             {
                 Amount      = int.Parse(txtAmount.Value.ToString()),
                 CustomerID  = db.CustomerRepository.GetCustomerByName(txtName.Text),
                 TypeID      = (rbRecieve.Checked) ? 1 : 2,
                 DateTitle   = DateTime.Now,
                 Description = txtDescription.Text
             };
             if (AccountId == 0)
             {
                 db.AccountingRepository.Insert(accounting);
                 db.Save();
             }
             else
             {
                 accounting.ID = AccountId;
                 db.AccountingRepository.Update(accounting);
             }
             db.Save();
             db.Dispose();
             DialogResult = DialogResult.OK;
         }
         else
         {
             MessageBox.Show("Please choose the transaction type");
         }
     }
 }
 public IUploadMediaItemRequestParametersBuilder <IMediaResourceUploadRequest> ContentType(string contentType)
 {
     BaseValidator.CheckForNullEmptyAndWhiteSpaceOrThrow(contentType, this.GetType().Name + ".ContentType");
     BaseValidator.CheckForTwiceSetAndThrow(this.contentType, this.GetType().Name + ".ContentType");
     this.contentType = contentType;
     return(this);
 }
Beispiel #6
0
 public bool IsRuleValid(BaseValidator placeHolderValidator, RadioButton userRadio, TextBox userName, RadioButton roleRadio, DropDownList roles)
 {
     if (userRadio.Checked && userName.Text.Trim().Length == 0)
     {
         placeHolderValidator.ErrorMessage = ((string)GetGlobalResourceObject("GlobalResources", "NonemptyUser"));
         placeHolderValidator.IsValid      = false;
         return(false);
     }
     if (roleRadio.Checked && roles.SelectedItem == null)
     {
         placeHolderValidator.ErrorMessage = ((string)GetGlobalResourceObject("GlobalResources", "NonemptyRole"));
         placeHolderValidator.IsValid      = false;
         return(false);
     }
     if (userRadio.Checked)
     {
         string userNameString = userName.Text.Trim();
         if (-1 != userNameString.IndexOf('*'))
         {
             placeHolderValidator.ErrorMessage = ((string)GetGlobalResourceObject("GlobalResources", "InvalidRuleName"));
             placeHolderValidator.IsValid      = false;
             return(false);
         }
     }
     return(true);
 }
 public IUploadMediaItemRequestParametersBuilder <IMediaResourceUploadRequest> ItemName(string itemName)
 {
     BaseValidator.CheckForNullEmptyAndWhiteSpaceOrThrow(itemName, this.GetType().Name + ".ItemName");
     BaseValidator.CheckForTwiceSetAndThrow(this.itemName, this.GetType().Name + ".ItemName");
     this.itemName = itemName;
     return(this);
 }
 public IUploadMediaItemRequestParametersBuilder <IMediaResourceUploadRequest> ItemTemplatePath(string templatePath)
 {
     ItemPathValidator.ValidateItemTemplate(templatePath, this.GetType().Name + ".ItemTemplatePath");
     BaseValidator.CheckForTwiceSetAndThrow(this.itemTemplate, this.GetType().Name + ".ItemTemplatePath");
     this.itemTemplate = templatePath;
     return(this);
 }
        protected virtual void SetUpValidator(BaseValidator validator, MetaColumn column)
        {
            // Set the validation group to match the dynamic control
            validator.ValidationGroup = Host.ValidationGroup;

            if (validator is DynamicValidator)
            {
                SetUpDynamicValidator((DynamicValidator)validator, column);
            }
            else if (validator is RequiredFieldValidator)
            {
                SetUpRequiredFieldValidator((RequiredFieldValidator)validator, column);
            }
            else if (validator is CompareValidator)
            {
                SetUpCompareValidator((CompareValidator)validator, column);
            }
            else if (validator is RangeValidator)
            {
                SetUpRangeValidator((RangeValidator)validator, column);
            }
            else if (validator is RegularExpressionValidator)
            {
                SetUpRegexValidator((RegularExpressionValidator)validator, column);
            }

            validator.ToolTip = validator.ErrorMessage;
            validator.Text    = "*";
        }
 public IUploadMediaItemRequestParametersBuilder <IMediaResourceUploadRequest> ItemDataStream(Stream itemDataStream)
 {
     BaseValidator.CheckNullAndThrow(itemDataStream, this.GetType().Name + ".ItemDataStream");
     BaseValidator.CheckForTwiceSetAndThrow(this.itemDataStream, this.GetType().Name + ".ItemDataStream");
     this.itemDataStream = itemDataStream;
     return(this);
 }
Beispiel #11
0
        protected void  dtgZonasTarifario_Update(Object sender, DataGridCommandEventArgs e)
        {
            string importe = "";

            importe = ((TextBox)e.Item.FindControl("txtKgExcTari")).Text;
            BaseValidator          valImporteExcTar = (RegularExpressionValidator)((PlaceHolder)e.Item.FindControl("phValidKgExcTari")).FindControl("valImporteExcTar");
            RequiredFieldValidator reqImporteExcTar = (RequiredFieldValidator)((PlaceHolder)e.Item.FindControl("phValidKgExcTari")).FindControl("reqImporteExcTar");

            valImporteExcTar.Enabled = true;
            reqImporteExcTar.Enabled = true;
            valImporteExcTar.Validate();
            reqImporteExcTar.Validate();
            if (!valImporteExcTar.IsValid || !reqImporteExcTar.IsValid)
            {
                return;
            }
            int key = Convert.ToInt32(dtgZonasTarifario.DataKeys[(int)e.Item.ItemIndex]);
            ITarifarioFleteZona oTariZona = tariFlete.ZonasCol.GetTarifarioFleteZonaByFleteZonaID(key);

            oTariZona.ImporteKgExcedente = Convert.ToDouble(importe);
            // Asignamos el usuario que está efectuando la acción.
            IUsuarios usuarioConectato = UsuariosFactory.GetUsuario();

            usuarioConectato.Login = this.usuarioConectadoID;
            usuarioConectato.ConsultarByLogin();

            oTariZona.Guardar(usuarioConectato.UsuarioID);
            dtgZonasTarifario.EditItemIndex = -1;
            this.BindGridZonasTarif(0);
            this.SetearPorTarifarioReferencia();

            this.chkZonasTarifTodas.Checked = false;
        }
Beispiel #12
0
 private void btnSubmit_Click(object sender, EventArgs e)
 {
     if (BaseValidator.IsFormValid(this.components))
     {
         string IMGName = Guid.NewGuid().ToString() + Path.GetExtension(pcCustomer.ImageLocation);
         string path    = Application.StartupPath + "/Images/";
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
         }
         pcCustomer.Image.Save(path + IMGName);
         CustomerTB customer = new CustomerTB()
         {
             Address     = txtAddress.Text,
             Email       = txtEmail.Text,
             Phone       = txtPhone.Text,
             FullName    = txtName.Text,
             CustomerIMG = IMGName
         };
         if (customerID == 0)
         {
             db.customerRepository.InsertCustomer(customer);
         }
         else
         {
             customer.CustomerID = customerID;
             db.customerRepository.UpdateCustomer(customer);
         }
         db.Save();
         DialogResult = DialogResult.OK;
     }
 }
Beispiel #13
0
        public frmEdituser()
        {
            InitializeComponent();
            btnhuy.Click += (s, e) => { Close(); };
            FormClosed   += (s, e) => { swapform?.Invoke(null, null); };

            BaseValidator.ClearList();

            RegexValidator rVusername = new RegexValidator();

            rVusername.Target       = txtUusername;
            rVusername.Pattern      = "^[a-z0-9_.-]+$";
            rVusername.ErrorMessage = "Tên tài khoản chỉ được trong [1-9]-[a-z]-[_,.,-]";

            RegexValidator rVpassword = new RegexValidator();

            rVpassword.Target       = txtUpassword;
            rVpassword.Pattern      = "^[a-z0-9]{3,}$";
            rVpassword.ErrorMessage = "Mật khẩu chỉ được trong [a-z]-[1-9] và > 3 ký tự";

            EmptyValidator rVname = new EmptyValidator();

            rVname.Target       = txtUname;
            rVname.ErrorMessage = "Tên người dùng không được rỗng";

            DOBValidator rVdob = new DOBValidator();

            rVdob.Target       = dtpDOB;
            rVdob.ErrorMessage = "Ngày tháng không hợp lệ";

            Load += FrmEdituser_Load;
            cbbper.SelectedIndexChanged += cbbper_SelectedIndexChanged;
            btnsua.Click += btnSua_Click;
        }
Beispiel #14
0
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            using (UnitofWork db = new UnitofWork())
            {
                if (BaseValidator.IsFormValid(this.components))
                {
                    DataLayer.Product product = new DataLayer.Product()
                    {
                        ProductName = TxtProductName.Text,
                        Unit        = TxtUnit.Text,
                        QTY         = int.Parse(NumQTY.Value.ToString()),
                        Price       = int.Parse(NumPrice.Value.ToString())
                    };
                    if (IsEdit == false)
                    {
                        db.ProductRepository.Insert(product);
                    }
                    else
                    {
                        int id = Convert.ToInt32(MydataGridView.CurrentRow.Cells[0].Value.ToString());

                        product.ProductID = id;
                        db.ProductRepository.Update(product);
                    }
                }
                db.Save();

                DialogResult = DialogResult.OK;
                bindgrid();
            }
        }
 private void btnsave_Click(object sender, EventArgs e)
 {
     if (BaseValidator.IsFormValid(this.components))
     {
         using (MainContext db = new MainContext())
         {
             string imagename = Guid.NewGuid().ToString() + Path.GetExtension(pictureBox1.ImageLocation);
             string path      = Application.StartupPath + "/Images/";
             if (!Directory.Exists(path))
             {
                 Directory.CreateDirectory(path);
             }
             pictureBox1.Image.Save(path + imagename);
             Customers customer = new Customers()
             {
                 FullName      = txtname.Text,
                 Address       = txtaddress.Text,
                 Email         = txtemail.Text,
                 Mobile        = txtmobile.Text,
                 CustomerImage = imagename
             };
             if (customerID == 0)
             {
                 db.CustomerRepository.InsertCustomer(customer);
             }
             else
             {
                 var editcustomer = db.CustomerRepository.GetCustomerById(customerID);
                 db.CustomerRepository.UpdateCustomer(editcustomer);
             }
             db.Save();
         }
         DialogResult = DialogResult.OK;
     }
 }
Beispiel #16
0
        private void AdjustSelectedInvoice(AdjustInputDetails adjustInputDetails)
        {
            BaseValidator validator = new BaseValidator();

            if (!validator.AdjustInvoice(adjustInputDetails))
            {
                ShowError(validator.ClientException, AdjustLineItemError);
                return;
            }
            MessageBoxResult msgResult;

            if (userdata.IsMultipleLineItemAdjust)
            {
                msgResult = MessageBox.Show("Are you sure you want to adjust this line items?", "Adjustment Confirmation", MessageBoxButton.OKCancel);
            }
            else
            {
                msgResult = MessageBox.Show("Are you sure you want to adjust these line item?", "Adjustment Confirmation", MessageBoxButton.OKCancel);
            }

            if (msgResult == MessageBoxResult.Cancel)
            {
                EnableApplicationBar();
                return;
            }

            string postData = JsonConvert.SerializeObject(adjustInputDetails);

            try
            {
                ServiceInvoker.InvokeServiceUsingPost("api/t360/LineItem/AdjustLineItems", postData, false, delegate(object a, ServiceEventArgs serviceEventArgs)
                {
                    ServiceResponse result = serviceEventArgs.Result;
                    if (result.Status)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            EnableApplicationBar();
                            NavigationService.GoBack();
                        });
                    }
                    else
                    {
                        List <Error> resultError = result.ErrorDetails;
                        ShowError(new AppException(resultError), AdjustLineItemError);
                        if (resultError[0] != null && T360ErrorCodes.NotInReviewerQueue == resultError[0].Code)
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                RedirectToInvoiceList();
                            });
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ShowError((AppException)ex);
            }
        }
Beispiel #17
0
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (BaseValidator.IsFormValid(this.components))
            {
                if (RbtnIncome.Checked || RbtnOutgoing.Checked)
                {
                    db = new UnitofWork();
                    DataLayer.Accounting accounting = new DataLayer.Accounting()
                    {
                        Amount      = int.Parse(NumericAmount.Value.ToString()),
                        TypeID      = (RbtnIncome.Checked) ? 1 : 2,
                        CustomerID  = db.CustomerRepository.GetCustomerIdByName(TxtName.Text),
                        Description = TxtDecription.Text,
                        Datetime    = DateTime.Now
                    };
                    if (AccountId == 0)
                    {
                        db.accountingrepository.Insert(accounting);
                    }
                    else
                    {
                        accounting.AccID = AccountId;
                        db.accountingrepository.Update(accounting);
                    }

                    db.Save();
                    db.Dispose();
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    RtlMessageBox.Show("لطفا نوع تراکنش را انتخاب کنید");
                }
            }
        }
Beispiel #18
0
        /// <include file='doc\BaseValidatorDesigner.uex' path='docs/doc[@for="BaseValidatorDesigner.GetDesignTimeHtml"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Gets the design time HTML of ValidatorBase controls.
        ///    </para>
        /// </devdoc>
        public override string GetDesignTimeHtml()
        {
            BaseValidator bv = (BaseValidator)Component;

            // Set to false to force a render
            bv.IsValid = false;

            // Put in dummy text if required
            string           originalText     = bv.ErrorMessage;
            ValidatorDisplay validatorDisplay = bv.Display;
            bool             blank            = (validatorDisplay == ValidatorDisplay.None || (originalText.Trim().Length == 0 && bv.Text.Trim().Length == 0));

            if (blank)
            {
                bv.ErrorMessage = "[" + bv.ID + "]";
                bv.Display      = ValidatorDisplay.Static;
            }

            string html = base.GetDesignTimeHtml();

            // Reset the control state
            if (blank)
            {
                bv.ErrorMessage = originalText;
                bv.Display      = validatorDisplay;
            }

            return(html);
        }
Beispiel #19
0
        public static List <string> Validate(string passwortA, string passwortB)
        {
            var messages = new List <string>();

            if (!BaseValidator.StringHasValue(passwortA))
            {
                messages.Add("Das Feld 'Passwort' muss ausgefüllt sein.");
            }
            if (!BaseValidator.StringHasValue(passwortB))
            {
                messages.Add("Das Feld 'Passwort Wiederholen' muss ausgefüllt sein.");
            }
            if (messages.Count == 0)
            {
                if (!BaseValidator.StringIsInRange(passwortA, 8, 64))
                {
                    messages.Add("Das Passwort muss zwischen 8 und 64 Zeichen lang sein.");
                }
                if (!BaseValidator.StringsAreEqual(passwortA, passwortB))
                {
                    messages.Add("Die Passwörter stimmen nicht überein.");
                }
            }
            return(messages);
        }
 private void btnLogin_Click(object sender, EventArgs e)
 {
     if (BaseValidator.IsFormValid(this.components))
     {
         using (var uow = new UnitOfWorks())
         {
             if (IsEdit)
             {
                 var id   = Common.Common.UserID;
                 var user = uow.Userrepository.GetById(id);
                 user.Username     = txtUsername.Text;
                 user.userPassword = txtPassword.Text;
                 uow.Userrepository.Update(user);
                 uow.Save();
                 Application.Restart();
             }
             else
             {
                 if (uow.Userrepository.GetAll(l => l.Username == txtUsername.Text && l.userPassword == txtPassword.Text).Any())
                 {
                     Common.Common.UserID = uow.Userrepository.GetAll(l => l.Username == txtUsername.Text && l.userPassword == txtPassword.Text).Select(u => u.UserID).SingleOrDefault();
                     DialogResult         = DialogResult.OK;
                 }
                 else
                 {
                     RtlMessageBox.Show("اطلاعات وارد شده صحیح نمی باشد", "هشدار", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 }
             }
         }
     }
 }
        private void butGuardarImportes_Click(object sender, System.EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
            {
                return;
            }
            BaseValidator valImportes = (BaseValidator)this.FindControl("valImportes");

            valImportes.Enabled = true;
            valImportes.Validate();
            if (!valImportes.IsValid)
            {
                return;
            }

            if (this.GuardarImportesTabla())
            {
                Session["tarifario"] = tariFlete;
            }
            //Limpiar la tabla
            this.tblImportesTarifario.Rows.Clear();
            this.CargarTablaImportes(false);
            this.txtAccion.Text = "";
            if (tariFlete.ZonasTopesCol.getCount() > 0)
            {
                this.SetearBotones("Editar");
            }
            else
            {
                this.SetearBotones("Ninguno");
            }
            valImportes.Enabled = false;
        }
 private void btnsave_Click(object sender, EventArgs e)
 {
     if (BaseValidator.IsFormValid(this.components))
     {
         if (AID == 0)
         {
             DataLayer.Accounting accounting = new DataLayer.Accounting()
             {
                 CustomerID  = int.Parse(dgvCustomer.CurrentRow.Cells[0].Value.ToString()),
                 TypeID      = byte.Parse(((rbtnInCome.Checked) ? 1 : 2).ToString()),
                 Amount      = int.Parse(numericUpDown1.Text.ToString()),
                 DateTime    = DateTime.Now,
                 Description = textBox1.Text
             };
             db.BaseRepositoryAccounting.Insert(accounting);
         }
         else
         {
             DataLayer.Accounting myAccounting = db.BaseRepositoryAccounting.GetById(AID);
             myAccounting.CustomerID  = db.CustomerRepository.GetCustomersByName(txtCustomer.Text).CustomersID;
             myAccounting.Amount      = int.Parse(numericUpDown1.Text);
             myAccounting.Description = textBox1.Text;
             myAccounting.TypeID      = byte.Parse((((rbtnInCome.Checked) ? 1 : 2).ToString()));
             db.BaseRepositoryAccounting.Update(myAccounting);
         }
         db.Save();
         DialogResult = DialogResult.OK;
     }
 }
Beispiel #23
0
 private void btnLogin_Click(object sender, EventArgs e)
 {
     if (BaseValidator.IsFormValid(this.components))
     {
         using (UnitOfWork db = new UnitOfWork())
         {
             if (IsEdit)
             {
                 var login = db.LoginRepository.Get().First();
                 login.UserName = txtUserName.Text;
                 login.Password = txtPassword.Text;
                 db.LoginRepository.Update(login);
                 db.Save();
                 Application.Restart();
             }
             else
             {
                 if (db.LoginRepository.Get(l => l.UserName == txtUserName.Text && l.Password == txtPassword.Text).Any())
                 {
                     DialogResult = DialogResult.OK;
                 }
                 else
                 {
                     RtlMessageBox.Show("کاربری یافت نشد.");
                 }
             }
         }
     }
 }
 private void btnSave_Click(object sender, EventArgs e)
 {
     try
     {
         if (BaseValidator.IsFormValid(this.components))
         {
             var s = new Staff();
             s.StaffName        = txtName.Text;
             s.StaffEmail       = txtEmail.Text;
             s.StaffSection     = txtSection.Text;
             s.StaffAddress     = txtAddress.Text;
             s.StaffAge         = int.Parse(txtAge.Text.ToString());
             s.StaffPhoneNumber = txtPhoneNumber.Text;
             using (UnitOfWork db = new UnitOfWork())
             {
                 if (id == 0)
                 {
                     db.SGenericRepository.Insert(s);
                 }
                 else
                 {
                     s.StaffID = id;
                     db.SGenericRepository.Update(s);
                 }
                 db.Save();
                 DialogResult = DialogResult.OK;
             }
         }
     }
     catch
     {
         RtlMessageBox.Show("به صورت صحیح وارد کنید!", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Beispiel #25
0
        /// <summary>
        /// Implementation of OnPreRender that links the Validator in the page with javascript code
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            ClientScriptManager cm = Page.ClientScript;
            BaseValidator       extendedValidator = this.GetExtendedValidator();
            CustomValidator     customValidator   = extendedValidator as CustomValidator;

            if (extendedValidator != null)
            {
                if (customValidator != null)
                {
                    customValidator.ClientValidationFunction = "CustomServerSideValidationEvaluateIsValid";
                }
                else
                {
                    string controlId = extendedValidator.ClientID;
                    cm.RegisterExpandoAttribute(controlId, "evaluationfunction", "GenericServerSideValidationEvaluateIsValid", false);
                }
            }

            //Call GetCallbackEventReference to be able to do a Callback on the client-side
            cm.GetCallbackEventReference(this, "arg", "ServerSideValidationValidate", "context");

            //Registers this control as one that requires postback handling when the page is posted back to the server.
            //This is to prevent full page validation when the postback is in fact a callback triggered by this control
            this.Page.RegisterRequiresPostBack(this);
        }
        public IEventRequestParametersBuilder <T> AddCustomValues(string customFieldName, string customFieldValue)
        {
            BaseValidator.CheckForNullAndEmptyOrThrow(customFieldName, this.GetType().Name + ".customFieldName");

            BaseValidator.CheckForNullAndEmptyOrThrow(customFieldValue, this.GetType().Name + ".customFieldValue");

            if (null == this.FieldsRawValuesByName)
            {
                Dictionary <string, string> newFields = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                this.FieldsRawValuesByName = newFields;
            }

            string lowerCaseField = customFieldName.ToLowerInvariant();

            bool keyIsDuplicated = DuplicateEntryValidator.IsDuplicatedFieldsInTheDictionary(this.FieldsRawValuesByName, lowerCaseField);

            if (keyIsDuplicated)
            {
                throw new InvalidOperationException(this.GetType().Name + ".customFieldValue : duplicate fields are not allowed");
            }

            this.FieldsRawValuesByName.Add(lowerCaseField, customFieldValue);

            return(this);
        }
        public void CreateValidator()
        {
            BaseValidator webValidator = CreateWebValidator();
            int           index        = Control.Parent.Controls.IndexOf(Control);

            Control.Parent.Controls.AddAt(index + 1, webValidator);
        }
        /// <summary> Adds the validator to page after control to validate. </summary>
        /// <param name="validator">The validator.</param>
        private void AddValidatorToPageAfterControl(BaseValidator validator)
        {
            var parent = this.control.Parent;
            int indexOfControlInParent = parent.Controls.IndexOf(this.control);

            try
            {
                parent.Controls.AddAt(indexOfControlInParent + 1, validator);
            }
            catch (HttpException ex)
            {
                string messageFormat =
                    "Sorry, you have encountered a rare .NET bug. "
                    + "The list of controls that contains the  '{0}', does also contain '<% %>' tags. "
                    + "In that case the control collection in '{1}' cannot be modified. "
                    + "To solve this problem, you could put the '{0}' control in another parent. {2}";

                string message = string.Format(
                    CultureInfo.InvariantCulture,
                    messageFormat,
                    this.control.ID,
                    parent.ID,
                    ex.Message);

                throw new InvalidOperationException(message);
            }
        }
Beispiel #29
0
        private static List <string> AddressIsValid()
        {
            var messages = new List <string>();

            if (!BaseValidator.StringHasValue(user.Address.Strasse))
            {
                messages.Add("Das Feld Strasse muss ausgefüllt sein.");
            }
            if (!BaseValidator.StringHasValue(user.Address.Ort))
            {
                messages.Add("Das Feld Ort muss ausgefüllt sein.");
            }
            if (!BaseValidator.StringHasValue(user.Address.Postleitzahl))
            {
                messages.Add("Das Feld Postleitzahl muss ausgefüllt sein.");
            }
            if (!BaseValidator.StringIsInMaxLenght(user.Address.Strasse, 40))
            {
                messages.Add("Das Feld Strasse darf maximal 40 Zeichen beinhalten.");
            }
            if (!BaseValidator.StringIsInMaxLenght(user.Address.Ort, 40))
            {
                messages.Add("Das Feld Ort darf maximal 40 Zeichen beinhalten.");
            }
            if (!BaseValidator.StringIsInMaxLenght(user.Address.Postleitzahl, 4))
            {
                messages.Add("Das Feld Postleitzahl darf maximal 4 Zeichen beinhalten.");
            }
            if (!BaseValidator.StringIsNumeric(user.Address.Postleitzahl))
            {
                messages.Add("Das Feld Postleitzahl darf nur Zahlen beinhalten.");
            }
            return(messages);
        }
        /// <summary>
        /// Gets the control validation value.
        /// </summary>
        /// <remarks>
        /// Based on the reflected source of <see cref="BaseValidator.GetControlValidationValue"/>.
        /// </remarks>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        private string GetControlValidationValue(string name)
        {
            Control valueControl = NamingContainer.FindControl(name);

            if (valueControl == null)
            {
                return(null);
            }
            PropertyDescriptor validationProperty = BaseValidator.GetValidationProperty(valueControl);

            if (validationProperty == null)
            {
                return(null);
            }

            object value = validationProperty.GetValue(valueControl);

            if (value is ListItem)
            {
                return(((ListItem)value).Value);
            }

            if (value != null)
            {
                return(value.ToString());
            }

            return(String.Empty);
        }
Beispiel #31
0
 public override void Initialize(IComponent component)
 {
     this._baseValidator = (BaseValidator) component;
     base.Initialize(component);
     for (int i = this._baseValidator.Controls.Count - 1; i >= 0; i--)
     {
         Control control = this._baseValidator.Controls[i];
         if (control is BaseValidator)
         {
             this._baseValidator.Controls.RemoveAt(i);
         }
     }
 }
Beispiel #32
0
	public void Initialize(BXCustomField currentField, BXCustomProperty currentValue)
	{
		field = currentField;
		value = currentValue;
		if (field == null)
			return;

		settings = new BXParamsBag<object>(field.Settings);
		viewMode = settings.ContainsKey("ViewMode") && (string)settings["ViewMode"] == "list" ? ViewMode.List : ViewMode.Flag;

		valDDList.Enabled = false;
		valList.Enabled = false;
		valFlag.Enabled = false;
		valCheckbox.Enabled = false;
		
		ListControl list;
		int listCount = Math.Max(settings.GetInt("ListSize", 5), 1);
		if (viewMode == ViewMode.List)
		{
			if (field.Multiple)
			{
				View.ActiveViewIndex = 0;
				list = List;
				validator = valList;
				List.Rows = Math.Min(listCount, Enums.Count + (!field.Multiple && !field.Mandatory ? 1 : 0));
			}
			else
			{
				View.ActiveViewIndex = 3;
				list = DDList;
				validator = valDDList;
			}
		}
		else
		{
			if (field.Multiple)
			{
				View.ActiveViewIndex = 2;
				list = ChBox;
				validator = valCheckbox;
			}
			else
			{
				View.ActiveViewIndex = 1;
				list = Flag;
				validator = valFlag;
			}
		}

		ListItem none = null;
		if (!field.Multiple && !field.Mandatory)
		{
			none = new ListItem(GetMessage("Option.NotSelected"), "");
			none.Selected = true;
			list.Items.Add(none);
		}

		validator.Enabled = field.Mandatory;
		validator.ValidationGroup = ValidationGroup;

		foreach (BXCustomFieldEnum e in Enums)
			list.Items.Add(new ListItem(e.Value, e.Id.ToString()));


		if (value != null)
		{
			bool stop = false;
			foreach (ListItem item in list.Items)
			{
				foreach (int val in value.Values)
					if (item.Value == val.ToString())
					{
						if (!field.Multiple)
						{
							if (none != null)
								none.Selected = false;
							stop = true;
						}
						
						item.Selected = true;
						break;
					}

				if (stop)
					break;
			}
		}
		else //BIND DEFAULT
		{
			bool stop = false;
			foreach (ListItem item in list.Items)
			{
				foreach (BXCustomFieldEnum val in Enums)
					if (item.Value == val.Id.ToString() && val.Default)
					{
						if (!field.Multiple)
						{
							if (none != null)
								none.Selected = false;
							stop = true;
						}
						
						item.Selected = true;
						break;
					}

				if (stop)
					break;
			}
		}
	}