Exemple #1
0
        private void ExtractMapData(string line, int numOfTasks, Validations validations)
        {
            if (LocalCommunication.MapMatrix == null && line.StartsWith(CffKeywords.LOCAL_COMMUNICATION_MAP))
            {
                // Check the MAP format is valid
                bool   isValidMapFormat = RegexValidation.RegexMap(line, validations);
                string returnedMap      = null;

                if (isValidMapFormat)
                {
                    returnedMap = validations.ValidateStringPair(
                        line,
                        TaffKeywords.ALLOCATION_MAP);
                }

                if (returnedMap != null)
                {
                    LocalCommunication.MapData   = new Map(returnedMap);
                    LocalCommunication.MapMatrix = LocalCommunication.MapData.ConvertToMatrix(
                        numOfTasks,
                        numOfTasks,
                        validations);
                }
            }
        }
Exemple #2
0
        public ClientResponse VerifyIfClientIsValid(ClientModel client)
        {
            _regex = new RegexValidation();

            if (!_regex.ValidateCnpj(client.Cnpj))
            {
                return new ClientResponse()
                       {
                           Success = false, Message = "Invalid Cnpj format."
                       }
            }
            ;

            if (!_regex.ValidatePhone(client.Phone))
            {
                return new ClientResponse()
                       {
                           Success = false, Message = "Phone format invalid."
                       }
            }
            ;

            return(new ClientResponse()
            {
                Success = true, Message = string.Empty
            });
        }
Exemple #3
0
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            if (modelType == typeof(ColumnValidation))
            {
                var    validationType = (ValidationType)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ValidationType").ConvertTo(typeof(Kooboo.CMS.Form.ValidationType));
                object model          = null;
                switch (validationType)
                {
                case ValidationType.Required:
                    model = new RequiredValidation();
                    break;

                case ValidationType.StringLength:
                    model = new StringLengthValidation();
                    break;

                case ValidationType.Range:
                    model = new RangeValidation();
                    break;

                case ValidationType.Regex:
                    model = new RegexValidation();
                    break;
                }
                bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
                return(model);
            }

            return(base.CreateModel(controllerContext, bindingContext, modelType));
        }
Exemple #4
0
        /// <summary>
        /// (重)发送入园凭证短信 基础数据验证
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public DataValidResult ValidDataForMessageSendRequest(MessageSendRequest request)
        {
            var orderInfo = request.Body.OrderInfo;
            var result    = new DataValidResult {
                Status = false
            };

            if (string.IsNullOrEmpty(orderInfo.OrderId))
            {
                result.Code    = "117001";
                result.Message = "(重)发送入园凭证短信异常,订单id不能为空";
                return(result);
            }
            if (string.IsNullOrEmpty(orderInfo.phoneNumber))
            {
                result.Code    = "117002";
                result.Message = "(重)发送入园凭证短信异常,重发手机号码不能为空";
                return(result);
            }
            if (!RegexValidation.IsCellPhone(orderInfo.phoneNumber))
            {
                result.Code    = "117003";
                result.Message = "(重)发送入园凭证短信异常,重发手机号码异常";
                return(result);
            }
            result.Status = true;
            return(result);
        }
Exemple #5
0
        public void Validation(string daysOfWeek, bool isClashException = true)
        {
            var         modelName  = isClashException ? "Clash exception" : "Clash";
            IValidation validation = new RequiredFieldValidation
            {
                Field = new List <ValidationInfo>
                {
                    new ValidationInfo {
                        FieldName = $"{modelName} time and DOWs - days of week", FieldToValidate = daysOfWeek
                    }
                }
            };

            validation.Execute();

            const string zeroOrOne = "^(?!0{7})[0-1]{7}$";

            validation = new RegexValidation
            {
                Field = new List <ValidationInfo>
                {
                    new ValidationInfo
                    {
                        ErrorMessage    = $"{modelName} time and DOWs - Invalid days of week",
                        FieldToValidate = daysOfWeek,
                        RegexPattern    = zeroOrOne
                    }
                }
            };
            validation.Execute();
        }
Exemple #6
0
        public void RegexValidation(string fromTime, string toTime, List <string> dowPattern)
        {
            const string hhmmFormat = "^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5][0-9]$";
            const string dayOfWeek  = "^\\b(?i)(Sun|Mon|Tue|Wed|Thu|Fri|Sat)\\b$";
            IValidation  validation = new RegexValidation()
            {
                Field = new List <ValidationInfo>()
                {
                    new ValidationInfo()
                    {
                        ErrorMessage = "Invalid Time Slice From Time", FieldToValidate = fromTime, RegexPattern = hhmmFormat
                    },
                    new ValidationInfo()
                    {
                        ErrorMessage = "Invalid Time Slice To Time", FieldToValidate = ToTime, RegexPattern = hhmmFormat
                    },
                    new ValidationInfo()
                    {
                        ErrorMessage = "Invalid Dow Pattern", FieldToValidate = dowPattern, RegexPattern = dayOfWeek
                    }
                }
            };

            validation.Execute();
        }
Exemple #7
0
        public bool ValidateUser()
        {
            bool register = true;

            tblFirst_Name_Error.Text = RegexValidation.Name_Check(txtFirst_Name.Text);
            register = tblFirst_Name_Error.Text != "" ? false : register;

            tblLast_Name_Error.Text = RegexValidation.Name_Check(txtLast_Name.Text);
            register = tblLast_Name_Error.Text != "" ? false : register;

            tblMobile_Error.Text = RegexValidation.Check_Mobile(txtMobile_Number.Text);
            register             = tblMobile_Error.Text != "" ? false : register;

            tblPassword_Error.Text = RegexValidation.Check_Password(txtPassword.Password);
            register = tblPassword_Error.Text != "" ? false : register;

            tblConfirmPassword_Error.Text = txtPassword.Password != txtConfirm_Password.Password ? "Passwords do not match" : "";
            register = tblConfirmPassword_Error.Text != "" ? false : register;

            tblState_Error.Text = cbState.SelectedIndex < 0 ? "State not selected" : "";
            register            = tblState_Error.Text != "" ? false : register;

            tblCity_Error.Text = cbCity.IsEnabled == false || cbCity.SelectedIndex < 0 ? "City not selected" : "";
            register           = tblCity_Error.Text != "" ? false : register;

            tblArea_Error.Text = cbArea.IsEnabled == false || cbArea.SelectedIndex < 0 ? "Area not selected" : "";
            register           = tblArea_Error.Text != "" ? false : register;

            tblEmail_Error.Text = RegexValidation.Check_Email(txtEmail.Text);
            register            = tblEmail_Error.Text != "" ? false : register;

            return(register);
        }
Exemple #8
0
        }                                      //0 or 1 for each day of week

        internal void Validate(IEnumerable <SalesArea> validSalesAreas)
        {
            ValidateDates();

            ValidateTimes();

            IValidation validation = new RequiredFieldValidation()
            {
                Field = new List <ValidationInfo>()
                {
                    new ValidationInfo()
                    {
                        FieldName = "PassSalesAreaPriority DaysOfWeek", FieldToValidate = DaysOfWeek
                    },
                    new ValidationInfo()
                    {
                        FieldName = "PassSalesAreaPriority SalesAreaPriorities", FieldToValidate = SalesAreaPriorities
                    },
                }
            };

            validation.Execute();

            validation = new RegexValidation()
            {
                Field = new List <ValidationInfo>()
                {
                    new ValidationInfo()
                    {
                        ErrorMessage    = "Invalid PassSalesAreaPriority DaysOfWeek",
                        FieldToValidate = DaysOfWeek,
                        RegexPattern    = ZeroOrOne
                    }
                }
            };
            validation.Execute();

            var allSalesAreaPriorities       = SalesAreaPriorities.Select(x => x.SalesArea);
            var duplicateSalesAreaPriorities = allSalesAreaPriorities.GroupBy(salesArea => salesArea).Where(g => g.Count() > 1).Select(g => g.Key);

            if (duplicateSalesAreaPriorities.Count() > 0)
            {
                throw new Exception("Duplicate SalesAreas: " + string.Join(",", duplicateSalesAreaPriorities.ToArray()));
            }

            if (validSalesAreas != null)
            {
                SalesAreaPriorities.ForEach(salesAreaPriority =>
                {
                    if (!validSalesAreas.Any(validSalesArea => string.Equals(validSalesArea.Name, salesAreaPriority.SalesArea, StringComparison.CurrentCulture)))
                    {
                        throw new Exception(salesAreaPriority.SalesArea + " is not a valid SalesArea");
                    }
                });
            }
        }
        private void ValidateRestrictionDatesAndDays(DateTime startDate, DateTime?endDate, string restrictionDays)
        {
            IValidation validation = new RequiredFieldValidation
            {
                Field = new List <ValidationInfo>
                {
                    new ValidationInfo {
                        FieldName = "Start Date", FieldToValidate = startDate
                    },
                    new ValidationInfo {
                        FieldName = "Restriction Days", FieldToValidate = restrictionDays
                    }
                }
            };

            validation.Execute();

            if (endDate.HasValue)
            {
                validation = new CompareValidation
                {
                    Field = new List <ValidationInfo>
                    {
                        new ValidationInfo
                        {
                            ErrorMessage    = "Restriction start date should be less than or equal to end date",
                            FieldToValidate = startDate.Date,
                            FieldToCompare  = endDate?.Date,
                            Operator        = Operator.LessThanEqual
                        }
                    }
                };
                validation.Execute();
            }
            const string zeroOrOne = "^(?!0{7})[0-1]{7}$";

            validation = new RegexValidation
            {
                Field = new List <ValidationInfo>
                {
                    new ValidationInfo
                    {
                        ErrorMessage    = "Invalid Restriction Days",
                        FieldToValidate = restrictionDays,
                        RegexPattern    = zeroOrOne
                    }
                }
            };
            validation.Execute();
        }
