Exemplo n.º 1
0
        public void EmailValidatorTest4()
        {
            Mock<ILogger> logger = new Mock<ILogger>();
            RegexHelper helper = new RegexHelper(logger.Object);

            bool ret = helper.IsValidEmail("testmailgmail.com");

            Assert.IsFalse(ret);
        }
        public void CheckStringContainsCorrectLscGroupEmailAddress()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            var testString = @"*****@*****.**";

            //Act
            bool result = regexHelper.CheckLiteralIsALscEmail(testString);

            //Assert
            Assert.IsTrue(result);
        }
        public void CheckStringContainsCorrectEmailAddressComplicated()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            var testString = @"*****@*****.**";

            //Act
            bool result = regexHelper.CheckLiteralIsALscEmail(testString);

            //Assert
            Assert.IsFalse(result);
        }
        public void CheckStringIfNull()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            string testString = null;

            //Act
            bool result = regexHelper.CheckLiteralIsALscEmail(testString);

            //Assert
            Assert.IsFalse(result);
        }
        public void CheckStringIfEmpty()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            var testString = @"";

            //Act
            bool result = regexHelper.CheckLiteralIsALscEmail(testString);

            //Assert
            Assert.IsFalse(result);
        }
        public void CheckStringContainsLettersWithCorrectLetters()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            var testString = @"andrewwebb";

            //Act
            bool result = regexHelper.CheckLiteralIsAlphaNumeric(testString);

            //Assert
            Assert.IsTrue(result);
        }
        public void CheckStringContainsNumbersLettersWithInCorrectString()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            var testString = @"andrew$webb1";

            //Act
            bool result = regexHelper.CheckLiteralIsAlphaNumeric(testString);

            //Assert
            Assert.IsFalse(result);
        }
        public void CheckStringContainsNumbersLettersWithNull()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            string testString = null;

            //Act
            bool result = regexHelper.CheckLiteralIsAlphaNumeric(testString);

            //Assert
            Assert.IsFalse(result);
        }
Exemplo n.º 9
0
        public void CheckStringContainsInCorrectEmailAddressNoDomain()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            var testString = @"andrewwebb@gmail";

            //Act
            bool result = regexHelper.CheckLiteralIsEmail(testString);

            //Assert
            Assert.IsFalse(result);
        }
Exemplo n.º 10
0
        public void CheckStringContainsCorrectEmailAddressComplicated()
        {
            //Arrange
            IRegexHelper regexHelper = new RegexHelper();
            var testString = @"*****@*****.**";

            //Act
            bool result = regexHelper.CheckLiteralIsEmail(testString);

            //Assert
            Assert.IsTrue(result);
        }
Exemplo n.º 11
0
        internal static StringAssertion IsNotValidEmail(this StringAssertion source)
        {
            source.Extend(x =>
            {
                //bool isEmail = Regex.IsMatch(x, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z");

                RegexHelper helper = new RegexHelper();
                var isEmail = helper.IsValidEmail(x);

                return AssertResult.New(string.IsNullOrWhiteSpace(x) || !isEmail, Resources.IsNotValidEmail);
            });

            return source;
        }
        public IEnumerable<string> applyPatternMatch(string entityValue, IEnumerable<string> valuesToMatch)
        {
            var result = new List<string>();
            if (valuesToMatch != null)
            {
                foreach (var valueToMatch in valuesToMatch)
                {
                    var regexHelper = new RegexHelper(entityValue, this.Platform.Equals(FamilyEnumeration.unix));
                    var matchValues = regexHelper.GetMatchPathNamesFromCurrentPathPattern(new string[] { valueToMatch });
                    var concatenatedValue = this.mergePatternAndMatch(entityValue, matchValues.SingleOrDefault());
                    if (!string.IsNullOrWhiteSpace(concatenatedValue))
                        result.Add(concatenatedValue);
                }
            }

            return result;
        }
Exemplo n.º 13
0
        /// <summary>
        /// 开始抓取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartGetData_Click(object sender, EventArgs e)
        {
            List <StepDetailSetting> stepDetailSettingList = dgvMain.DataSource as List <StepDetailSetting>;

            if (stepDetailSettingList == null || stepDetailSettingList.Count == 0)
            {
                ShowMsg("没有任何绑定字段,无法从页面抓取");
                return;
            }
            string msg;

            string[] notShowProperties = null;
            Type     type = GetTheSaveDataType(out msg, ref notShowProperties);

            if (type == null)
            {
                ShowMsg(msg);
                return;
            }
            string filePath = Config.CurrentDir + Guid.NewGuid() + ".txt";

            _mainForm.geckoWebBrowser.SaveDocument(filePath);
            var content = System.IO.File.ReadAllText(filePath);

            try
            {
                System.IO.File.Delete(filePath);
            }
            catch
            {
            }
            string url = _mainForm.geckoWebBrowser.Url.ToString();
            object obj = type.GetConstructor(new Type[0]).Invoke(null);

            PropertyInfo[] ps = type.GetProperties();
            foreach (StepDetailSetting setting in stepDetailSettingList)
            {
                PropertyInfo pi = ps.FirstOrDefault(m => m.Name == setting.PropertyName);
                if (pi == null)
                {
                    continue;
                }
                bool   isContent  = setting.FromSource == FromSourceContent;
                string fromSource = isContent ? content : url;
                //正则规则匹配
                List <string> list  = new List <string>();
                List <string> list1 = RegexHelper.GetStringByPattern(fromSource, setting.Pattern, setting.Multi == Multi);
                if (!string.IsNullOrEmpty(setting.Pattern2))
                {
                    foreach (var item in list1)
                    {
                        var list2 = RegexHelper.GetStringByPattern(item, setting.Pattern, setting.Multi2 == Multi);
                        list2 = list2.Where(m => !string.IsNullOrEmpty(m) && !string.IsNullOrEmpty(m.Trim())).ToList();
                        list.AddRange(list2);
                    }
                }
                else
                {
                    list.AddRange(list1);
                }
                string val = list.ToJoin();
                pi.SetValue(obj, val, null);
            }
            //有特殊属性,则赋值,如:OpDate
            PropertyInfo opDatePi = type.GetProperty("OpDate");

            if (opDatePi != null)
            {
                opDatePi.SetValue(obj, DateTime.Now, null);
            }
            PropertyInfo stepSettingIdPi = type.GetProperty("StepSettingId");

            if (stepSettingIdPi != null)
            {
                stepSettingIdPi.SetValue(obj, Id, null);
            }
            txtMain.Text = obj.ToJson();
        }
Exemplo n.º 14
0
        private async void Save()
        {
            //this.NombreReferenciaUno = "hola";
            //string prue = this.BancoText;

            //VALIDACIONES
            //validar foto perfil
            byte[] imageArray = null;
            if (this.fileFoto != null)
            {
                imageArray = FilesHelper.ReadFully(this.fileFoto.GetStream());
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Agrega tu foto de perfil", Languages.Accept);

                return;
            }


            //Login
            if (string.IsNullOrEmpty(this.Login))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu usuario", Languages.Accept);

                return;
            }

            //Password
            if (string.IsNullOrEmpty(this.Password))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu contraseña", Languages.Accept);

                return;
            }
            if (this.Password.Length < 3)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe una contraseña mayor a 3 caracteres", Languages.Accept);

                return;
            }

            //ClvPuesto--  this.PuestoText
            if (this.PuestoText == null)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Selecciona el puesto que te interesa", Languages.Accept);

                return;
            }
            //Nombre
            if (string.IsNullOrEmpty(this.Nombre))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu nombre", Languages.Accept);

                return;
            }
            //ApellidoPaterno
            if (string.IsNullOrEmpty(this.ApellidoPaterno))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu apellido paterno", Languages.Accept);

                return;
            }
            //ApellidoMaterno
            if (string.IsNullOrEmpty(this.ApellidoMaterno))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu apellido materno", Languages.Accept);

                return;
            }
            //Curp
            if (string.IsNullOrEmpty(this.Curp))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu CURP", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidCurp(this.Curp))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe una CURP valida", Languages.Accept);

                return;
            }
            //Email
            if (string.IsNullOrEmpty(this.Email))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu email", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidEmailAddress(this.Email))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un email valido", Languages.Accept);

                return;
            }

            //validar identificacion
            byte[] imageArrayIdentificacion = null;
            if (this.fileIdentificacion != null)
            {
                imageArrayIdentificacion = FilesHelper.ReadFully(this.fileIdentificacion.GetStream());
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Agrega la foto de tu identificación", Languages.Accept);

                return;
            }
            //Telefono
            if (string.IsNullOrEmpty(this.Telefono))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu teléfono", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidTel(this.Telefono) || this.Telefono.Length != 10)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un teléfono de 10 dígitos", Languages.Accept);

                return;
            }
            //DescripcionTelefono
            if (string.IsNullOrEmpty(this.DescripcionTelefono))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe la descripción de tu teléfono", Languages.Accept);

                return;
            }
            //ClvEstadoCivil --this.EstadoCivilText
            if (this.EstadoCivilText == null)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Selecciona tu estado civil", Languages.Accept);

                return;
            }
            //Peso
            double ejem = 0;

            if (double.TryParse(this.Peso, out ejem))
            {
                if (double.IsNaN(Convert.ToDouble(this.Peso)) || Convert.ToDouble(this.Peso) == 0 || Convert.ToDouble(this.Peso) > 200 || Convert.ToDouble(this.Peso) < 20)
                {
                    await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un peso valido en Kilogramos", Languages.Accept);

                    return;
                }
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Introduce un Peso valido", Languages.Accept);

                return;
            }

            //Altura
            if (double.TryParse(this.Altura, out ejem))
            {
                if (double.IsNaN(Convert.ToDouble(this.Altura)) || Convert.ToDouble(this.Altura) == 0 || Convert.ToDouble(this.Altura) > 2 || Convert.ToDouble(this.Altura) < .5)
                {
                    await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe una altura valida en Metros", Languages.Accept);

                    return;
                }
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Introduce una Altura valida", Languages.Accept);

                return;
            }

            //ClvGradoEstudios-- this.GradoEstudiosText
            if (this.GradoEstudiosText == null)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Selecciona tu grado de estudios", Languages.Accept);

                return;
            }
            // ClvEstado -- this.EstadoText
            if (this.EstadoText == null)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Selecciona tu estado de residencia", Languages.Accept);

                return;
            }
            // ClvMunicipio -- this.MunicipioText
            if (this.MunicipioText == null)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Selecciona tu municipio de residencia", Languages.Accept);

                return;
            }
            //CodigoPostal
            if (string.IsNullOrEmpty(this.CodigoPostal))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un código postal", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidCP(this.CodigoPostal) || this.CodigoPostal.Length != 5)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Código postal no valido", Languages.Accept);

                return;
            }
            //Colonia
            if (string.IsNullOrEmpty(this.Colonia))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe el nombre de la colonia donde resides", Languages.Accept);

                return;
            }
            //Calle
            if (string.IsNullOrEmpty(this.Calle))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe el nombre de la calle donde resides", Languages.Accept);

                return;
            }
            //NumeroExterior
            if (string.IsNullOrEmpty(this.NumeroExterior) || !RegexHelper.IsValidCP(this.NumeroExterior))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un numero exterior", Languages.Accept);

                return;
            }
            //NumeroInterior
            if (string.IsNullOrEmpty(this.NumeroInterior) || !RegexHelper.IsValidCP(this.NumeroInterior))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un numero interior", Languages.Accept);

                return;
            }

            // validar comprobante
            byte[] imageArrayComprobante = null;
            if (this.fileComprobante != null)
            {
                imageArrayComprobante = FilesHelper.ReadFully(this.fileComprobante.GetStream());
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Agrega la foto de tu comprobante domiciliario", Languages.Accept);

                return;
            }
            //ClvBanco -- this.BancoText
            if (this.BancoText == null)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Selecciona un banco", Languages.Accept);

                return;
            }
            //Clabe
            if (string.IsNullOrEmpty(this.Clabe))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu cuenta clabe", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidCP(this.Clabe) || this.Clabe.Length != 18)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu cuenta clabe de 18 números", Languages.Accept);

                return;
            }

            //NumeroCuenta
            if (string.IsNullOrEmpty(this.NumeroCuenta))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu número de cuenta", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidCP(this.NumeroCuenta) || this.NumeroCuenta.Length > 12)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un número de cuenta no mayor a 12 números", Languages.Accept);

                return;
            }
            //NumeroTarjeta
            if (string.IsNullOrEmpty(this.NumeroTarjeta))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe tu número de tarjeta", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidCP(this.NumeroTarjeta) || this.NumeroTarjeta.Length != 16)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un número de tarjeta de 16 dígitos", Languages.Accept);

                return;
            }
            //NombreReferenciaUno
            if (string.IsNullOrEmpty(this.NombreReferenciaUno))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe el nombre de la referencia Uno", Languages.Accept);

                return;
            }
            //TelefonoReferenciaUno
            if (string.IsNullOrEmpty(this.TelefonoReferenciaUno) || this.TelefonoReferenciaUno.Length != 10)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe el teléfono de la referencia Uno", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidTel(this.TelefonoReferenciaUno))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un teléfono de 10 dígitos en la referencia Uno", Languages.Accept);

                return;
            }
            //NombreReferenciaDos
            if (string.IsNullOrEmpty(this.NombreReferenciaDos))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe el nombre de la referencia Dos", Languages.Accept);

                return;
            }
            //TelefonoReferenciaDos
            if (string.IsNullOrEmpty(this.TelefonoReferenciaDos) || this.TelefonoReferenciaDos.Length != 10)
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe el teléfono de la referencia Dos", Languages.Accept);

                return;
            }
            if (!RegexHelper.IsValidTel(this.TelefonoReferenciaDos))
            {
                await Application.Current.MainPage.DisplayAlert("Aviso", "Escribe un teléfono de 10 dígitos  en la referencia Dos", Languages.Accept);

                return;
            }



            this.IsRunning = true;
            this.IsEnabled = false;

            var connection = await this.apiService.CheckConnection();

            if (!connection.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    connection.Message,
                    Languages.Accept);

                return;
            }

            /*byte[] imageArray = null;
             * if (this.fileFoto != null)
             * {
             *  imageArray = FilesHelper.ReadFully(this.fileFoto.GetStream());
             * }
             * byte[] imageArrayIdentificacion = null;
             * if (this.fileIdentificacion != null)
             * {
             *  imageArrayIdentificacion = FilesHelper.ReadFully(this.fileIdentificacion.GetStream());
             * }
             * byte[] imageArrayComprobante = null;
             * if (this.fileComprobante != null)
             * {
             *  imageArrayComprobante = FilesHelper.ReadFully(this.fileComprobante.GetStream());
             * }*/


            var registro = new Registro
            {
                login                   = this.Login,                              //
                password                = this.Password,                           //
                clvPuesto               = Convert.ToInt32(this.PuestoText),        //
                nombre                  = this.Nombre,                             //
                apellidoPaterno         = this.ApellidoPaterno,                    //
                apellidoMaterno         = this.ApellidoMaterno,                    //
                email                   = this.Email,                              //
                curp                    = this.Curp,                               //
                telefono                = this.Telefono,                           //
                descripcionTelefono     = this.DescripcionTelefono,
                estadoCivil             = this.EstadoCivilText,                    //
                peso                    = Convert.ToDouble(this.Peso),             //
                altura                  = Convert.ToDouble(this.Altura),           //
                clvGradoEstudios        = Convert.ToInt32(this.GradoEstudiosText), //
                estado                  = this.EstadoText,                         //
                municipio               = this.MunicipioText,                      //
                codigoPostal            = this.CodigoPostal,                       //
                colonia                 = this.Colonia,                            //
                calle                   = this.Calle,                              //
                numeroExterior          = this.NumeroExterior,                     //
                numeroInterior          = this.NumeroInterior,                     //
                clvBanco                = Convert.ToInt32(this.BancoText),         //
                clabe                   = this.Clabe,                              //
                numeroCuenta            = this.NumeroCuenta,                       //
                numeroTarjeta           = this.NumeroTarjeta,                      //
                nombreReferenciaUno     = this.NombreReferenciaUno,                //
                telefonoReferenciaUno   = this.TelefonoReferenciaUno,              //
                nombreReferenciaDos     = this.NombreReferenciaDos,
                telefonoReferenciaDos   = this.TelefonoReferenciaDos,
                ImageArray              = imageArray,               //
                IdentificacionArray     = imageArrayIdentificacion, //
                ComprobanteArray        = imageArrayComprobante,    //
                foto                    = "",
                identificacion          = "",
                comprobanteDomiciliario = "",
            };

            var url        = Application.Current.Resources["UrlAPI"].ToString();
            var prefix     = Application.Current.Resources["UrlPrefix"].ToString();
            var controller = Application.Current.Resources["UrlRegistro"].ToString();
            var response   = await this.apiService.Post <Registro>(url, prefix, controller, registro);

            if (!response.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    response.Message,
                    Languages.Accept);

                return;
            }

            this.IsRunning = false;
            this.IsEnabled = true;

            Registro respuesta = (Registro)response.Result;

            await Application.Current.MainPage.DisplayAlert(
                "Mensaje",
                respuesta.mensajeRegistro,
                "Aceptar");

            if (respuesta.usuarioRegistrado)
            {
                await Application.Current.MainPage.Navigation.PopAsync();
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Dispose method.
 /// </summary>
 public void Dispose()
 {
     _dataService = null;
     _regexpHelper = null;
 }
Exemplo n.º 16
0
        /// <summary>
        /// General validation method which isn't used by the LLBLGen Pro framework, but can be used by your own code to validate an entity at any given moment.
        /// </summary>
        public override void ValidateEntity()
        {
            // variable to collect errors
            StringBuilder sbExceptionMessage = new StringBuilder();

            #region Check validation rules.

            // ** phone in incorrect format
            /// check if phone comes in correct format for US-Employees
            if (!string.IsNullOrEmpty(HomePhone) &&
                Country == "USA" &&
                !RegexHelper.IsValidUSPhoneNumber(HomePhone))
            {
                // add the error info to the message
                sbExceptionMessage.Append(HOME_PHONE_ERROR_MESSAGE + DELIMITER);
            }


            // ** PostalCode in incorrect format
            if (!string.IsNullOrEmpty(PostalCode) &&
                !RegexHelper.IsValidZIPCode(this.PostalCode))
            {
                // add the error info to the message
                sbExceptionMessage.Append(POSTAL_CODE_ERROR_MESSAGE + DELIMITER);
            }


            // ** Birth date must be smaller than today
            // assuming we are able to register babies too :)
            if (BirthDate != null &&
                !(BirthDate < DateTime.Now))
            {
                // add the error info to the message
                sbExceptionMessage.Append(BIRTH_DATE_ERROR_MESSAGE + DELIMITER);
            }


            // ** HireDate must be greater than BirthDate
            // assuming we are able to hire babies too :D
            if (HireDate != null && BirthDate != null &&
                !(HireDate > BirthDate))
            {
                // add the error info to the message
                sbExceptionMessage.Append(HIRE_DATE_ERROR_MESSAGE + DELIMITER);
            }


            // -- add more validations --
            // ...
            #endregion

            // get the errors collected
            string strExceptionMessage = sbExceptionMessage.ToString();

            // Do exist any break rule in this entity?
            if (strExceptionMessage != string.Empty)
            {
                // set error info so we can access that outside
                this.SetEntityError(strExceptionMessage);

                // throws an exception with all the breaking rules info
                throw new ORMEntityValidationException(strExceptionMessage, this);
            }

            base.ValidateEntity();
        }
Exemplo n.º 17
0
        private async void Register()
        {
            var url        = Application.Current.Resources["UrlAPI"].ToString();
            var prefix     = Application.Current.Resources["UrlPrefix"].ToString();
            var controller = Application.Current.Resources["UrlUsersController"].ToString();

            var connection = await ApiService.GetInstance().CheckConnection();

            if (!connection.IsSuccess)
            {
                ToastNotificationUtils.ShowErrorToastNotifications("No hay conexion a internet");
                return;
            }
            else if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Surname))
            {
                ToastNotificationUtils.ShowErrorToastNotifications("Nombre incorrecto");
                return;
            }
            else if (!RegexHelper.IsValidEmail(Email) || string.IsNullOrEmpty(Email))
            {
                ToastNotificationUtils.ShowErrorToastNotifications("Email incorrecto");
                return;
            }
            else if (Password.Length < 6)
            {
                ToastNotificationUtils.ShowErrorToastNotifications("La contraseña debe tener al menos 6 caracteres");
                return;
            }
            else
            {
                IsRunning = true;
                byte[] imageArray = null;

                if (file != null)
                {
                    imageArray = FilesHelper.ReadFully(file.GetStream());
                }
                var userRequest = new UserRequest();
                userRequest.Name       = Name;
                userRequest.Surname    = Surname;
                userRequest.Email      = Email;
                userRequest.Password   = Password;
                userRequest.ImageArray = imageArray;

                var postUserResponse = await ApiService.GetInstance().Post <UserRequest>(url, prefix, controller, userRequest);

                if (postUserResponse.IsSuccess)
                {
                    var token = await ApiService.GetInstance().GetToken(url, Email, Password);

                    if (token == null || string.IsNullOrEmpty(token.AccessToken))
                    {
                        ShowErrorMessage("Error al obtener el token. Contacte con el administrador del sistema");
                        IsRunning = false;
                        return;
                    }


                    Settings.TokenType   = token.TokenType;
                    Settings.AccessToken = token.AccessToken;

                    Settings.UserASP = JsonConvert.SerializeObject(postUserResponse.Result);
                    MyUserASP newUser = JsonConvert.DeserializeObject <MyUserASP>(Settings.UserASP);

                    var userResponse = await DataService.GetInstance().PostUser(newUser.Id, newUser.Email, newUser.Name, newUser.Surname, newUser.Image);

                    if (postUserResponse.IsSuccess)
                    {
                        IsRunning = false;
                        NavigationService.NavigateToAsync <MainViewModel>();
                    }
                    else
                    {
                        IsRunning = false;
                        ShowErrorMessage("Se ha producido un error durante el registro del usuario");
                    }
                }
                else
                {
                    IsRunning = false;
                    ShowErrorMessage("Se ha producido un error durante el registro del usuario");
                }
            }
        }