Exemple #10
0
        private void ExtractMapData(string line, Validations validations)
        {
            if (AllocationMapData == null && line.StartsWith(TaffKeywords.ALLOCATION_MAP))
            {
                // Check the MAP format is valid
                bool isValidMapFormat = RegexValidation.RegexMap(line, validations);

                if (isValidMapFormat)
                {
                    AllocationMapData = validations.ValidateStringPair(
                        line,
                        TaffKeywords.ALLOCATION_MAP);
                }
            }
        }
        public bool ValidProfile()
        {
            bool register = true;

            tblFirst_Name_Error.Text = RegexValidation.Name_Check(txtFirst_Name.Text);
            register = tblFirst_Name_Error.Text != "" ? false : register;

            tblLast_Name_Error.Text = RegexValidation.Name_Check(txtLast_Name.Text);
            register = tblLast_Name_Error.Text != "" ? false : register;

            tblMobile_Error.Text = RegexValidation.Check_Mobile(txtMobile_Number.Text, "driver", driver.Driver_Id);
            register             = tblMobile_Error.Text != "" ? false : register;

            if (txtMobile_Alternate.Text != "")
            {
                tblMobile_Alternate_Error.Text = RegexValidation.Check_Mobile(txtMobile_Alternate.Text, "driver", driver.Driver_Id);
            }
            register = tblMobile_Alternate_Error.Text != "" ? false : register;

            tblState_Error.Text = cbState.SelectedIndex < 0 ? "State not selected" : "";
            register            = tblState_Error.Text != "" ? false : register;

            tblCity_Error.Text = cbCity.IsEnabled == false || cbCity.SelectedIndex < 0 ? "City not selected" : "";
            register           = tblCity_Error.Text != "" ? false : register;

            tbladrl1_Error.Text = RegexValidation.Check_Address(txtAdrl_1.Text);
            register            = tbladrl1_Error.Text != "" ? false : register;

            tbladrl2_Error.Text = RegexValidation.Check_Address(txtAdrl_2.Text);
            register            = tbladrl2_Error.Text != "" ? false : register;

            tblArea_Error.Text = cbArea.IsEnabled == false || cbArea.SelectedIndex < 0 ? "Area not selected" : "";
            register           = tblArea_Error.Text != "" ? false : register;

            if (txtEmail.Text != "")
            {
                tblEmail_Error.Text = RegexValidation.Check_Email(txtEmail.Text, "driver", driver.Driver_Id);
            }
            register = tblEmail_Error.Text != "" ? false : register;

            return(register);
        }
 /// <summary>
 /// 发送手机短信
 /// </summary>
 /// <param name="mobile">手机号码</param>
 /// <param name="content">内容</param>
 /// <returns></returns>
 public static bool Send(string mobile, string content)
 {
     if (!RegexValidation.IsCellPhone(mobile))
     {
         return(false);
     }
     return(true);
     //Task<string> task = new Task<string>(() =>
     //{
     //    string msg = MsgManage.SendSMSNew(mobile, content);
     //    return msg;
     //});
     ////启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
     //task.Start();
     ////等待任务的完成执行过程。
     //task.Wait();
     //long resultMsg = 0;
     //long.TryParse(task.Result, out resultMsg);
     //return resultMsg > 0;
 }
Exemple #13
0
        private Column(string columnName, int columnIndexInFile, bool isRequired, bool isIdentity, ValueType valueType
                       , int stringMaxLenght, string[] dateTimeFormats, CultureInfo[] cultureInfos, decimal minValue, decimal maxValue
                       , RegexValidation regexValidation = RegexValidation.None, string regex = "")
        {
            RegexValidation   = regexValidation;
            _regex            = regex;
            ColumnName        = columnName;
            ColumnIndexInFile = columnIndexInFile;
            IsRequired        = isRequired;
            IsIdentity        = isIdentity;
            ValueType         = valueType;
            StringMaxLenght   = stringMaxLenght;
            DateTimeFormats   = dateTimeFormats;
            CultureInfos      = cultureInfos;
            MinValue          = minValue;
            MaxValue          = maxValue;
            SetRegex();

            Validate();
        }
Exemple #14
0
    protected void Button_Send_Click(object sender, EventArgs e)
    {
        if (RegexValidation.IsNameValid(TextBox_Kontaktperson.Text) == false)
        {
            Label_Error.Text = "Fejl i navn";
        }
        else if (RegexValidation.IsTlfNrValid(TextBox_Telefon.Text) == false)
        {
            Label_Error.Text = "Fejl i telefon nummer";
        }
        else if (RegexValidation.IsEmailValid(TextBox_Email.Text) == false)
        {
            Label_Error.Text = "Forkert mail";
        }
        else if (TextBox_Sporgsmal.Text == "")
        {
            Label_Error.Text = "Skriv et spørgsmål";
        }
        else
        {
            Response.Redirect(Request.RawUrl);

            //Kode der sender en mail via SMTP protokolen - det kræver at serveren er sat op til det
            //but here it is

            //MailMessage objeto_mail = new MailMessage();
            //SmtpClient client = new SmtpClient();
            //client.Port = 25;
            //client.Host = "smtp.internal.mycompany.com";
            //client.Timeout = 10000;
            //client.DeliveryMethod = SmtpDeliveryMethod.Network;
            //client.UseDefaultCredentials = false;
            //client.Credentials = new System.Net.NetworkCredential("user", "Password");
            //objeto_mail.From = new MailAddress("*****@*****.**");
            //objeto_mail.To.Add(new MailAddress("*****@*****.**"));
            //objeto_mail.Subject = TextBox_Email.Text + TextBox_Kontaktperson.Text + TextBox_Firmanavn.Text + TextBox_Telefon.Text;
            //objeto_mail.Body = TextBox_Sporgsmal.Text;
            //client.Send(objeto_mail);
        }
    }
        private bool ValidateEmail(AddCustomerRequest request, ref ValidationResult result)
        {
            var errors = new List <string>();

            if (string.IsNullOrEmpty(request.Email))
            {
                errors.Add("Email must be populated");
            }

            if (!RegexValidation.IsEmailValid(request.Email))
            {
                errors.Add("Email must be a valid email address");
            }

            if (errors.Any())
            {
                result.PassedValidation = false;
                result.Errors.AddRange(errors);
                return(true);
            }

            return(false);
        }