Exemplo n.º 18
0
 public static string ToNoTag(this string value)
 {
     return(RegexHelper.Replace(value, RegexPattern.Tag, ""));
 }
Exemplo n.º 19
0
        public List <string> analyse(List <string> arPadding)
        {
            List <string> arProcessResult = new List <string>();

            foreach (string strPadding in arPadding)
            {
                List <string> arProcessPerPadding = new List <string> {
                    strPadding
                };

                //Replace Google Top N words
                //[G500]{3-4} Google Top 500, Length from 3 to 4
                // \[G(\d+?)\]({(\d+)(-(\d+))?})?
                //Only 9897 Number
                List <List <string> > arMatchResults = RegexHelper.Match(@"\[G(\d+?)\]({(\d+)(-(\d+))?})?", strPadding);

                foreach (List <string> arList in arMatchResults)
                {
                    int iTop, iBeg, iEnd;

                    try
                    {
                        iTop = Int32.Parse(arList[1]);
                    }
                    catch
                    {
                        throw new AnalyseException("in [Gn], n must be a number;");
                    }

                    if (iTop <= 0 || iTop > 9897)
                    {
                        throw new AnalyseException("in [Gn], n must between 1 to 9897;");
                    }

                    try
                    {
                        iBeg = arList[3] == "" ? -1 : Int32.Parse(arList[3]);
                        iEnd = arList[5] == "" ? 9999 : Int32.Parse(arList[5]);
                    }
                    catch
                    {
                        throw new AnalyseException("in {a-b}, both a and b must be a number; if in {a}, a must be a number;");
                    }

                    if (iEnd < iBeg)
                    {
                        throw new AnalyseException("in {a-b}, b must equal or above a;");
                    }

                    List <string> arTempResult = new List <string>();

                    //TOP iTop
                    for (int i = 0; i < iTop; i++)
                    {
                        //check length between iBeg to iEnd
                        if (arGoogleTopWords[i].Length >= iBeg && arGoogleTopWords[i].Length <= iEnd)
                        {
                            foreach (string padding in arProcessPerPadding)
                            {
                                arTempResult.Add(padding.Replace(arList[0], arGoogleTopWords[i]));
                            }
                        }
                    }

                    arProcessPerPadding = arTempResult;
                }

                arProcessResult.AddRange(arProcessPerPadding);
            }

            return(arProcessResult);
        }
Exemplo n.º 20
0
        /// <summary>
        /// 解析快递信息
        /// </summary>
        /// <param name="json">服务器返回json数据</param>
        /// <param name="ExpressInfo">快递单号信息</param>
        /// <returns>是否成功</returns>
        private static bool ParseExpressInfo(string json, ExpressInfo ExpressInfo)
        {
            try
            {
                JObject jo    = JObject.Parse(json);
                JToken  value = null;

                //快递单当前的状态
                int state = -1;
                if (jo.TryGetValue("state", out value))
                {
                    if (!Int32.TryParse(value.ToString(), out state))
                    {
                        return(false);
                    }
                }

                //查询结果状态
                if (jo.TryGetValue("status", out value))
                {
                    if (value.ToString().Equals("200"))
                    {
                        //快递单号
                        string ExpressNo = string.Empty;

                        if (jo.TryGetValue("nu", out value))
                        {
                            ExpressNo = value.ToString();
                        }
                        if (string.IsNullOrEmpty(ExpressNo))
                        {
                            return(false);
                        }
                        if (state == 3 || state == 4 || state == 6)
                        {
                            //3:签收,收件人已签收;4:退签,即货物由于用户拒签、超区等原因退回,而且发件人已经签收;
                            //6:退回,货物正处于退回发件人的途中;
                            //快递周期已结束,则将当前快递单号移入到历史表中,不在产生任何短信信息
                            SaveExpressHistoryInfo(ExpressNo, state);
                        }

                        if (jo.TryGetValue("data", out value))
                        {
                            List <ExpressProcessDetail> list = JsonConvert.DeserializeObject <List <ExpressProcessDetail> >(value.ToString());
                            if (list != null && list.Count > 0)
                            {
                                list.Reverse();
                                int length                = list.Count;
                                int maxGroupNo            = GetExpressDetailMaxGroupNo(ExpressNo);
                                ExpressProcessDetail item = null;
                                for (int i = maxGroupNo; i < length; i++)
                                {
                                    item           = list[i];
                                    item.ExpressNo = ExpressNo;
                                    item.GroupNo   = i + 1;
                                    //相对准确,但不是完全准确的一个状态
                                    item.State = GetExpressDetailState(item, maxGroupNo == 0 && i == 0);
                                }


                                //产生了新的快递进度信息,准备发送短信通知
                                if (length > maxGroupNo)
                                {
                                    var saveList = list.Where(e => e.GroupNo > maxGroupNo).ToList();
                                    //保存新的进度信息
                                    SQLHelper.BatchSaveData(saveList, "p_ExpressProcessDetail");
                                    //插入短信通知,等待任务轮训时发送短信
                                    var      lastDetail = list[length - 1];
                                    string[] Receivers  = ExpressInfo.Receiver.Split(new char[] { ',' });
                                    foreach (string Receiver in Receivers)
                                    {
                                        if (RegexHelper.IsMobile(Receiver))
                                        {
                                            //短信最大长度为40字节,20汉字
                                            string content = string.Format("亲快件*{0}!{1}", ExpressNo.Substring(ExpressNo.Length - 4 > 0 ? ExpressNo.Length - 4 : 0), lastDetail.Context.Replace(" ", ""));
                                            //由于短信接口只有20条免费短信的限制,所以改为邮件提醒
                                            //MessageHelper.AddMessage(Receiver, content.FormatStringLength(40), "");
                                        }
                                        else if (RegexHelper.IsEmail(Receiver))
                                        {
                                            bool isAddMessage = false;
                                            //修改消息添加规则,有变更就添加可能一天收很多邮件,让人厌烦
                                            //现在规则修改为快递状态为1:揽件 3:签收 5:派件 这几种状态必发
                                            //然后每天其它状态的最多发送一条
                                            var importantDetail = saveList.Where(e => e.State == 1 || e.State == 3 || e.State == 5);
                                            if (importantDetail != null && importantDetail.Count() > 0)
                                            {
                                                isAddMessage = true;
                                            }
                                            else
                                            {
                                                if (!HasSendMessage(ExpressInfo.ExpressGUID))
                                                {
                                                    isAddMessage = true;
                                                }
                                            }
                                            if (isAddMessage)
                                            {
                                                Hashtable             ht = new Hashtable();
                                                List <ExpressCompany> listExpressCompany = GetAllExpressCompany();
                                                string ExpressCompany = listExpressCompany.FirstOrDefault(e => e.CompanyCode == ExpressInfo.ExpressCompanyCode).CompanyName;
                                                ht["TotalTime"]      = lastDetail.Time.GetDayAndHours(list[0].Time);
                                                ht["T"]              = list;
                                                ht["V"]              = ExpressInfo;
                                                ht["ExpressCompany"] = ExpressCompany;
                                                ht["Status"]         = state;
                                                string content = FileGen.GetFileText(FileHelper.GetAbsolutePath("Temples/ExpressDetail.vm"), ht).ToString();
                                                //添加邮件消息提醒
                                                MessageHelper.AddMessage(Receiver, content, "快递进度变更", "快递进度", ExpressInfo.ExpressGUID, MessageType.EMAIL);
                                            }
                                        }
                                        else
                                        {
                                            TaskLog.ExpressProgressLogInfo.WriteLogE(string.Format("快递单号“{0}”的接收人“{1}”无法识别,不为邮件/手机号任何一种,请检查!", ExpressInfo.ExpressNo, ExpressInfo.Receiver));
                                        }
                                    }
                                }
                            }
                        }
                        return(true);
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Validates the given EntityFieldCore object on the given fieldIndex with the given value.
        /// This routine is called by the Entity's own value validator after the value has passed validation for destination column type and
        /// null values.
        /// </summary>
        /// <param name="involvedEntity">The involved entity.</param>
        /// <param name="fieldIndex">Index of IEntityFieldCore to validate</param>
        /// <param name="value">Value which should be stored in field with index fieldIndex. Will not be null (earlier logic filters out nulls before
        /// a call will be made to this routine).</param>
        /// <returns>
        /// true if the value is valid for the field, false otherwise
        /// </returns>
        /// <remarks>Use the entity.SetEntityFieldError() and entity.SetEntityError() methods if you want to set a IDataErrorInfo error string after the
        /// validation.</remarks>
        public override bool ValidateFieldValue(IEntityCore involvedEntity, int fieldIndex, object value)
        {
            // value to return
            bool fieldIsValid = true;

            if (value != null)
            {
                #region Inspect fieldIndex to determinate if they are in a correct format
                switch ((CustomerFieldIndex)fieldIndex)
                {
                    #region Phone
                case CustomerFieldIndex.Phone:

                    /// check if phone comes in correct format ofr US-Customers
                    if (((CustomerEntity)involvedEntity).Country == "USA" &&
                        !RegexHelper.IsValidUSPhoneNumber((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Phone.ToString(), PHONE_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Phone.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region Fax
                case CustomerFieldIndex.Fax:

                    /// check if fax comes in correct format for US-Customers
                    if (((CustomerEntity)involvedEntity).Country == "USA" &&
                        !RegexHelper.IsValidUSPhoneNumber((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Fax.ToString(), FAX_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Fax.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region Address
                case CustomerFieldIndex.Address:

                    /// check if Address comes in correct format
                    if (!RegexHelper.IsValidStreetAddress((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Address.ToString(), ADDRESS_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Address.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region City
                case CustomerFieldIndex.City:

                    /// check if City comes in correct format
                    if (!RegexHelper.IsValidName((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.City.ToString(), CITY_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.City.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region Country
                case CustomerFieldIndex.Country:

                    /// check if Country comes in correct format
                    if (!RegexHelper.IsValidName((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Country.ToString(), COUNTRY_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.Country.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region PostalCode
                case CustomerFieldIndex.PostalCode:

                    /// check if PostalCode comes in correct format
                    if (!RegexHelper.IsValidZIPCode((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.PostalCode.ToString(), POSTAL_CODE_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.PostalCode.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region ContactName
                case CustomerFieldIndex.ContactName:

                    /// check if ContactName comes in correct format
                    if (!RegexHelper.IsValidName((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.ContactName.ToString(), CONTACT_NAME_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.ContactName.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region CompanyName
                case CustomerFieldIndex.CompanyName:

                    /// check if CompanyName comes in correct format
                    if (!RegexHelper.IsValidName((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.CompanyName.ToString(), COMPANY_NAME_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.CompanyName.ToString(), "", false);
                    }
                    break;
                    #endregion

                    #region ContactTitle
                case CustomerFieldIndex.ContactTitle:

                    /// check if ContactTitle comes in correct format
                    if (!RegexHelper.IsValidAlphaText((string)value))
                    {
                        // set error info, so we could check that outside
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.ContactTitle.ToString(), CONTACT_TITLE_INCORRECT_FORMAT_ERROR_MESSAGE, false);
                        fieldIsValid = false;
                    }
                    else
                    {
                        // everything seems to be OK with this field so we clean the error info.
                        involvedEntity.SetEntityFieldError(CustomerFieldIndex.ContactTitle.ToString(), "", false);
                    }
                    break;
                    #endregion


                    // -- add more fields to be checked --
                    // ...
                }
                #endregion
            }
            // return valid field status
            return(fieldIsValid);
        }
Exemplo n.º 22
0
        protected override void Seed(NTT_BlogEngine.DAL.Data.ApplicationDbContext context)
        {
            var entityRep = new EntityRepository(context);


            var post = new Post
            {
                Title       = "Khoang hành lý trên xe hơi có máy để ở giữa!",
                Slug        = RegexHelper.CreateSlug("Khoang hành lý trên xe hơi có máy để ở giữa!"),
                Description = "Xe có máy để ở giữa hai trục có khoang hành lý ở trước và sau trong khi hầu hết xe hơi khác của loài người thì máy ở trước còn khoang hành lý ở sau. Với chiếc xe thể thao 2 chỗ ngồi hai cửa nhỏ như chiếc Porsche 718 Cayman mình giới thiệu trong bài này thì hai khoang hành lý giúp để được...",
                Content     = "<h2>Introduction</h2><p>In this article I will demonstrate how you can use Autofac IoC container in MVC application. This article will cover various dependency injection scenarios in MVC, namely: controller, custom filter and view dependency injection.&nbsp;</p><p>In large applications development you will usually have different projects which contains different parts of your architecture like data, services, UI ..etc. Thats why in this article I have created a solution that contains more than one project so it can be as close to real application development as possible. Figure 1 shows the solution structure.</p>",
                ImagePath   = "~/Content/img/post-img/SACH_1.jpg",
                Date        = DateTime.Now
            };

            var comment = new Comment
            {
                Content = "This is comment for post 1",
                Date    = DateTime.Now,
                Post    = post
            };

            var post2 = new Post
            {
                Title       = "Tìm được bằng chứng cho thấy từng có sự sống trên sao Hỏa",
                Slug        = RegexHelper.CreateSlug("Tìm được bằng chứng cho thấy từng có sự sống trên sao Hỏa"),
                Description = "Từ các mẫu vật lấy từ phần đá bùn có niên đại lên đến 3 tỷ năm tuổi ở miệng núi lửa Gale (sao Hỏa), qua phân tích, tàu thăm dò Curiosity...",
                Content     = "Từ các mẫu vật lấy từ phần đá bùn có niên đại lên đến 3 tỷ năm tuổi ở miệng núi lửa Gale (sao Hỏa), qua phân tích, tàu thăm dò Curiosity phát hiện thấy có sự tồn tại của chất hữu cơ bên trong chúng. Bên cạnh đó, NASA cũng cho biết Curiosity còn tìm thấy khí metan trong bầu khí quyển của hành tinh Đỏ.<br/>Sự sống của bất kỳ hành tinh nào đều được xây dựng nên từ những nền tảng nhất định và như chúng ta đã biết, chúng bao gồm các hợp chất hữu cơ và phân tử.Tìm thấy hợp chất hữu cơ là dấu hiệu cho hàng loạt các thông tin khác nhau, chẳng hạn như sự tồn tại của một nền văn minh cổ đại, nguồn thức ăn hỗ trợ sự sống hoặc một dạng sống nào đó mà con người chưa từng được biết đến. ",
                ImagePath   = "~/Content/img/post-img/SACH_2.jpg",
                Date        = DateTime.Now
            };

            var comment2 = new Comment
            {
                Content = "This is comment for post 2",
                Date    = DateTime.Now,
                Post    = post2
            };

            var post3 = new Post
            {
                Title       = "[Infographic] Nguy cơ mắc các bệnh nguy hiểm ở từng độ tuổi và cách phòng ngừa",
                Slug        = RegexHelper.CreateSlug("[Infographic] Nguy cơ mắc các bệnh nguy hiểm ở từng độ tuổi và cách phòng ngừa"),
                Description = "Mặc dù tuổi thọ trung bình lớn hơn nhiều so với hai thập niên trước nhưng dân số ngày nay phải đối mặt với nguy cơ mắc các bệnh nguy hiểm ngày càng cao hơn nhất là các bệnh về tim mạch và ung thư.",
                Content     = "Mặc dù tuổi thọ trung bình lớn hơn nhiều so với hai thập niên trước nhưng dân số ngày nay phải đối mặt với nguy cơ mắc các bệnh nguy hiểm ngày càng cao hơn nhất là các bệnh về tim mạch và ung thư. Các căn bệnh nguy hiểm này bắt nguồn từ nhiều nguyên nhân tuy nhiên kết quả điều trị phụ thuộc rất nhiều vào việc phòng ngừa và phát hiện sớm. Ở từng độ tuổi khác nhau sẽ có nguy cơ mắc các loại bệnh khác nhau và mức độ nguy hiểm của chúng cũng khác nhau.Để biết rõ hơn, mời các bạn theo dõi infographic sau đây!",
                ImagePath   = "~/Content/img/post-img/SACH_3.jpg",
                Date        = DateTime.Now
            };

            var comment3 = new Comment
            {
                Content = "This is comment for post 3",
                Date    = DateTime.Now,
                Post    = post3
            };

            var post4 = new Post
            {
                Title       = "Tesla sắp có bản update để xe có thể tự lái hoàn toàn!",
                Slug        = RegexHelper.CreateSlug("Tesla sắp có bản update để xe có thể tự lái hoàn toàn!"),
                Description = "Autopilot là tính năng lái xe tự động của Tesla, nhưng hiện tại nó chỉ mới làm được một số thứ mang tính hỗ trợ như tự bẻ bánh lái để bạn chạy đúng làn, tự thắng, tự tăng tốc... và điều kiện là tái xế phải đặt tay lên vô lăng.",
                Content     = "Autopilot là tính năng lái xe tự động của Tesla, nhưng hiện tại nó chỉ mới làm được một số thứ mang tính hỗ trợ như tự bẻ bánh lái để bạn chạy đúng làn, tự thắng, tự tăng tốc... và điều kiện là tái xế phải đặt tay lên vô lăng.<br/> Nhưng trong bản update Tesla Version 9.0 sắp tới, Autopilot 2.0 sẽ có khả năng tự lái hoàn toàn. Tất nhiên xe làm được là một chuyện, và luật có cho phép hay không, cho phép như thế nào là một câu chuyện khác. Tesla nói thêm tất cả những gì bạn cần làm là bước vô và nói nơi bạn muốn đến.Nếu bạn không nói gì cả,xe tự chở bạn tới địa điểm trên lịch hẹn của mình,hoặc chở bạn về nhà.Xe sẹ tự tính toán đường tới ưu,tự lái xuyên qua những con đường đô thị(ngay cả khi không phân làn),tự dừng lại khi có đèn đỏ hoặc bảng hiệu bắt buộc dừng,rồi tìm kiếm chỗ đỗ xe",
                ImagePath   = "~/Content/img/post-img/SACH_4.jpg",
                Date        = DateTime.Now
            };

            var comment4 = new Comment
            {
                Content = "This is comment for post 4",
                Date    = DateTime.Now,
                Post    = post4
            };


            entityRep.Add <Post>(post);
            entityRep.Add <Comment>(comment);
            entityRep.Add <Post>(post2);
            entityRep.Add <Comment>(comment2);
            entityRep.Add <Post>(post3);
            entityRep.Add <Comment>(comment3);
            entityRep.Add <Post>(post4);
            entityRep.Add <Comment>(comment4);

            entityRep.SaveChanges();
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check permissions
        if (CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Localization", "LocalizeStrings"))
        {
            // Set title
            CurrentMaster.Title.TitleText     = GetString("localizable.localizefield");
            CurrentMaster.Title.TitleImage    = GetImageUrl("Objects/CMS_UICulture/new.png");
            CurrentMaster.Title.HelpTopicName = "localize_field";
            CurrentMaster.Title.HelpName      = "helpTopic";

            // Validate hash
            Regex re = RegexHelper.GetRegex(@"[\w\d_$$]*");
            identifier = QueryHelper.GetString("params", "");

            if (!QueryHelper.ValidateHash("hash") || !re.IsMatch(identifier))
            {
                pnlContent.Visible = false;
                return;
            }

            // Load dialog parameters
            Hashtable parameters = (Hashtable)WindowHelper.GetItem(identifier);
            if (parameters != null)
            {
                hdnValue              = ValidationHelper.GetString(parameters["HiddenValue"], String.Empty);
                textbox               = ValidationHelper.GetString(parameters["TextBoxID"], String.Empty);
                hdnIsMacro            = ValidationHelper.GetString(parameters["HiddenIsMacro"], String.Empty);
                plainText             = ValidationHelper.GetString(parameters["TextBoxValue"], String.Empty);
                btnLocalizeField      = ValidationHelper.GetString(parameters["ButtonLocalizeField"], String.Empty);
                btnLocalizeString     = ValidationHelper.GetString(parameters["ButtonLocalizeString"], String.Empty);
                btnRemoveLocalization = ValidationHelper.GetString(parameters["ButtonRemoveLocalization"], String.Empty);
                resourceKeyPrefix     = ValidationHelper.GetString(parameters["ResourceKeyPrefix"], String.Empty);
            }
            btnOk.Click += btnOk_Click;

            lstExistingOrNew.Items[0].Text = GetString("localizable.createnew");
            lstExistingOrNew.Items[1].Text = GetString("localizable.useexisting");

            // Disable option to use existing resource string for user who is not admin
            if (!CurrentUser.UserSiteManagerAdmin)
            {
                lstExistingOrNew.Items[1].Enabled = false;
            }

            // If "create new" is selected
            if (lstExistingOrNew.SelectedIndex == 0)
            {
                if (!String.IsNullOrEmpty(resourceKeyPrefix))
                {
                    lblPrefix.Text    = resourceKeyPrefix;
                    lblPrefix.Visible = true;
                }
                lblSelectKey.ResourceString = GetString("localizable.newkey");
                resourceSelector.Visible    = false;
                txtNewResource.Visible      = true;

                if (!RequestHelper.IsPostBack())
                {
                    txtNewResource.Text = ResHelper.GetUniqueResStringKey(resourceKeyPrefix, plainText);
                }
            }
            // If "use existing" is selected
            else
            {
                lblSelectKey.ResourceString = GetString("localizable.existingkey");
                resourceSelector.Visible    = true;
                txtNewResource.Visible      = false;
            }
        }
        // Dialog is not available for unauthorized user
        else
        {
            ShowError(GetString("security.accesspage.onlyglobaladmin"));
            pnlControls.Visible = false;
        }
    }
Exemplo n.º 24
0
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (PortalContext.ViewMode.IsOneOf(ViewModeEnum.LiveSite, ViewModeEnum.Preview))
            {
                Uri referrer = Request.UrlReferrer;

                // Regular expression for match and extraxt host name
                Regex domainRegex = RegexHelper.GetRegex("(www.)?(google|yahoo|bing).[a-zA-Z]{2,3}");

                if (referrer != null)
                {
                    if (domainRegex.Match(referrer.Host).Success)
                    {
                        bool isRegularExpression = false;

                        // Host name without www or domain
                        string host = domainRegex.Match(referrer.Host).Groups[2].Value;

                        // If host name is yahoo - uses other query parameter name
                        string highlightText = URLHelper.GetUrlParameter(referrer.Query, (host == "yahoo") ? "p" : "q");

                        if (highlightText != null)
                        {
                            // Replace + with blank space, if text has more than one word
                            if (highlightText.Contains("+"))
                            {
                                // Search concrete phrase
                                if (highlightText.Contains("%22"))
                                {
                                    highlightText = highlightText.Replace("+", " ");
                                }
                                else
                                {
                                    isRegularExpression = true;
                                    highlightText       = highlightText.Replace("+", "|");
                                }
                            }

                            // In case that somebody will search exact phrase
                            if (highlightText.Contains("%22"))
                            {
                                highlightText = highlightText.Replace("%22", string.Empty);
                            }
                        }

                        // Register highlighter script
                        ScriptHelper.RegisterJQueryHighLighter(Page);
                        ScriptHelper.RegisterStartupScript(Page, typeof(String), "highlighter" + ClientID,
                                                           ScriptHelper.GetScript(
                                                               "$cmsj(function(){$cmsj('body').highlight(" +
                                                               ScriptHelper.GetString(highlightText) + ", " +
                                                               ScriptHelper.GetString(CSSClassName) + ", " +
                                                               ScriptHelper.GetString(isRegularExpression.ToString()) +
                                                               ")})"));
                    }
                }
            }
        }
    }
Exemplo n.º 25
0
    /// <summary>
    /// Loads code of original view/stored procedure from SQL script.
    /// </summary>
    public void Rollback()
    {
        if ((State == STATE_ALTER_VIEW) || (State == STATE_ALTER_PROCEDURE))
        {
            string fileName = null;
            if (SQLScriptExists(this.ObjectName, ref fileName))
            {
                if (!String.IsNullOrEmpty(fileName))
                {
                    // Rollback object from file
                    Regex re = null;
                    if (this.IsView == true)
                    {
                        re = RegexHelper.GetRegex("\\s*CREATE\\s+VIEW\\s+", RegexOptions.IgnoreCase);
                    }
                    else
                    {
                        re = RegexHelper.GetRegex("\\s*CREATE\\s+PROCEDURE\\s+", RegexOptions.IgnoreCase);
                    }

                    // Load SQL script
                    string query = File.ReadAllText(fileName);

                    // Split query to parts separated by "GO" (trying to find part containing CREATE VIEW or CREATE PROCEDURE)
                    int    startingIndex = 0;
                    string partOfQuery   = "";
                    do
                    {
                        int index = query.IndexOf("GO" + Environment.NewLine, startingIndex, StringComparison.InvariantCultureIgnoreCase);
                        if (index == -1)
                        {
                            index = query.IndexOf(Environment.NewLine + "GO", startingIndex, StringComparison.InvariantCultureIgnoreCase);
                            if (index == -1)
                            {
                                index = query.Length;
                            }
                        }

                        // Try to find CREATE VIEW or CREATE PROCEDURE
                        partOfQuery = query.Substring(startingIndex, index - startingIndex).Trim();
                        if (!String.IsNullOrEmpty(partOfQuery) && re.IsMatch(partOfQuery))
                        {
                            SetupControl(partOfQuery);
                            txtObjName.Text = this.ObjectName;
                            break;
                        }
                        startingIndex = index + 3;
                    }while (startingIndex < query.Length);
                }
                else
                {
                    // Rollback object from system
                    string query = SqlGenerator.GetSystemViewSqlQuery(this.ObjectName);
                    SetupControl(query);
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text    = GetString("systbl.unabletorollback");
            }
        }
    }
Exemplo n.º 26
0
 public bool ValidatePassportId()
 {
     return(RegexHelper.Match(PassportId, "^[0-9]{9}$"));
 }
Exemplo n.º 27
0
        public void submitCustomerInfo()
        {
            VerifySignCheck();
            try
            {
                int    storeId = prams.Value <int>("storeId");
                string name    = prams.Value <string>("name");
                string mobile  = prams.Value <string>("mobile");
                string token   = prams.Value <string>("token");
                int    type    = prams.Value <int>("type");
                if (string.IsNullOrEmpty(name))
                {
                    result.setResult(ApiStatusCode.参数错误, "客户名称不能为空");
                    goto Finish;
                }
                if (string.IsNullOrEmpty(mobile))
                {
                    result.setResult(ApiStatusCode.参数错误, "客户联系不能为空");
                    goto Finish;
                }
                if (!RegexHelper.IsValidRealMobileNo(mobile))
                {
                    result.setResult(ApiStatusCode.参数错误, "非法的手机号码");
                    goto Finish;
                }


                string imgContent = "";
                //上传图片
                for (int i = 0; i < Context.Request.Files.Count; i++)
                {
                    HttpPostedFile oFile = Context.Request.Files[i];
                    if (oFile == null)
                    {
                        continue;
                    }
                    string fileName = "/resource/modeng/" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + StringHelper.CreateCheckCodeWithNum(6) + ".jpg";
                    if (FileUploadHelper.UploadFile(oFile, fileName))
                    {
                        if (string.IsNullOrEmpty(imgContent))
                        {
                            imgContent = fileName;
                        }
                        else
                        {
                            imgContent += "|" + fileName;
                        }
                    }
                }
                int flag = UserCarLogic.Instance.AddCustomerModel(new CustomerModel()
                {
                    UserId     = storeId,
                    UserName   = name,
                    UserMobile = mobile,
                    UserImg    = imgContent,
                    UserToken  = string.IsNullOrEmpty(token) ? "" : token,
                    UserType   = type
                });
                if (flag > 0)
                {
                    result.setResult(ApiStatusCode.OK, flag);
                }
                else
                {
                    result.setResult(ApiStatusCode.失败, "");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug(string.Format("StackTrace:{0},Message:{1}", ex.StackTrace, ex.Message), this.DebugMode);
                result.setResult(ApiStatusCode.务器错误, ex.Message);
            }
            goto Finish;
Finish:
            JsonResult(result);
        }
Exemplo n.º 28
0
        private async void ExecuteRunExtendedDialog(object o)
        {
            bool isPass = true;

            if (string.IsNullOrEmpty(TxtUserPhone) || !RegexHelper.IsHandset(TxtUserPhone))
            {
                ErrMsgOut = "请输入有效手机号!";
                isPass    = false;
                return;
            }

            if (GlobalUser.USER.Mobile == TxtUserPhone)
            {
                ErrMsgOut = "新手机号与原手机号相同!";
                isPass    = false;
                return;
            }
            if (string.IsNullOrEmpty(TxtUserPhoneCode))
            {
                ErrMsgOut = "无效的验证码!";
                isPass    = false;
                return;
            }


            if (isPass)
            {
                UserPwdFindModel lm = new UserPwdFindModel()
                {
                    phone = TxtUserPhone,
                    role  = 1
                };

                var reqResult1 = WebProxy(lm, ApiType.CheckUserPhone, null);

                string retData1 = reqResult1?.retData.ToString();

                if (reqResult1?.retCode == 0 && (retData1.ToLower().Contains("check") && !retData1.Contains("1")))
                {
                    UserPwdFindModel lm1 = new UserPwdFindModel()
                    {
                        phone      = TxtUserPhone,
                        phone_code = TxtUserPhoneCode
                    };

                    var reqResult = WebProxy(lm1, ApiType.ModifyUserPhone, GlobalUser.USER.Token);

                    if (reqResult?.retCode == 0)
                    {
                        GlobalUser.USER.Mobile = TxtUserPhone;
                        RememberUser();
                        ErrMsgOut = "更新成功";
                        //_uc.CurrentCloseBtn.CommandParameter = true;

                        await Task.Factory.StartNew(() => Thread.Sleep(333))
                        .ContinueWith(t =>
                        {
                            _uc.CurrentCloseBtn.CommandParameter = true;
                            ButtonAutomationPeer peer            =
                                new ButtonAutomationPeer(_uc.CurrentCloseBtn);

                            IInvokeProvider invokeProv =
                                peer.GetPattern(PatternInterface.Invoke)
                                as IInvokeProvider;
                            invokeProv.Invoke();
                        }, TaskScheduler.FromCurrentSynchronizationContext());
                    }
                    else
                    {
                        ErrMsgOut = reqResult.retMsg;
                    }
                }
                else
                {
                    ErrMsgOut = Properties.Settings.Default.UsedPhoneNum;
                }
            }
        }
Exemplo n.º 29
0
 public bool ValidateHairColor()
 {
     return(RegexHelper.Match(HairColor, "^#[0-9a-f]{6}$"));
 }
Exemplo n.º 30
0
        /// <summary>
        /// Checks if a iban code fits to the country format rules.
        /// </summary>
        /// <param name="iban">The given iban.</param>
        /// <returns>'True' if the format is ok, otherwise 'false'.</returns>
        private bool CheckIbanFormatting(Iban iban)
        {
            RegexHelper regexpheler = new RegexHelper();

            if (regexpheler.RegexpMatch(iban.Country.RegExp, iban.IBAN))
                return true;

            return false;
        }
 private IList<String> matchSubKeysToPatternMatch(string[] subKeyNames, string subKeyPattern)
 {
     var regexHelper = new RegexHelper(subKeyPattern, false);
     return regexHelper.MatchPathNamesToPattern(subKeyNames, subKeyPattern);
 }
Exemplo n.º 32
0
        public static void Execute(string filename)
        {
            List <string> inputPassports = File.ReadAllLines(filename).ToList();

            inputPassports.Add("");

            Passport passport           = new Passport();
            int      validatedPassports = 0;
            int      checkedPassports   = 0;

            foreach (string line in inputPassports)
            {
                if (string.IsNullOrEmpty(line))
                {
                    if (passport.ValidatePassport(false))
                    {
                        checkedPassports++;
                    }
                    if (passport.ValidatePassport(true))
                    {
                        validatedPassports++;
                    }

                    passport = new Passport();
                    continue;
                }

                string[] data = line.Split(" ");

                foreach (string entry in data)
                {
                    RegexHelper.Match(entry, @"^(.*):(.*)$", out string field, out string value);
                    switch (field)
                    {
                    case "byr":
                        passport.BirthYear = value;
                        break;

                    case "iyr":
                        passport.IssueYear = value;
                        break;

                    case "eyr":
                        passport.ExpirationYear = value;
                        break;

                    case "hgt":
                        passport.Height = value;
                        break;

                    case "hcl":
                        passport.HairColor = value;
                        break;

                    case "ecl":
                        passport.EyeColor = value;
                        break;

                    case "pid":
                        passport.PassportId = value;
                        break;

                    case "cid":
                        passport.CountryId = value;
                        break;

                    default:
                        break;
                    }
                }
            }

            Console.WriteLine($"Part One: {checkedPassports}");
            Console.WriteLine($"Part Two: {validatedPassports}");
        }
Exemplo n.º 33
0
        protected async Task RegisterUser()
        {
            if (!registerForm.IsValid())
            {
                return;
            }
            await WithFullScreenLoading(async() =>
            {
                var registerAccountModel = registerForm.GetValue <RegisterAccountDto>();
                if (RegexHelper.ContainsChineseCharacters(registerAccountModel.UserAccount))
                {
                    ToastError("不支持中文账号");
                    return;
                }

                if (!registerAccountModel.Password.Equals(registerAccountModel.ConfirmPassword))
                {
                    ToastError("两次密码输入不一致");
                    return;
                }
                var user = await userManager.FindByNameAsync(registerAccountModel.UserAccount);
                if (user != null)
                {
                    ToastError("用户账号已存在");
                    return;
                }

                bool AccountIsEmail = !string.IsNullOrWhiteSpace(registerAccountModel.Email) && RegexHelper.IsEmail(registerAccountModel.Email);

                var identityResult = await CreateUserAsync(
                    registerAccountModel.UserAccount,
                    registerAccountModel.Password,
                    AccountIsEmail ? registerAccountModel.Email : null,
                    registerAccountModel.QQ);

                if (!identityResult.Succeeded)
                {
                    foreach (var identityError in identityResult.Errors)
                    {
                        ToastError(identityError.Description);
                    }
                    return;
                }
                else
                {
                    ToastSuccess("注册成功,即将自动登录...");
                    await Task.Delay(1000);
                    await AutoLogin(registerAccountModel.UserAccount);
                }
            });
        }
Exemplo n.º 34
0
    /// <summary>
    /// Did you mean suggestion.
    /// </summary>
    private static string DidYouMean(string dictionaryFile, string searchQuery, IEnumerable <string> searchTerms)
    {
        if (searchTerms != null)
        {
            Spelling       SpellChecker   = null;
            WordDictionary WordDictionary = null;


            #region "Word dictionary"

            // If not in cache, create new
            WordDictionary = new WordDictionary();
            WordDictionary.EnableUserFile = false;

            // Getting folder for dictionaries
            string folderName = HttpContext.Current.Request.MapPath("~/App_Data/Dictionaries/");

            // Check if dictionary file exists
            string fileName = Path.Combine(folderName, dictionaryFile);
            if (!File.Exists(fileName))
            {
                EventLogProvider.LogEvent(EventType.ERROR, "DidYouMean webpart", "Dictionary file not found!");

                return(String.Empty);
            }

            WordDictionary.DictionaryFolder = folderName;
            WordDictionary.DictionaryFile   = dictionaryFile;

            // Load and initialize the dictionary
            WordDictionary.Initialize();

            #endregion


            #region "SpellCheck"

            // Prepare spellchecker
            SpellChecker                = new Spelling();
            SpellChecker.Dictionary     = WordDictionary;
            SpellChecker.SuggestionMode = Spelling.SuggestionEnum.NearMiss;

            bool suggest = false;

            // Check all searched terms
            foreach (string term in searchTerms)
            {
                if (term.Length > 2)
                {
                    SpellChecker.Suggest(term);
                    ArrayList al = SpellChecker.Suggestions;

                    // If there are some suggestions
                    if ((al != null) && (al.Count > 0))
                    {
                        suggest = true;

                        // Expression to find term
                        Regex regex = RegexHelper.GetRegex("([\\+\\-\\s\\(]|^)" + term + "([\\s\\)]|$)");

                        // Change term in original search query
                        string suggestion = "$1" + startTag + al[0] + endTag + "$2";
                        searchQuery = regex.Replace(searchQuery, suggestion);
                    }
                }
            }

            #endregion


            if (suggest)
            {
                return(searchQuery);
            }
        }

        return(String.Empty);
    }
Exemplo n.º 35
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="dataservice">An object that implements IDataService interface.</param>
 public ManagerDE(IDataService dataservice) : base(dataservice)
 {
     _regexpHelper = new RegexHelper();
     _dataService  = dataservice;
 }
Exemplo n.º 36
0
        public string UploadSubtitle(long userImdbId, string subLanguageId, string subFileNamePath, Action <int> progress)
        {
            string finalUrl;

            subFileNamePath = new ChangeEncoding().TryReduceRtlLargeFileContent(subFileNamePath);
            var fileInfo = new MovieFileInfo(_movieFileName, subFileNamePath);

            //login
            if (progress != null)
            {
                progress(10);
            }

            LogWindow.AddMessage(LogType.Info, "TryLogin ...");
            tryLogin();

            if (progress != null)
            {
                progress(25);
            }

            LogWindow.AddMessage(LogType.Info, "TryUploadSubtitle ...");

            TryUploadResult res = null;

            try
            {
                res = _client.TryUploadSubtitles(_loginToken,
                                                 new[]
                {
                    new TryUploadInfo
                    {
                        subhash       = fileInfo.SubtitleHash,
                        subfilename   = fileInfo.SubFileName,
                        moviehash     = fileInfo.MovieHash,
                        moviebytesize = fileInfo.MovieFileLength,
                        moviefilename = fileInfo.MovieFileName
                    }
                }
                                                 );
            }
            catch (Exception ex)
            {
                if (!processNewMovieFile(ref userImdbId, fileInfo, ref res, ex))
                {
                    throw;
                }
            }

            if (res == null)
            {
                throw new InvalidOperationException("Bad response ...");
            }

            if (progress != null)
            {
                progress(50);
            }

            if (res.status != "200 OK")
            {
                throw new Exception("Bad response ...");
            }

            if (res.alreadyindb == 0)
            {
                if ((userImdbId == 0) && (res.data == null || res.data.Length == 0))
                {
                    throw new Exception("Bad format ...");
                }

                LogWindow.AddMessage(LogType.Info, string.Format("CheckSubHash({0})", fileInfo.SubtitleHash));
                var checkSubHashRes = _client.CheckSubHash(_loginToken, new[] { fileInfo.SubtitleHash });

                if (progress != null)
                {
                    progress(75);
                }

                var idSubtitleFile = int.Parse(checkSubHashRes.data[fileInfo.SubtitleHash].ToString());
                if (idSubtitleFile > 0)
                {
                    throw new Exception("Duplicate subHash, alreadyindb.");
                }

                LogWindow.AddMessage(LogType.Info, "PostData ...");
                //xml-rpc.net dll does not work here so, ...
                var post = PostXml.PostData(
                    ConfigSetGet.GetConfigData("OpensubtitlesOrgApiUri"),
                    UploadData.CreateUploadXml(_loginToken,
                                               new UploadBaseinfo
                {
                    idmovieimdb      = res.data != null ? res.data[0]["IDMovieImdb"].ToString() : userImdbId.ToString(),
                    sublanguageid    = subLanguageId,
                    movieaka         = string.Empty,
                    moviereleasename = fileInfo.MovieReleaseName,
                    subauthorcomment = string.Empty
                },
                                               new UploadCDsInfo
                {
                    moviebytesize = fileInfo.MovieFileLength.ToString(),
                    moviefilename = fileInfo.MovieFileName,
                    moviehash     = fileInfo.MovieHash,
                    subfilename   = fileInfo.SubFileName,
                    subhash       = fileInfo.SubtitleHash,
                    subcontent    = fileInfo.SubContentToUpload,
                    moviefps      = string.Empty,
                    movieframes   = string.Empty,
                    movietimems   = string.Empty
                }));

                LogWindow.AddMessage(LogType.Info, "Done!");
                finalUrl = RegexHelper.GetUploadUrl(post);
                LogWindow.AddMessage(LogType.Announcement, string.Format("Url: {0}", finalUrl));
            }
            else
            {
                throw new Exception("Duplicate file, alreadyindb");
            }

            if (progress != null)
            {
                progress(100);
            }
            return(finalUrl.Trim());
        }
        public static HashSet <IState> PopulateTransitions(
            this HashSet <IState> states,
            IAlphabet alphabet,
            HashSet <ILetter> stack,
            InstructionsInput input)
        {
            var transitions = RegexHelper.Match(input.instructions, Instruction.TRANSITIONS).Split("\n");

            foreach (var transition in transitions)
            {
                if (String.IsNullOrWhiteSpace(transition))
                {
                    continue;
                }

                var transitionGroup      = transition.Trim().Split(InstructionDelimeter.TRANSITION_FROM_TO);
                var transitionFromValues = transitionGroup[0].Trim().Split(InstructionDelimeter.TRANSITION_FROM_VALUES, 2);
                var toStateValue         = transitionGroup[1].Trim();

                var fromStateValue   = transitionFromValues[0].Trim();
                var transitionLetter = new Letter(transitionFromValues[1].Trim().ToCharArray()[0]);

                var transitionValue = new DirectionValue
                {
                    Letter = transitionLetter
                };


                var pushDownGroup = RegexHelper.Match(transitionFromValues[1], "(?<=\\[)([\\S\\s].*?)*(?=])").Trim();
                if (!String.IsNullOrWhiteSpace(pushDownGroup))
                {
                    var pushDownValues = pushDownGroup.Split(",");

                    var letterToPop  = new Letter(pushDownValues[0].Trim().ToCharArray()[0]);
                    var letterToPush = new Letter(pushDownValues[1].Trim().ToCharArray()[0]);
                    if ((!letterToPop.IsEpsilon && !stack.Contains(letterToPop)) ||
                        (!letterToPush.IsEpsilon && !stack.Contains(letterToPush))
                        )
                    {
                        throw new Exception("Invalid push down values!");
                    }
                    transitionValue.LetterToPop  = letterToPop;
                    transitionValue.LetterToPush = letterToPush;
                }

                if (transitionLetter.IsEpsilon && !alphabet.Letters.Contains(transitionLetter))
                {
                    alphabet.Letters.Add(transitionLetter);
                }

                if (alphabet.Letters.Contains(transitionLetter))
                {
                    foreach (var fromState in states)
                    {
                        if (fromState.Value.Equals(fromStateValue))
                        {
                            foreach (var toState in states)
                            {
                                if (toState.Value.Equals(toStateValue))
                                {
                                    if (fromState.Directions.ContainsKey(toState))
                                    {
                                        fromState.Directions[toState].Add(transitionValue);
                                    }
                                    else
                                    {
                                        fromState.Directions.Add(toState, new HashSet <DirectionValue>()
                                        {
                                            transitionValue
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(states);
        }
Exemplo n.º 38
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="dataservice">An object that implements IDataService interface.</param>
 public ManagerDE(IDataService dataservice) : base(dataservice)
 {
     _regexpHelper = new RegexHelper();
     _dataService = dataservice;
     
 }
Exemplo n.º 39
0
        private async void Save()
        {
            if (string.IsNullOrEmpty(this.FirstName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.FirstNameError,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.LastName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.LastNameError,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.EMail))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EMailError,
                    Languages.Accept);

                return;
            }

            if (!RegexHelper.IsValidEmailAddress(this.EMail))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EMailError,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.Phone))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PhoneError,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.Password))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PasswordError,
                    Languages.Accept);

                return;
            }

            if (this.Password.Length < 6)
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PasswordError,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.PasswordConfirm))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PasswordConfirmError,
                    Languages.Accept);

                return;
            }


            if (!this.Password.Equals(this.PasswordConfirm))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PasswordsNoMatch,
                    Languages.Accept);

                return;
            }

            this.IsRunning = true;
            this.IsEnabled = false;

            var connection = await this.apiService.CheckConnection();

            if (!connection.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    connection.Message,
                    Languages.Accept);

                return;
            }

            byte[] imageArray = null;
            if (this.file != null)
            {
                imageArray = FilesHelper.ReadFully(this.file.GetStream());
            }

            var userRequest = new UserRequest
            {
                Address    = this.Address,
                EMail      = this.EMail,
                FirstName  = this.FirstName,
                ImageArray = imageArray,
                LastName   = this.LastName,
                Password   = this.Password,
            };

            var url        = Application.Current.Resources["UrlAPI"].ToString();
            var prefix     = Application.Current.Resources["UrlPrefix"].ToString();
            var controller = Application.Current.Resources["UrlUsersController"].ToString();
            var response   = await this.apiService.Post(url, prefix, controller, userRequest);

            if (!response.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    response.Message,
                    Languages.Accept);

                return;
            }

            this.IsRunning = false;
            this.IsEnabled = true;

            await Application.Current.MainPage.DisplayAlert(
                Languages.Confirm,
                Languages.RegisterConfirmation,
                Languages.Accept);

            await Application.Current.MainPage.Navigation.PopAsync();
        }
Exemplo n.º 40
0
    private string FindCreateIndexesStatements(string[] statements)
    {
        var createIndexRegex = RegexHelper.GetRegex("CREATE.*INDEX", true);

        return(string.Join(Environment.NewLine, statements.Where(s => createIndexRegex.IsMatch(s))));
    }
        public string SendProtocolMail(string mailDTO, string protocolDTO)
        {
            try
            {
                var mail     = mailDTO.Deserialize <MailDTO>();
                var protocol = protocolDTO.Deserialize <ProtocolDTO>();
                if (!protocol.HasAnyDocument() && protocol.HasId())
                {
                    var domain = FacadeFactory.Instance.ProtocolFacade.GetById(protocol.UniqueId.Value);
                    protocol.CopyFrom(domain);
                }
                mail.CopyFrom(protocol);

                if (mail.Sender != null)
                {
                    if (!RegexHelper.IsValidEmail(mail.Sender.EmailAddress))
                    {
                        mail.Sender.Code = mail.Sender.EmailAddress;
                    }
                }

                if (mail.HasRecipients())
                {
                    foreach (var item in mail.Recipients)
                    {
                        if (!RegexHelper.IsValidEmail(item.EmailAddress))
                        {
                            item.Code = item.EmailAddress;
                        }
                    }
                }

                if (mail.HasRecipientsCc())
                {
                    foreach (var item in mail.RecipientsCc)
                    {
                        if (!RegexHelper.IsValidEmail(item.EmailAddress))
                        {
                            item.Code = item.EmailAddress;
                        }
                    }
                }

                if (mail.HasRecipientsBcc())
                {
                    foreach (var item in mail.RecipientsBcc)
                    {
                        if (!RegexHelper.IsValidEmail(item.EmailAddress))
                        {
                            item.Code = item.EmailAddress;
                        }
                    }
                }

                mail = MailService.Send(mail, false);
                mail = PairToProtocol(mail, protocol);

                return(mail.SerializeAsResponse());
            }
            catch (Exception ex)
            {
                var response = new APIResponse <MailDTO>(ex);
                return(response.Serialize());
            }
            finally
            {
                NHibernateSessionManager.Instance.CloseTransactionAndSessions();
            }
        }
Exemplo n.º 42
0
 protected override IEnumerable <string> GetFileLinks(string pageContent, string filePattern)
 {
     return(RegexHelper.GetLinks(pageContent).Where(link => Regex.IsMatch(link, filePattern)).Select(x => "http://www.vcu.edu.vn/vi/" + x).Distinct());
 }
Exemplo n.º 43
0
 public bool ValidateEyeColor()
 {
     return(RegexHelper.Match(EyeColor, "^(amb|blu|brn|gry|grn|hzl|oth)$", out string color));
 }
Exemplo n.º 44
0
        private IEnumerable<string> applyPatternMatch(string entityValue, IEnumerable<string> valuesToMatch)
        {
            IEnumerable<string> result = new List<string>();
            if (valuesToMatch != null)
            {
                foreach (var valueToMatch in valuesToMatch)
                {
                    RegexHelper regexHelper = new RegexHelper(entityValue);
                    IList<string> matchValues = regexHelper.GetMatchPathNamesFromCurrentPathPattern(new string[] { valueToMatch });
                    ((List<string>)result).AddRange(matchValues);
                }
            }

            return result;
        }
Exemplo n.º 45
0
    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentMaster.PanelContent.RemoveCssClass("dialog-content");

        // Set title
        PageTitle.TitleText = GetString("om.contact.collision");
        // Validate hash
        Regex re = RegexHelper.GetRegex(@"[\w\d_$$]*");

        mIdentifier = QueryHelper.GetString("params", "");
        if (!QueryHelper.ValidateHash("hash") || !re.IsMatch(mIdentifier))
        {
            pnlContent.Visible = false;
            return;
        }

        // Load dialog parameters
        Hashtable parameters = (Hashtable)WindowHelper.GetItem(mIdentifier);

        if (parameters != null)
        {
            mMergedContacts = (DataSet)parameters["MergedContacts"];
            mParentContact  = (ContactInfo)parameters["ParentContact"];

            if (!mParentContact.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser))
            {
                RedirectToAccessDenied(mParentContact.TypeInfo.ModuleName, "Read");
            }

            mIsSitemanager = ValidationHelper.GetBoolean(parameters["issitemanager"], false);

            if (mIsSitemanager)
            {
                mStamp = SettingsKeyInfoProvider.GetValue("CMSCMStamp");
            }
            else
            {
                mStamp = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSCMStamp");
            }
            mStamp = MacroResolver.Resolve(mStamp);

            if (mParentContact != null)
            {
                // Check permissions
                ContactHelper.AuthorizedReadContact(mParentContact.ContactSiteID, true);

                // Load data
                Initialize();
                LoadContactCollisions();
                LoadContactGroups();
                LoadCustomFields();

                // Init controls
                btnMerge.Click        += new EventHandler(btnMerge_Click);
                btnStamp.OnClientClick = "AddStamp('" + htmlNotes.CurrentEditor.ClientID + "'); return false;";
                ScriptHelper.RegisterTooltip(Page);
                RegisterScripts();

                // Set tabs
                tabFields.HeaderText        = GetString("om.contact.fields");
                tabContacts.HeaderText      = GetString("om.account.list");
                tabContactGroups.HeaderText = GetString("om.contactgroup.list");
                tabCustomFields.HeaderText  = GetString("general.customfields");
            }
        }

        // User relative messages placeholder so that JQueryTab isn't moved a bit
        MessagesPlaceHolder.UseRelativePlaceHolder = false;

        // Do not let the editor overflow dialog window
        htmlNotes.SetValue("width", "520");
    }
Exemplo n.º 46
0
 /// <summary>
 /// Dispose method.
 /// </summary>
 public void Dispose()
 {
     _dataService  = null;
     _regexpHelper = null;
 }
Exemplo n.º 47
0
        public async Task <Result> Login(LoginParam model, bool includeRefreshToken)
        {
            User user = null;

            if (RegexHelper.VerifyPhone(model.Name).Succeeded)
            {
                // 手机号验证
                user = await _userManager.Users.FirstOrDefaultAsync(c => c.PhoneNumber == model.Name);

                if (!user.PhoneNumberConfirmed)
                {
                    return(Result.Fail("手机未验证,不允许用手机登录"));
                }
            }
            else if (RegexHelper.VerifyEmail(model.Name).Succeeded)
            {
                // 邮箱验证
                user = await _userManager.FindByEmailAsync(model.Name);

                if (!user.EmailConfirmed)
                {
                    return(Result.Fail("邮箱未验证,不允许用邮箱登录"));
                }
            }
            else
            {
                // 用户名登录验证
                user = await _userManager.FindByNameAsync(model.Name);
            }
            if (user == null)
            {
                return(Result.Fail("用户不存在"));
            }
            if (!user.IsActive)
            {
                return(Result.Fail("用户已禁用"));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            // update false -> set lockoutOnFailure: true
            var signInResult = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, true);

            if (signInResult.IsLockedOut)
            {
                return(Result.Fail("用户已锁定,请稍后重试"));
            }
            else if (signInResult.IsNotAllowed)
            {
                return(Result.Fail("用户邮箱未验证或手机未验证,不允许登录"));
            }
            else if (signInResult.RequiresTwoFactor)
            {
                // 当手机或邮箱验证通过时,TwoFactorEnabled才会生效,否则,则RequiresTwoFactor不可能=true。
                // 设置启用双因素身份验证。
                // 用户帐户已启用双因素身份验证,因此您必须提供第二个身份验证因素。
                var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);

                //return Result.Fail(userFactors.Select(c => c), "当前账号存在安全风险,请进一步验证");
                List <(string, string)> ls = new List <(string, string)>();
                foreach (var item in userFactors)
                {
                    if (item == "Phone")
                    {
                        ls.Add((item, StringHelper.PhoneEncryption(user.PhoneNumber)));
                    }
                    else if (item == "Email")
                    {
                        ls.Add((item, StringHelper.EmailEncryption(user.Email)));
                    }
                }
                return(Result.Fail(new
                {
                    Providers = ls.Select(c => new { key = c.Item1, value = c.Item2 }),
                    signInResult.RequiresTwoFactor
                }, "当前账号存在安全风险,请进一步验证身份"));
            }
            else if (signInResult.Succeeded)
            {
                var token = await _tokenService.GenerateAccessToken(user);

                var loginResult = new LoginResult()
                {
                    Token  = token,
                    Avatar = user.AvatarUrl,
                    Email  = user.Email,
                    Name   = user.FullName,
                    Phone  = user.PhoneNumber
                };
                if (includeRefreshToken)
                {
                    var refreshToken = _tokenService.GenerateRefreshToken();
                    user.RefreshTokenHash = _userManager.PasswordHasher.HashPassword(user, refreshToken);
                    await _userManager.UpdateAsync(user);

                    loginResult.RefreshToken = refreshToken;
                }
                return(Result.Ok(loginResult));
            }
            return(Result.Fail("用户登录失败,用户名或密码错误"));
        }