Exemple #16
0
        //public void ConvertToComposite()
        //{
        //    user.User_Id = (int)composite["User_Id"];
        //    user.Password = (string)composite["Password"];
        //    user.Mobile_Number = (string)composite["Mobile_Number"];
        //    user.Mobile_Alternate = (string)composite["Mobile_Alternate"];
        //    user.F_Name = (string)composite["F_Name"];
        //    user.L_Name = (string)composite["L_Name"];
        //    user.Email = (string)composite["Email"];
        //    user.Close = (bool)composite["Close"];
        //    user.Area_Id = (int)composite["Area_Id"];
        //    user.Address_Line_2 = (string)composite["Address_Line_2"];
        //    user.Address_Line_1 = (string)composite["Address_Line_1"];
        //    user.Account_Status = (string)composite["Account_Status"];

        //}

        public bool ItemsValid()
        {
            txtItemsError.Text = RegexValidation.Check_Items(txtItems.Text);

            return(txtItemsError.Text == "" ? true : false);
        }
        public void GivenEmailPattern_WhenValidate_ReturnTrue()
        {
            bool isValid = RegexValidation.EmailMatch("*****@*****.**");

            Assert.IsTrue(isValid);
        }
        public void GivenMobleNumber_WhenValidate_ReturnTrue()
        {
            bool isValid = RegexValidation.MobileNumberMatch("91 9140401246");

            Assert.IsTrue(isValid);
        }
        public void GivenPasswordSampleTwo_WhenTestingValidation_ReturnTure()
        {
            bool isValid = RegexValidation.PasswordMatch02("Sandeep26nas");

            Assert.IsTrue(isValid);
        }
        public void GivenPasswordSamplethree_WhenTestingValidation_ReturnTure()
        {
            bool isValid = RegexValidation.PasswordMatch03("Sandeep1Singh");

            Assert.IsTrue(isValid);
        }
        /// <summary>
        /// Sets parameters from a data form in an object.
        /// </summary>
        /// <param name="e">IQ Event Arguments describing the request.</param>
        /// <param name="EditableObject">Object whose parameters will be set.</param>
        /// <param name="Form">Data Form.</param>
        /// <param name="OnlySetChanged">If only changed parameters are to be set.</param>
        /// <returns>Any errors encountered, or null if parameters was set properly.</returns>
        public static async Task <SetEditableFormResult> SetEditableForm(IqEventArgs e, object EditableObject, DataForm Form, bool OnlySetChanged)
        {
            Type   T = EditableObject.GetType();
            string DefaultLanguageCode = GetDefaultLanguageCode(T);
            List <KeyValuePair <string, string> > Errors = null;
            PropertyInfo PropertyInfo;
            FieldInfo    FieldInfo;
            Language     Language = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode);

            Namespace Namespace             = null;
            Namespace ConcentratorNamespace = await Language.GetNamespaceAsync(typeof(ConcentratorServer).Namespace);

            LinkedList <Tuple <PropertyInfo, FieldInfo, object> > ToSet = null;
            ValidationMethod           ValidationMethod;
            OptionAttribute            OptionAttribute;
            RegularExpressionAttribute RegularExpressionAttribute;
            RangeAttribute             RangeAttribute;
            DataType DataType;
            Type     PropertyType;
            string   NamespaceStr;
            string   LastNamespaceStr = null;
            object   ValueToSet;
            object   ValueToSet2;

            object[] Parsed;
            bool     ReadOnly;
            bool     Alpha;
            bool     DateOnly;
            bool     HasHeader;
            bool     HasOptions;
            bool     ValidOption;
            bool     Nullable;

            if (Namespace is null)
            {
                Namespace = await Language.CreateNamespaceAsync(T.Namespace);
            }

            if (ConcentratorNamespace is null)
            {
                ConcentratorNamespace = await Language.CreateNamespaceAsync(typeof(ConcentratorServer).Namespace);
            }

            foreach (Field Field in Form.Fields)
            {
                PropertyInfo = T.GetRuntimeProperty(Field.Var);
                FieldInfo    = PropertyInfo is null?T.GetRuntimeField(Field.Var) : null;

                if (PropertyInfo is null && FieldInfo is null)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(1, "Property not found."));
                    continue;
                }

                if (PropertyInfo != null && (!PropertyInfo.CanRead || !PropertyInfo.CanWrite))
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                NamespaceStr = (PropertyInfo?.DeclaringType ?? FieldInfo.DeclaringType).Namespace;
                if (Namespace is null || NamespaceStr != LastNamespaceStr)
                {
                    Namespace = await Language.GetNamespaceAsync(NamespaceStr);

                    LastNamespaceStr = NamespaceStr;
                }

                ValidationMethod = null;
                ReadOnly         = Alpha = DateOnly = HasHeader = HasOptions = ValidOption = false;

                foreach (Attribute Attr in (PropertyInfo?.GetCustomAttributes() ?? FieldInfo.GetCustomAttributes()))
                {
                    if (Attr is HeaderAttribute)
                    {
                        HasHeader = true;
                    }
                    else if ((OptionAttribute = Attr as OptionAttribute) != null)
                    {
                        HasOptions = true;
                        if (Field.ValueString == OptionAttribute.Option.ToString())
                        {
                            ValidOption = true;
                        }
                    }
                    else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null)
                    {
                        ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern);
                    }
                    else if ((RangeAttribute = Attr as RangeAttribute) != null)
                    {
                        ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max);
                    }
                    else if (Attr is OpenAttribute)
                    {
                        ValidationMethod = new OpenValidation();
                    }
                    else if (Attr is ReadOnlyAttribute)
                    {
                        ReadOnly = true;
                    }
                    else if (Attr is AlphaChannelAttribute)
                    {
                        Alpha = true;
                    }
                    else if (Attr is DateOnlyAttribute)
                    {
                        DateOnly = true;
                    }
                }

                if (!HasHeader)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                if (ReadOnly)
                {
                    if (Field.ValueString != (PropertyInfo?.GetValue(EditableObject) ?? FieldInfo?.GetValue(EditableObject))?.ToString())
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(3, "Property is read-only."));
                    }

                    continue;
                }

                if (HasOptions && !ValidOption)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                    continue;
                }

                PropertyType = PropertyInfo?.PropertyType ?? FieldInfo.FieldType;
                ValueToSet   = null;
                ValueToSet2  = null;
                Parsed       = null;
                DataType     = null;
                Nullable     = false;

                if (PropertyType.GetTypeInfo().IsGenericType)
                {
                    Type GT = PropertyType.GetGenericTypeDefinition();
                    if (GT == typeof(Nullable <>))
                    {
                        Nullable     = true;
                        PropertyType = PropertyType.GenericTypeArguments[0];
                    }
                }

                if (Nullable && string.IsNullOrEmpty(Field.ValueString))
                {
                    ValueToSet2 = null;
                }
                else
                {
                    if (PropertyType == typeof(string[]))
                    {
                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        ValueToSet = ValueToSet2 = Parsed = Field.ValueStrings;
                        DataType   = StringDataType.Instance;
                    }
                    else if (PropertyType.GetTypeInfo().IsEnum)
                    {
                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        try
                        {
                            ValueToSet = ValueToSet2 = Enum.Parse(PropertyType, Field.ValueString);
                        }
                        catch (Exception)
                        {
                            AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                            continue;
                        }
                    }
                    else if (PropertyType == typeof(bool))
                    {
                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        if (!CommonTypes.TryParse(Field.ValueString, out bool b))
                        {
                            AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(5, "Invalid boolean value."));
                            continue;
                        }

                        DataType   = BooleanDataType.Instance;
                        ValueToSet = ValueToSet2 = b;
                    }
                    else
                    {
                        if (PropertyType == typeof(string))
                        {
                            DataType = StringDataType.Instance;
                        }
                        else if (PropertyType == typeof(sbyte))
                        {
                            DataType = ByteDataType.Instance;
                        }
                        else if (PropertyType == typeof(short))
                        {
                            DataType = ShortDataType.Instance;
                        }
                        else if (PropertyType == typeof(int))
                        {
                            DataType = IntDataType.Instance;
                        }
                        else if (PropertyType == typeof(long))
                        {
                            DataType = LongDataType.Instance;
                        }
                        else if (PropertyType == typeof(byte))
                        {
                            DataType = ShortDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(byte.MinValue.ToString(), byte.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(ushort))
                        {
                            DataType = IntDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(uint))
                        {
                            DataType = LongDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(ulong))
                        {
                            DataType = IntegerDataType.Instance;

                            if (ValidationMethod is null)
                            {
                                ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString());
                            }
                        }
                        else if (PropertyType == typeof(DateTime))
                        {
                            if (DateOnly)
                            {
                                DataType = DateDataType.Instance;
                            }
                            else
                            {
                                DataType = DateTimeDataType.Instance;
                            }
                        }
                        else if (PropertyType == typeof(decimal))
                        {
                            DataType = DecimalDataType.Instance;
                        }
                        else if (PropertyType == typeof(double))
                        {
                            DataType = DoubleDataType.Instance;
                        }
                        else if (PropertyType == typeof(float))
                        {
                            DataType = DoubleDataType.Instance;                                // Use xs:double anyway
                        }
                        else if (PropertyType == typeof(TimeSpan))
                        {
                            DataType = TimeDataType.Instance;
                        }
                        else if (PropertyType == typeof(Uri))
                        {
                            DataType = AnyUriDataType.Instance;
                        }
                        else if (PropertyType == typeof(SKColor))
                        {
                            if (Alpha)
                            {
                                DataType = ColorAlphaDataType.Instance;
                            }
                            else
                            {
                                DataType = ColorDataType.Instance;
                            }
                        }
                        else
                        {
                            DataType = null;
                        }

                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new BasicValidation();
                        }

                        try
                        {
                            if (DataType is null)
                            {
                                ValueToSet  = Field.ValueString;
                                ValueToSet2 = Activator.CreateInstance(PropertyType, ValueToSet);
                            }
                            else
                            {
                                ValueToSet = DataType.Parse(Field.ValueString);

                                if (ValueToSet.GetType() == PropertyType)
                                {
                                    ValueToSet2 = ValueToSet;
                                }
                                else
                                {
                                    ValueToSet2 = Convert.ChangeType(ValueToSet, PropertyType);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(6, "Invalid value."));
                            continue;
                        }
                    }

                    if (Parsed is null)
                    {
                        Parsed = new object[] { ValueToSet }
                    }
                    ;

                    ValidationMethod.Validate(Field, DataType, Parsed, Field.ValueStrings);
                    if (Field.HasError)
                    {
                        AddError(ref Errors, Field.Var, Field.Error);
                        continue;
                    }
                }

                if (ToSet is null)
                {
                    ToSet = new LinkedList <Tuple <PropertyInfo, FieldInfo, object> >();
                }

                ToSet.AddLast(new Tuple <PropertyInfo, FieldInfo, object>(PropertyInfo, FieldInfo, ValueToSet2));
            }

            if (Errors is null)
            {
                SetEditableFormResult Result = new SetEditableFormResult()
                {
                    Errors = null,
                    Tags   = new List <KeyValuePair <string, object> >()
                };

                foreach (Tuple <PropertyInfo, FieldInfo, object> P in ToSet)
                {
                    try
                    {
                        if (OnlySetChanged)
                        {
                            object Current = P.Item1?.GetValue(EditableObject) ?? P.Item2?.GetValue(EditableObject);

                            if (Current is null)
                            {
                                if (P.Item3 is null)
                                {
                                    continue;
                                }
                            }
                            else if (P.Item3 != null && Current.Equals(P.Item3))
                            {
                                continue;
                            }
                        }

                        if (P.Item1 != null)
                        {
                            P.Item1.SetValue(EditableObject, P.Item3);
                            Result.Tags.Add(new KeyValuePair <string, object>(P.Item1.Name, P.Item3));
                        }
                        else
                        {
                            P.Item2.SetValue(EditableObject, P.Item3);
                            Result.Tags.Add(new KeyValuePair <string, object>(P.Item2.Name, P.Item3));
                        }
                    }
                    catch (Exception ex)
                    {
                        AddError(ref Errors, P.Item1?.Name ?? P.Item2.Name, ex.Message);
                    }
                }

                return(Result);
            }
            else
            {
                return(new SetEditableFormResult()
                {
                    Errors = Errors.ToArray(),
                    Tags = null
                });
            }
        }
        public void GivenPasswordSampleFour_WhenTestingValidation_ReturnTure()
        {
            bool isValid = RegexValidation.PasswordMatch04("SandeepSingh123@");

            Assert.IsTrue(isValid);
        }
Exemple #23
0
        /// <summary>
        /// Sets parameters from a data form in an object.
        /// </summary>
        /// <param name="e">IQ Event Arguments describing the request.</param>
        /// <param name="EditableObject">Object whose parameters will be set.</param>
        /// <param name="Form">Data Form.</param>
        /// <returns>Any errors encountered, or null if parameters was set properly.</returns>
        public static async Task <KeyValuePair <string, string>[]> SetEditableForm(IqEventArgs e, object EditableObject, DataForm Form)
        {
            Type   T = EditableObject.GetType();
            string DefaultLanguageCode = GetDefaultLanguageCode(T);
            List <KeyValuePair <string, string> > Errors = null;
            PropertyInfo PI;
            Language     Language = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode);

            Namespace Namespace = await Language.GetNamespaceAsync(T.Namespace);

            Namespace ConcentratorNamespace = await Language.GetNamespaceAsync(typeof(ConcentratorServer).Namespace);

            LinkedList <KeyValuePair <PropertyInfo, object> > ToSet = null;
            ValidationMethod           ValidationMethod;
            OptionAttribute            OptionAttribute;
            RegularExpressionAttribute RegularExpressionAttribute;
            RangeAttribute             RangeAttribute;
            DataType DataType;
            Type     PropertyType;
            string   Header;
            object   ValueToSet;

            object[] Parsed;
            bool     ReadOnly;
            bool     Alpha;
            bool     DateOnly;
            bool     HasHeader;
            bool     HasOptions;
            bool     ValidOption;

            if (Namespace == null)
            {
                Namespace = await Language.CreateNamespaceAsync(T.Namespace);
            }

            if (ConcentratorNamespace == null)
            {
                ConcentratorNamespace = await Language.CreateNamespaceAsync(typeof(ConcentratorServer).Namespace);
            }

            foreach (Field Field in Form.Fields)
            {
                PI = T.GetRuntimeProperty(Field.Var);
                if (PI == null)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(1, "Property not found."));
                    continue;
                }

                if (!PI.CanRead || !PI.CanWrite)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                Header           = null;
                ValidationMethod = null;
                ReadOnly         = Alpha = DateOnly = HasHeader = HasOptions = ValidOption = false;

                foreach (Attribute Attr in PI.GetCustomAttributes())
                {
                    if (Attr is HeaderAttribute)
                    {
                        HasHeader = true;
                    }
                    else if ((OptionAttribute = Attr as OptionAttribute) != null)
                    {
                        HasOptions = true;
                        if (Field.ValueString == OptionAttribute.Option.ToString())
                        {
                            ValidOption = true;
                        }
                    }
                    else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null)
                    {
                        ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern);
                    }
                    else if ((RangeAttribute = Attr as RangeAttribute) != null)
                    {
                        ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max);
                    }
                    else if (Attr is OpenAttribute)
                    {
                        ValidationMethod = new OpenValidation();
                    }
                    else if (Attr is ReadOnlyAttribute)
                    {
                        ReadOnly = true;
                    }
                    else if (Attr is AlphaChannelAttribute)
                    {
                        Alpha = true;
                    }
                    else if (Attr is DateOnlyAttribute)
                    {
                        DateOnly = true;
                    }
                }

                if (Header == null)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable."));
                    continue;
                }

                if (ReadOnly)
                {
                    if (Field.ValueString != PI.GetValue(EditableObject).ToString())
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(3, "Property is read-only."));
                    }

                    continue;
                }

                if (HasOptions && !ValidOption)
                {
                    AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                    continue;
                }

                PropertyType = PI.PropertyType;
                ValueToSet   = null;
                Parsed       = null;
                DataType     = null;

                if (PropertyType == typeof(string[]))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    ValueToSet = Parsed = Field.ValueStrings;
                    DataType   = StringDataType.Instance;
                }
                else if (PropertyType == typeof(Enum))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    try
                    {
                        ValueToSet = Enum.Parse(PropertyType, Field.ValueString);
                    }
                    catch (Exception)
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option."));
                        continue;
                    }
                }
                else if (PropertyType == typeof(bool))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (!CommonTypes.TryParse(Field.ValueString, out bool b))
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(5, "Invalid boolean value."));
                        continue;
                    }

                    DataType = BooleanDataType.Instance;
                }
                else
                {
                    if (PropertyType == typeof(string))
                    {
                        DataType = StringDataType.Instance;
                    }
                    else if (PropertyType == typeof(byte))
                    {
                        DataType = ByteDataType.Instance;
                    }
                    else if (PropertyType == typeof(short))
                    {
                        DataType = ShortDataType.Instance;
                    }
                    else if (PropertyType == typeof(int))
                    {
                        DataType = IntDataType.Instance;
                    }
                    else if (PropertyType == typeof(long))
                    {
                        DataType = LongDataType.Instance;
                    }
                    else if (PropertyType == typeof(sbyte))
                    {
                        DataType = ShortDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(sbyte.MinValue.ToString(), sbyte.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ushort))
                    {
                        DataType = IntDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(uint))
                    {
                        DataType = LongDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ulong))
                    {
                        DataType = IntegerDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(DateTime))
                    {
                        if (DateOnly)
                        {
                            DataType = DateDataType.Instance;
                        }
                        else
                        {
                            DataType = DateTimeDataType.Instance;
                        }
                    }
                    else if (PropertyType == typeof(decimal))
                    {
                        DataType = DecimalDataType.Instance;
                    }
                    else if (PropertyType == typeof(double))
                    {
                        DataType = DoubleDataType.Instance;
                    }
                    else if (PropertyType == typeof(float))
                    {
                        DataType = DoubleDataType.Instance;                            // Use xs:double anyway
                    }
                    else if (PropertyType == typeof(TimeSpan))
                    {
                        DataType = TimeDataType.Instance;
                    }
                    else if (PropertyType == typeof(Uri))
                    {
                        DataType = AnyUriDataType.Instance;
                    }
                    else if (PropertyType == typeof(SKColor))
                    {
                        if (Alpha)
                        {
                            DataType = ColorAlphaDataType.Instance;
                        }
                        else
                        {
                            DataType = ColorDataType.Instance;
                        }
                    }
                    else
                    {
                        DataType = null;
                    }

                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    try
                    {
                        ValueToSet = DataType.Parse(Field.ValueString);
                    }
                    catch (Exception)
                    {
                        AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(6, "Invalid value."));
                        continue;
                    }
                }

                if (Parsed == null)
                {
                    Parsed = new object[] { ValueToSet }
                }
                ;

                ValidationMethod.Validate(Field, DataType, Parsed, Field.ValueStrings);
                if (Field.HasError)
                {
                    AddError(ref Errors, Field.Var, Field.Error);
                    continue;
                }

                if (ToSet == null)
                {
                    ToSet = new LinkedList <KeyValuePair <PropertyInfo, object> >();
                }

                ToSet.AddLast(new KeyValuePair <PropertyInfo, object>(PI, ValueToSet));
            }

            if (Errors == null)
            {
                foreach (KeyValuePair <PropertyInfo, object> P in ToSet)
                {
                    try
                    {
                        P.Key.SetValue(EditableObject, P.Value);
                    }
                    catch (Exception ex)
                    {
                        AddError(ref Errors, P.Key.Name, ex.Message);
                    }
                }
            }

            if (Errors == null)
            {
                return(null);
            }
            else
            {
                return(Errors.ToArray());
            }
        }
Exemple #24
0
 public void InitClassObject()
 {
     //Arrange
     person = new RegexValidation();
 }
Exemple #25
0
        /// <summary>
        /// Gets a data form containing editable parameters from an object.
        /// </summary>
        /// <param name="Client">Client</param>
        /// <param name="e">IQ Event Arguments describing the request.</param>
        /// <param name="EditableObject">Object whose parameters will be edited.</param>
        /// <param name="Title">Title of form.</param>
        /// <returns>Data form containing editable parameters.</returns>
        public static async Task <DataForm> GetEditableForm(XmppClient Client, IqEventArgs e, object EditableObject, string Title)
        {
            Type     T = EditableObject.GetType();
            string   DefaultLanguageCode = GetDefaultLanguageCode(T);
            DataForm Parameters          = new DataForm(Client, FormType.Form, e.To, e.From);
            Language Language            = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode);

            Namespace Namespace = await Language.GetNamespaceAsync(T.Namespace);

            List <Field> Fields = new List <Field>();
            List <Page>  Pages  = new List <Page>();
            Dictionary <string, Page>             PageByLabel = new Dictionary <string, Page>();
            Dictionary <string, Section>          SectionByPageAndSectionLabel = null;
            List <KeyValuePair <string, string> > Options = null;
            string                     Header;
            string                     ToolTip;
            string                     PageLabel;
            string                     SectionLabel;
            string                     s;
            int                        StringId;
            bool                       Required;
            bool                       ReadOnly;
            bool                       Masked;
            bool                       Alpha;
            bool                       DateOnly;
            HeaderAttribute            HeaderAttribute;
            ToolTipAttribute           ToolTipAttribute;
            PageAttribute              PageAttribute;
            SectionAttribute           SectionAttribute;
            OptionAttribute            OptionAttribute;
            TextAttribute              TextAttribute;
            RegularExpressionAttribute RegularExpressionAttribute;
            LinkedList <string>        TextAttributes;
            RangeAttribute             RangeAttribute;
            ValidationMethod           ValidationMethod;
            Type                       PropertyType;
            Field                      Field;
            Page                       DefaultPage = null;
            Page                       Page;

            if (Namespace == null)
            {
                Namespace = await Language.CreateNamespaceAsync(T.Namespace);
            }

            foreach (PropertyInfo PI in T.GetRuntimeProperties())
            {
                if (!PI.CanRead || !PI.CanWrite)
                {
                    continue;
                }

                Header           = ToolTip = PageLabel = SectionLabel = null;
                TextAttributes   = null;
                ValidationMethod = null;
                Required         = ReadOnly = Masked = Alpha = DateOnly = false;

                foreach (Attribute Attr in PI.GetCustomAttributes())
                {
                    if ((HeaderAttribute = Attr as HeaderAttribute) != null)
                    {
                        Header   = HeaderAttribute.Header;
                        StringId = HeaderAttribute.StringId;
                        if (StringId > 0)
                        {
                            Header = await Namespace.GetStringAsync(StringId, Header);
                        }
                    }
                    else if ((ToolTipAttribute = Attr as ToolTipAttribute) != null)
                    {
                        ToolTip  = ToolTipAttribute.ToolTip;
                        StringId = ToolTipAttribute.StringId;
                        if (StringId > 0)
                        {
                            ToolTip = await Namespace.GetStringAsync(StringId, ToolTip);
                        }
                    }
                    else if ((PageAttribute = Attr as PageAttribute) != null)
                    {
                        PageLabel = PageAttribute.Label;
                        StringId  = PageAttribute.StringId;
                        if (StringId > 0)
                        {
                            PageLabel = await Namespace.GetStringAsync(StringId, PageLabel);
                        }
                    }
                    else if ((SectionAttribute = Attr as SectionAttribute) != null)
                    {
                        SectionLabel = SectionAttribute.Label;
                        StringId     = SectionAttribute.StringId;
                        if (StringId > 0)
                        {
                            SectionLabel = await Namespace.GetStringAsync(StringId, SectionLabel);
                        }
                    }
                    else if ((TextAttribute = Attr as TextAttribute) != null)
                    {
                        if (TextAttributes == null)
                        {
                            TextAttributes = new LinkedList <string>();
                        }

                        StringId = TextAttribute.StringId;
                        if (StringId > 0)
                        {
                            TextAttributes.AddLast(await Namespace.GetStringAsync(StringId, TextAttribute.Label));
                        }
                        else
                        {
                            TextAttributes.AddLast(TextAttribute.Label);
                        }
                    }
                    else if ((OptionAttribute = Attr as OptionAttribute) != null)
                    {
                        if (Options == null)
                        {
                            Options = new List <KeyValuePair <string, string> >();
                        }

                        StringId = OptionAttribute.StringId;
                        if (StringId > 0)
                        {
                            Options.Add(new KeyValuePair <string, string>(OptionAttribute.Option.ToString(),
                                                                          await Namespace.GetStringAsync(StringId, TextAttribute.Label)));
                        }
                        else
                        {
                            Options.Add(new KeyValuePair <string, string>(OptionAttribute.Option.ToString(), OptionAttribute.Label));
                        }
                    }
                    else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null)
                    {
                        ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern);
                    }
                    else if ((RangeAttribute = Attr as RangeAttribute) != null)
                    {
                        ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max);
                    }
                    else if (Attr is OpenAttribute)
                    {
                        ValidationMethod = new OpenValidation();
                    }
                    else if (Attr is RequiredAttribute)
                    {
                        Required = true;
                    }
                    else if (Attr is ReadOnlyAttribute)
                    {
                        ReadOnly = true;
                    }
                    else if (Attr is MaskedAttribute)
                    {
                        Masked = true;
                    }
                    else if (Attr is AlphaChannelAttribute)
                    {
                        Alpha = true;
                    }
                    else if (Attr is DateOnlyAttribute)
                    {
                        DateOnly = true;
                    }
                }

                if (Header == null)
                {
                    continue;
                }

                PropertyType = PI.PropertyType;
                Field        = null;

                if (PropertyType == typeof(string[]))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (Options == null)
                    {
                        Field = new TextMultiField(Parameters, PI.Name, Header, Required, (string[])PI.GetValue(EditableObject),
                                                   null, ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                    else
                    {
                        Field = new ListMultiField(Parameters, PI.Name, Header, Required, (string[])PI.GetValue(EditableObject),
                                                   Options.ToArray(), ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                }
                else if (PropertyType == typeof(Enum))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (Options == null)
                    {
                        Options = new List <KeyValuePair <string, string> >();

                        foreach (string Option in Enum.GetNames(PropertyType))
                        {
                            Options.Add(new KeyValuePair <string, string>(Option, Option));
                        }
                    }

                    Field = new ListSingleField(Parameters, PI.Name, Header, Required, new string[] { PI.GetValue(EditableObject).ToString() },
                                                Options.ToArray(), ToolTip, null, ValidationMethod, string.Empty, false, ReadOnly, false);
                }
                else if (PropertyType == typeof(bool))
                {
                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    Field = new BooleanField(Parameters, PI.Name, Header, Required,
                                             new string[] { CommonTypes.Encode((bool)PI.GetValue(EditableObject)) },
                                             Options?.ToArray(), ToolTip, BooleanDataType.Instance, ValidationMethod,
                                             string.Empty, false, ReadOnly, false);
                }
                else
                {
                    DataType DataType;

                    if (PropertyType == typeof(string))
                    {
                        DataType = StringDataType.Instance;
                    }
                    else if (PropertyType == typeof(byte))
                    {
                        DataType = ByteDataType.Instance;
                    }
                    else if (PropertyType == typeof(short))
                    {
                        DataType = ShortDataType.Instance;
                    }
                    else if (PropertyType == typeof(int))
                    {
                        DataType = IntDataType.Instance;
                    }
                    else if (PropertyType == typeof(long))
                    {
                        DataType = LongDataType.Instance;
                    }
                    else if (PropertyType == typeof(sbyte))
                    {
                        DataType = ShortDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(sbyte.MinValue.ToString(), sbyte.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ushort))
                    {
                        DataType = IntDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(uint))
                    {
                        DataType = LongDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ulong))
                    {
                        DataType = IntegerDataType.Instance;

                        if (ValidationMethod == null)
                        {
                            ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(DateTime))
                    {
                        if (DateOnly)
                        {
                            DataType = DateDataType.Instance;
                        }
                        else
                        {
                            DataType = DateTimeDataType.Instance;
                        }
                    }
                    else if (PropertyType == typeof(decimal))
                    {
                        DataType = DecimalDataType.Instance;
                    }
                    else if (PropertyType == typeof(double))
                    {
                        DataType = DoubleDataType.Instance;
                    }
                    else if (PropertyType == typeof(float))
                    {
                        DataType = DoubleDataType.Instance;                            // Use xs:double anyway
                    }
                    else if (PropertyType == typeof(TimeSpan))
                    {
                        DataType = TimeDataType.Instance;
                    }
                    else if (PropertyType == typeof(Uri))
                    {
                        DataType = AnyUriDataType.Instance;
                    }
                    else if (PropertyType == typeof(SKColor))
                    {
                        if (Alpha)
                        {
                            DataType = ColorAlphaDataType.Instance;
                        }
                        else
                        {
                            DataType = ColorDataType.Instance;
                        }
                    }
                    else
                    {
                        DataType = null;
                    }

                    if (ValidationMethod == null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (Masked)
                    {
                        Field = new TextPrivateField(Parameters, PI.Name, Header, Required, new string[] { (string)PI.GetValue(EditableObject) },
                                                     Options?.ToArray(), ToolTip, StringDataType.Instance, ValidationMethod,
                                                     string.Empty, false, ReadOnly, false);
                    }
                    else if (Options == null)
                    {
                        Field = new TextSingleField(Parameters, PI.Name, Header, Required, new string[] { (string)PI.GetValue(EditableObject) },
                                                    null, ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                    else
                    {
                        Field = new ListSingleField(Parameters, PI.Name, Header, Required, new string[] { (string)PI.GetValue(EditableObject) },
                                                    Options.ToArray(), ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                }

                if (Field == null)
                {
                    continue;
                }

                Fields.Add(Field);

                if (string.IsNullOrEmpty(PageLabel))
                {
                    if (DefaultPage == null)
                    {
                        DefaultPage = new Page(Parameters, string.Empty);
                        Pages.Add(DefaultPage);
                        PageByLabel[string.Empty] = DefaultPage;
                    }

                    Page      = DefaultPage;
                    PageLabel = string.Empty;
                }
                else
                {
                    if (!PageByLabel.TryGetValue(PageLabel, out Page))
                    {
                        Page = new Page(Parameters, PageLabel);
                        Pages.Add(Page);
                        PageByLabel[PageLabel] = Page;
                    }
                }

                if (string.IsNullOrEmpty(SectionLabel))
                {
                    if (TextAttributes != null)
                    {
                        foreach (string Text in TextAttributes)
                        {
                            Page.Add(new TextElement(Parameters, Text));
                        }
                    }

                    Page.Add(new FieldReference(Parameters, Field.Var));
                }
                else
                {
                    if (SectionByPageAndSectionLabel == null)
                    {
                        SectionByPageAndSectionLabel = new Dictionary <string, Section>();
                    }

                    s = PageLabel + " \xa0 " + SectionLabel;
                    if (!SectionByPageAndSectionLabel.TryGetValue(s, out Section Section))
                    {
                        Section = new Section(Parameters, SectionLabel);
                        SectionByPageAndSectionLabel[s] = Section;

                        Page.Add(Section);
                    }

                    if (TextAttributes != null)
                    {
                        foreach (string Text in TextAttributes)
                        {
                            Section.Add(new TextElement(Parameters, Text));
                        }
                    }

                    Section.Add(new FieldReference(Parameters, Field.Var));
                }
            }

            Parameters.Title  = Title;
            Parameters.Fields = Fields.ToArray();
            Parameters.Pages  = Pages.ToArray();

            return(Parameters);
        }
Exemple #26
0
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            if (modelType == typeof(ColumnValidation))
            {
                var validationType = (ValidationType)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ValidationType").ConvertTo(typeof(Kooboo.CMS.Form.ValidationType));
                object model = null;
                switch (validationType)
                {
                    case ValidationType.Required:
                        model = new RequiredValidation();
                        break;
                    case ValidationType.StringLength:
                        model = new StringLengthValidation();
                        break;
                    case ValidationType.Range:
                        model = new RangeValidation();
                        break;
                    case ValidationType.Regex:
                        model = new RegexValidation();
                        break;
                }
                bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
                return model;
            }

            return base.CreateModel(controllerContext, bindingContext, modelType);
        }
        public async Task <AddRecordItemResponse> AddRecordItemAsync(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            AddRecordItemResponse result = new AddRecordItemResponse
            {
                IsSucceded = true,
                ResultId   = (int)AddRecordItemResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.RecordItem, out global::System.Object orecordItemRequest);
                Domain.Models.Request.RecordItem recordItemRequest = orecordItemRequest as Domain.Models.Request.RecordItem;

                parameters.TryGetValue(ParameterTypeEnum.MasterAddress, out global::System.Object omasterAddress);
                string masterAddress = omasterAddress.ToString();

                parameters.TryGetValue(ParameterTypeEnum.MasterPrivateKey, out global::System.Object omasterPrivateKey);
                string masterPrivateKey = omasterPrivateKey.ToString();

                parameters.TryGetValue(ParameterTypeEnum.ContractAddress, out global::System.Object ocontractAddress);
                string contractAddress = ocontractAddress.ToString();

                parameters.TryGetValue(ParameterTypeEnum.ContractABI, out global::System.Object ocontractABI);
                string contractABI = ocontractABI.ToString();

                parameters.TryGetValue(ParameterTypeEnum.RecordItemImageContainer, out global::System.Object orecordItemImageContainer);
                string recordItemImageContainer = orecordItemImageContainer.ToString();

                //database helpers
                DBRecordItemHelper  dbRecordItemHelper  = new DBRecordItemHelper(DBCONNECTION_INFO);
                DBUserAccountHelper dbUserAccountHelper = new DBUserAccountHelper(DBCONNECTION_INFO);

                //blockchain helper
                BlockchainHelper bh = new BlockchainHelper(telemetryClient, STORAGE_ACCOUNT, RPC_CLIENT, masterAddress, masterPrivateKey);

                telemetryClient.TrackTrace("Validating username length");

                //validate username length
                if (!RegexValidation.IsValidUsername(recordItemRequest.username))
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordItemResultEnum.InvalidUsernameLength;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating username existance");

                //validate if account exists
                UserAccount userAccount = dbUserAccountHelper.GetUser(recordItemRequest.username);

                if (userAccount == null)
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordItemResultEnum.UsernameNotExists;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating record item existance");

                //validate if record item exists for voting
                RecordItem recordItemExists = dbRecordItemHelper.GetRecordItem(recordItemRequest.hash);

                if (recordItemExists != null)
                {
                    //there is no record item linked with this vote
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordItemResultEnum.AlreadyExists;
                }
                else
                {
                    telemetryClient.TrackTrace("Adding record item to blockchain");

                    var res_AddRecordAsync = await bh.AddRecordAsync(recordItemRequest.hash, recordItemRequest.username, contractAddress, contractABI);

                    telemetryClient.TrackTrace($"Add record item result: {res_AddRecordAsync}");

                    if (string.IsNullOrEmpty(res_AddRecordAsync))
                    {
                        //there was an error adding the record to the blockchain
                        result.IsSucceded = false;
                        result.ResultId   = (int)AddRecordItemResultEnum.BlockchainIssue;
                        return(result);
                    }

                    telemetryClient.TrackTrace("Adding record item to database");

                    RecordItem recordItem = RecordItemParser.TransformRecordItem(recordItemRequest);

                    recordItem.hash          = recordItem.hash.ToLower();
                    recordItem.transactionId = res_AddRecordAsync;
                    recordItem.createdDate   = Timezone.GetCustomTimeZone();
                    recordItem.image         = recordItem.image + ".png";

                    //perform insert in mongodb
                    await dbRecordItemHelper.CreateRecordItem(recordItem);

                    telemetryClient.TrackTrace("Adding record item image to storage");

                    //upload image to blobstorage
                    byte[] buffer = Convert.FromBase64String(recordItemRequest.ImageBytes);
                    await UploadRecordItemImageAsync(recordItemImageContainer, recordItem.image, buffer);
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordItemResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordItemResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }
        public void GivenLastName_WhenValidate_ReturnTrue()
        {
            bool isValid = RegexValidation.LastNameMatch("Singh");

            Assert.IsTrue(isValid);
        }
        /// <summary>
        /// Gets a data form containing editable parameters from an object.
        /// </summary>
        /// <param name="Client">Client</param>
        /// <param name="e">IQ Event Arguments describing the request.</param>
        /// <param name="EditableObject">Object whose parameters will be edited.</param>
        /// <param name="Title">Title of form.</param>
        /// <returns>Data form containing editable parameters.</returns>
        public static async Task <DataForm> GetEditableForm(XmppClient Client, IqEventArgs e, object EditableObject, string Title)
        {
            Type     T = EditableObject.GetType();
            string   DefaultLanguageCode = GetDefaultLanguageCode(T);
            DataForm Parameters          = new DataForm(Client, FormType.Form, e.To, e.From);
            Language Language            = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode);

            Namespace    Namespace = null;
            List <Field> Fields    = new List <Field>();
            List <Page>  Pages     = new List <Page>();
            Dictionary <string, Page>             PageByLabel = new Dictionary <string, Page>();
            Dictionary <string, Section>          SectionByPageAndSectionLabel = null;
            List <KeyValuePair <string, string> > Options = null;
            string                     NamespaceStr;
            string                     LastNamespaceStr = null;
            string                     Header;
            string                     ToolTip;
            string                     PageLabel;
            string                     SectionLabel;
            string                     s;
            int                        StringId;
            int                        PagePriority;
            int                        PageOrdinal = 0;
            int                        FieldPriority;
            int                        FieldOrdinal = 0;
            bool                       Required;
            bool                       ReadOnly;
            bool                       Masked;
            bool                       Alpha;
            bool                       DateOnly;
            bool                       Nullable;
            HeaderAttribute            HeaderAttribute;
            ToolTipAttribute           ToolTipAttribute;
            PageAttribute              PageAttribute;
            SectionAttribute           SectionAttribute;
            OptionAttribute            OptionAttribute;
            TextAttribute              TextAttribute;
            RegularExpressionAttribute RegularExpressionAttribute;
            LinkedList <TextAttribute> TextAttributes;
            RangeAttribute             RangeAttribute;
            ValidationMethod           ValidationMethod;
            Type                       PropertyType;
            Field                      Field;
            Page                       DefaultPage = null;
            Page                       Page;

            if (Namespace is null)
            {
                Namespace = await Language.CreateNamespaceAsync(T.Namespace);
            }

            LinkedList <KeyValuePair <PropertyInfo, FieldInfo> > Properties = new LinkedList <KeyValuePair <PropertyInfo, FieldInfo> >();

            foreach (PropertyInfo PI in T.GetRuntimeProperties())
            {
                if (PI.CanRead)
                {
                    Properties.AddLast(new KeyValuePair <PropertyInfo, FieldInfo>(PI, null));
                }
            }

            foreach (FieldInfo FI in T.GetRuntimeFields())
            {
                Properties.AddLast(new KeyValuePair <PropertyInfo, FieldInfo>(null, FI));
            }

            foreach (KeyValuePair <PropertyInfo, FieldInfo> Rec in Properties)
            {
                PropertyInfo PropertyInfo = Rec.Key;
                FieldInfo    FieldInfo    = Rec.Value;

                NamespaceStr = (PropertyInfo?.DeclaringType ?? FieldInfo.DeclaringType).Namespace;
                if (Namespace is null || NamespaceStr != LastNamespaceStr)
                {
                    Namespace = await Language.GetNamespaceAsync(NamespaceStr);

                    LastNamespaceStr = NamespaceStr;
                }

                Header           = ToolTip = PageLabel = SectionLabel = null;
                TextAttributes   = null;
                ValidationMethod = null;
                Options          = null;
                Required         = Masked = Alpha = DateOnly = false;
                ReadOnly         = PropertyInfo != null && !PropertyInfo.CanWrite;
                PagePriority     = PageAttribute.DefaultPriority;
                FieldPriority    = HeaderAttribute.DefaultPriority;

                foreach (Attribute Attr in (PropertyInfo?.GetCustomAttributes() ?? FieldInfo.GetCustomAttributes()))
                {
                    if ((HeaderAttribute = Attr as HeaderAttribute) != null)
                    {
                        Header        = HeaderAttribute.Header;
                        StringId      = HeaderAttribute.StringId;
                        FieldPriority = HeaderAttribute.Priority;
                        if (StringId > 0)
                        {
                            Header = await Namespace.GetStringAsync(StringId, Header);
                        }
                    }
                    else if ((ToolTipAttribute = Attr as ToolTipAttribute) != null)
                    {
                        ToolTip  = ToolTipAttribute.ToolTip;
                        StringId = ToolTipAttribute.StringId;
                        if (StringId > 0)
                        {
                            ToolTip = await Namespace.GetStringAsync(StringId, ToolTip);
                        }
                    }
                    else if ((PageAttribute = Attr as PageAttribute) != null)
                    {
                        PageLabel    = PageAttribute.Label;
                        StringId     = PageAttribute.StringId;
                        PagePriority = PageAttribute.Priority;
                        if (StringId > 0)
                        {
                            PageLabel = await Namespace.GetStringAsync(StringId, PageLabel);
                        }
                    }
                    else if ((SectionAttribute = Attr as SectionAttribute) != null)
                    {
                        SectionLabel = SectionAttribute.Label;
                        StringId     = SectionAttribute.StringId;
                        if (StringId > 0)
                        {
                            SectionLabel = await Namespace.GetStringAsync(StringId, SectionLabel);
                        }
                    }
                    else if ((TextAttribute = Attr as TextAttribute) != null)
                    {
                        if (TextAttributes is null)
                        {
                            TextAttributes = new LinkedList <TextAttribute>();
                        }

                        TextAttributes.AddLast(TextAttribute);
                    }
                    else if ((OptionAttribute = Attr as OptionAttribute) != null)
                    {
                        if (Options is null)
                        {
                            Options = new List <KeyValuePair <string, string> >();
                        }

                        StringId = OptionAttribute.StringId;
                        if (StringId > 0)
                        {
                            Options.Add(new KeyValuePair <string, string>(OptionAttribute.Option.ToString(),
                                                                          await Namespace.GetStringAsync(StringId, OptionAttribute.Label)));
                        }
                        else
                        {
                            Options.Add(new KeyValuePair <string, string>(OptionAttribute.Option.ToString(), OptionAttribute.Label));
                        }
                    }
                    else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null)
                    {
                        ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern);
                    }
                    else if ((RangeAttribute = Attr as RangeAttribute) != null)
                    {
                        ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max);
                    }
                    else if (Attr is OpenAttribute)
                    {
                        ValidationMethod = new OpenValidation();
                    }
                    else if (Attr is RequiredAttribute)
                    {
                        Required = true;
                    }
                    else if (Attr is ReadOnlyAttribute)
                    {
                        ReadOnly = true;
                    }
                    else if (Attr is MaskedAttribute)
                    {
                        Masked = true;
                    }
                    else if (Attr is AlphaChannelAttribute)
                    {
                        Alpha = true;
                    }
                    else if (Attr is DateOnlyAttribute)
                    {
                        DateOnly = true;
                    }
                }

                if (Header is null)
                {
                    continue;
                }

                PropertyType = PropertyInfo?.PropertyType ?? FieldInfo.FieldType;
                Field        = null;
                Nullable     = false;

                if (PropertyType.GetTypeInfo().IsGenericType)
                {
                    Type GT = PropertyType.GetGenericTypeDefinition();
                    if (GT == typeof(Nullable <>))
                    {
                        Nullable     = true;
                        PropertyType = PropertyType.GenericTypeArguments[0];
                    }
                }

                string PropertyName  = PropertyInfo?.Name ?? FieldInfo.Name;
                object PropertyValue = (PropertyInfo?.GetValue(EditableObject) ?? FieldInfo.GetValue(EditableObject));

                if (PropertyType == typeof(string[]))
                {
                    if (ValidationMethod is null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (Options is null)
                    {
                        Field = new TextMultiField(Parameters, PropertyName, Header, Required, (string[])PropertyValue,
                                                   null, ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                    else
                    {
                        Field = new ListMultiField(Parameters, PropertyName, Header, Required, (string[])PropertyValue,
                                                   Options.ToArray(), ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                }
                else if (PropertyType.GetTypeInfo().IsEnum)
                {
                    if (ValidationMethod is null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (Options is null)
                    {
                        Options = new List <KeyValuePair <string, string> >();

                        foreach (string Option in Enum.GetNames(PropertyType))
                        {
                            Options.Add(new KeyValuePair <string, string>(Option, Option));
                        }
                    }

                    s = PropertyValue?.ToString();
                    if (Nullable && s is null)
                    {
                        s = string.Empty;
                    }

                    Field = new ListSingleField(Parameters, PropertyName, Header, Required, new string[] { s },
                                                Options.ToArray(), ToolTip, null, ValidationMethod, string.Empty, false, ReadOnly, false);
                }
                else if (PropertyType == typeof(bool))
                {
                    if (ValidationMethod is null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    if (Nullable && PropertyValue is null)
                    {
                        s = string.Empty;
                    }
                    else
                    {
                        s = CommonTypes.Encode((bool)PropertyValue);
                    }

                    Field = new BooleanField(Parameters, PropertyName, Header, Required, new string[] { s },
                                             Options?.ToArray(), ToolTip, BooleanDataType.Instance, ValidationMethod,
                                             string.Empty, false, ReadOnly, false);
                }
                else
                {
                    DataType DataType;

                    if (PropertyType == typeof(string))
                    {
                        DataType = StringDataType.Instance;
                    }
                    else if (PropertyType == typeof(sbyte))
                    {
                        DataType = ByteDataType.Instance;
                    }
                    else if (PropertyType == typeof(short))
                    {
                        DataType = ShortDataType.Instance;
                    }
                    else if (PropertyType == typeof(int))
                    {
                        DataType = IntDataType.Instance;
                    }
                    else if (PropertyType == typeof(long))
                    {
                        DataType = LongDataType.Instance;
                    }
                    else if (PropertyType == typeof(byte))
                    {
                        DataType = ShortDataType.Instance;

                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new RangeValidation(byte.MinValue.ToString(), byte.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ushort))
                    {
                        DataType = IntDataType.Instance;

                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(uint))
                    {
                        DataType = LongDataType.Instance;

                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(ulong))
                    {
                        DataType = IntegerDataType.Instance;

                        if (ValidationMethod is null)
                        {
                            ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString());
                        }
                    }
                    else if (PropertyType == typeof(DateTime))
                    {
                        if (DateOnly)
                        {
                            DataType = DateDataType.Instance;
                        }
                        else
                        {
                            DataType = DateTimeDataType.Instance;
                        }
                    }
                    else if (PropertyType == typeof(decimal))
                    {
                        DataType = DecimalDataType.Instance;
                    }
                    else if (PropertyType == typeof(double))
                    {
                        DataType = DoubleDataType.Instance;
                    }
                    else if (PropertyType == typeof(float))
                    {
                        DataType = DoubleDataType.Instance;                            // Use xs:double anyway
                    }
                    else if (PropertyType == typeof(TimeSpan))
                    {
                        DataType = TimeDataType.Instance;
                    }
                    else if (PropertyType == typeof(Uri))
                    {
                        DataType = AnyUriDataType.Instance;
                    }
                    else if (PropertyType == typeof(SKColor))
                    {
                        if (Alpha)
                        {
                            DataType = ColorAlphaDataType.Instance;
                        }
                        else
                        {
                            DataType = ColorDataType.Instance;
                        }
                    }
                    else
                    {
                        DataType = StringDataType.Instance;
                    }

                    if (ValidationMethod is null)
                    {
                        ValidationMethod = new BasicValidation();
                    }

                    s = PropertyValue?.ToString();
                    if (Nullable && s is null)
                    {
                        s = string.Empty;
                    }

                    if (Masked)
                    {
                        Field = new TextPrivateField(Parameters, PropertyName, Header, Required, new string[] { s },
                                                     Options?.ToArray(), ToolTip, DataType, ValidationMethod,
                                                     string.Empty, false, ReadOnly, false);
                    }
                    else if (Options is null)
                    {
                        Field = new TextSingleField(Parameters, PropertyName, Header, Required, new string[] { s },
                                                    null, ToolTip, DataType, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                    else
                    {
                        Field = new ListSingleField(Parameters, PropertyName, Header, Required, new string[] { s },
                                                    Options.ToArray(), ToolTip, DataType, ValidationMethod, string.Empty, false, ReadOnly, false);
                    }
                }

                if (Field is null)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(PageLabel))
                {
                    if (DefaultPage is null)
                    {
                        DefaultPage = new Page(Parameters, string.Empty)
                        {
                            Priority = PageAttribute.DefaultPriority,
                            Ordinal  = PageOrdinal++
                        };
                        Pages.Add(DefaultPage);
                        PageByLabel[string.Empty] = DefaultPage;
                    }

                    Page      = DefaultPage;
                    PageLabel = string.Empty;
                }
                else
                {
                    if (!PageByLabel.TryGetValue(PageLabel, out Page))
                    {
                        Page = new Page(Parameters, PageLabel)
                        {
                            Priority = PagePriority,
                            Ordinal  = PageOrdinal++
                        };
                        Pages.Add(Page);
                        PageByLabel[PageLabel] = Page;
                    }
                }

                Field.Priority = FieldPriority;
                Field.Ordinal  = FieldOrdinal++;
                Fields.Add(Field);

                if (string.IsNullOrEmpty(SectionLabel))
                {
                    if (TextAttributes != null)
                    {
                        foreach (TextAttribute TextAttr in TextAttributes)
                        {
                            if (TextAttr.Position == TextPosition.BeforeField)
                            {
                                StringId = TextAttr.StringId;
                                if (StringId > 0)
                                {
                                    Page.Add(new TextElement(Parameters, await Namespace.GetStringAsync(StringId, TextAttr.Label)));
                                }
                                else
                                {
                                    Page.Add(new TextElement(Parameters, TextAttr.Label));
                                }
                            }
                        }
                    }

                    Page.Add(new FieldReference(Parameters, Field.Var));

                    if (TextAttributes != null)
                    {
                        foreach (TextAttribute TextAttr in TextAttributes)
                        {
                            if (TextAttr.Position == TextPosition.AfterField)
                            {
                                StringId = TextAttr.StringId;
                                if (StringId > 0)
                                {
                                    Page.Add(new TextElement(Parameters, await Namespace.GetStringAsync(StringId, TextAttr.Label)));
                                }
                                else
                                {
                                    Page.Add(new TextElement(Parameters, TextAttr.Label));
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (SectionByPageAndSectionLabel is null)
                    {
                        SectionByPageAndSectionLabel = new Dictionary <string, Section>();
                    }

                    s = PageLabel + " \xa0 " + SectionLabel;
                    if (!SectionByPageAndSectionLabel.TryGetValue(s, out Section Section))
                    {
                        Section = new Section(Parameters, SectionLabel);
                        SectionByPageAndSectionLabel[s] = Section;

                        Page.Add(Section);
                    }

                    if (TextAttributes != null)
                    {
                        foreach (TextAttribute TextAttr in TextAttributes)
                        {
                            if (TextAttr.Position == TextPosition.BeforeField)
                            {
                                StringId = TextAttr.StringId;
                                if (StringId > 0)
                                {
                                    Section.Add(new TextElement(Parameters, await Namespace.GetStringAsync(StringId, TextAttr.Label)));
                                }
                                else
                                {
                                    Section.Add(new TextElement(Parameters, TextAttr.Label));
                                }
                            }
                        }
                    }

                    Section.Add(new FieldReference(Parameters, Field.Var));

                    if (TextAttributes != null)
                    {
                        foreach (TextAttribute TextAttr in TextAttributes)
                        {
                            if (TextAttr.Position == TextPosition.AfterField)
                            {
                                StringId = TextAttr.StringId;
                                if (StringId > 0)
                                {
                                    Section.Add(new TextElement(Parameters, await Namespace.GetStringAsync(StringId, TextAttr.Label)));
                                }
                                else
                                {
                                    Section.Add(new TextElement(Parameters, TextAttr.Label));
                                }
                            }
                        }
                    }
                }
            }

            if (EditableObject is IPropertyFormAnnotation PropertyFormAnnotation)
            {
                FormState State = new FormState()
                {
                    Form        = Parameters,
                    PageByLabel = PageByLabel,
                    SectionByPageAndSectionLabel = SectionByPageAndSectionLabel,
                    DefaultPage  = DefaultPage,
                    LanguageCode = Language.Code,
                    Fields       = Fields,
                    Pages        = Pages,
                    FieldOrdinal = FieldOrdinal,
                    PageOrdinal  = PageOrdinal
                };

                await PropertyFormAnnotation.AnnotatePropertyForm(State);
            }

            Fields.Sort(OrderFields);
            Parameters.Title  = Title;
            Parameters.Fields = Fields.ToArray();

            if (Pages != null)
            {
                Pages.Sort(OrderPages);

                foreach (Page Page2 in Pages)
                {
                    Page2.Sort();
                }
            }

            Parameters.Pages = Pages.ToArray();

            return(Parameters);
        }
Exemple #30
0
 public static Column CreateStringColumn(string columnName, int columnIndexInFile, bool isRequired, int stringMaxLenght, RegexValidation regexValidation = RegexValidation.None)
 {
     return(new Column(columnName, columnIndexInFile, isRequired, false, ValueType.String, stringMaxLenght, null, null, 0, 0, regexValidation));
 }
        public async Task <AddRecordVoteResponse> AddRecordVoteAsync(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            AddRecordVoteResponse result = new AddRecordVoteResponse
            {
                IsSucceded = true,
                ResultId   = (int)AddRecordVoteResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.Username, out global::System.Object ousername);
                string username = ousername.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.Hash, out global::System.Object ohash);
                string hash = ohash.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.IsApproval, out global::System.Object oisApproval);
                bool isApproval = Convert.ToBoolean(oisApproval.ToString());

                parameters.TryGetValue(ParameterTypeEnum.MasterAddress, out global::System.Object omasterAddress);
                string masterAddress = omasterAddress.ToString();

                parameters.TryGetValue(ParameterTypeEnum.MasterPrivateKey, out global::System.Object omasterPrivateKey);
                string masterPrivateKey = omasterPrivateKey.ToString();

                parameters.TryGetValue(ParameterTypeEnum.ContractAddress, out global::System.Object ocontractAddress);
                string contractAddress = ocontractAddress.ToString();

                parameters.TryGetValue(ParameterTypeEnum.ContractABI, out global::System.Object ocontractABI);
                string contractABI = ocontractABI.ToString();

                //database helpers
                DBUserAccountHelper dbUserAccountHelper = new DBUserAccountHelper(DBCONNECTION_INFO);
                DBRecordItemHelper  dbRecordItemHelper  = new DBRecordItemHelper(DBCONNECTION_INFO);
                DBRecordVoteHelper  dbRecordVoteHelper  = new DBRecordVoteHelper(DBCONNECTION_INFO);

                //blockchain helper
                BlockchainHelper bh = new BlockchainHelper(telemetryClient, STORAGE_ACCOUNT, RPC_CLIENT, masterAddress, masterPrivateKey);

                telemetryClient.TrackTrace("Validating username length");

                //validate username length
                if (!RegexValidation.IsValidUsername(username))
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordVoteResultEnum.InvalidUsernameLength;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating username existance");

                //validate if account exists
                UserAccount userAccount = dbUserAccountHelper.GetUser(username);

                if (userAccount == null)
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordVoteResultEnum.UsernameNotExists;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating record item existance");

                //validate if record item exists for voting
                RecordItem recordItem = dbRecordItemHelper.GetRecordItem(hash);

                if (recordItem == null)
                {
                    //there is no record item linked with this vote
                    result.IsSucceded = false;
                    result.ResultId   = (int)AddRecordVoteResultEnum.NotExists;
                    return(result);
                }
                else
                {
                    telemetryClient.TrackTrace("Validating record vote existance");

                    //validate if user has voted submit a vote before
                    RecordVote vote = dbRecordVoteHelper.GetRecordVote(hash, username);

                    if (vote != null)
                    {
                        //the user already voted
                        result.IsSucceded = false;
                        result.ResultId   = (int)AddRecordVoteResultEnum.AlreadyVoted;
                        return(result);
                    }
                    else
                    {
                        telemetryClient.TrackTrace("Adding record vote to blockchain");

                        //sending to the blockchain
                        var res_IncreaseOperationAsync = string.Empty;
                        if ((bool)isApproval)
                        {
                            res_IncreaseOperationAsync = await bh.IncreaseApprovalsAsync(hash, contractAddress, contractABI);

                            System.Diagnostics.Trace.TraceInformation($"Add record for approval vote result: {res_IncreaseOperationAsync}");
                        }
                        else
                        {
                            res_IncreaseOperationAsync = await bh.IncreaseDisapprovalsAsync(hash, contractAddress, contractABI);

                            System.Diagnostics.Trace.TraceInformation($"Add record for disapproval vote result: {res_IncreaseOperationAsync }");
                        }

                        if (string.IsNullOrEmpty(res_IncreaseOperationAsync))
                        {
                            //there was an error voting the record in the blockchain
                            result.IsSucceded = false;
                            result.ResultId   = (int)AddRecordVoteResultEnum.BlockchainIssue;
                            return(result);
                        }

                        telemetryClient.TrackTrace("Adding record vote to database");

                        //save record in mongodb
                        vote = new RecordVote
                        {
                            username      = username,
                            hash          = hash,
                            isApproval    = isApproval,
                            transactionId = res_IncreaseOperationAsync,
                            createdDate   = Timezone.GetCustomTimeZone()
                        };

                        //perform insert in mongodb
                        await dbRecordVoteHelper.CreateRecordVote(vote);
                    }
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordVoteResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)AddRecordVoteResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }