private async void OnRegisterCommand()
        {
            RegisterErrorMsg = null;
            if (RegisterUserName == null || RegisterPassword == null || RegisterConfirmPassword == null || RegisterFirstName == null || RegisterLastName == null || RegisterEmail == null)
            {
                RegisterErrorMsg = MessageNames.RegisterBlank;
            }
            else
            {
                RegisterErrorMsg = ValidationUtilities.ValidateInput(RegisterFirstName);
                if (RegisterErrorMsg == null)
                {
                    RegisterErrorMsg = ValidationUtilities.ValidateInput(RegisterLastName);
                    if (RegisterErrorMsg == null)
                    {
                        RegisterErrorMsg = ValidationUtilities.ValidateInput(RegisterUserName);
                        if (RegisterErrorMsg == null)
                        {
                            if (RegexUtilities.IsValidEmail(RegisterEmail))
                            {
                                RegisterErrorMsg = ValidationUtilities.ValidatePassword(RegisterPassword);
                                if (RegisterErrorMsg == null)
                                {
                                    if (RegisterPassword != RegisterConfirmPassword)
                                    {
                                        RegisterErrorMsg = MessageNames.RegisterWrongPasswords;
                                    }
                                    else
                                    {
                                        try
                                        {
                                            _userName.FirstName = RegisterFirstName;
                                            _userName.LastName  = RegisterLastName;
                                            _userName.UserName  = RegisterUserName;
                                            _userName.Password  = RegisterPassword;
                                            _userName.Email     = RegisterEmail;
                                            await _userDataService.RegisterUser(_userName);
                                        }
                                        catch (Exception)
                                        {
                                            RegisterErrorMsg = MessageNames.RegisterUniqueException;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                RegisterErrorMsg = MessageNames.RegisterWrongEmail;
                            }
                        }
                    }
                }
            }

            if (RegisterErrorMsg == null)
            {
                MessagingCenter.Send(this, MessageNames.RegisterdUser);
                _navigationService.GoBack();
            }
        }
示例#2
0
        public IHttpActionResult ResetPassword(SendActivationReq req)
        {
            try
            {
                string currentUsrEmail = HttpUtilities.GetUserNameFromToken(this.Request);
                byte[] salt            = AuthorizationUtilities.generateSalt();
                User   user            = _context.Users.FirstOrDefault(i => i.Id == req.UserId);
                //  if (user.IsActiveUser == false)
                ValidationUtilities.ValidateUserforNewPassword(req.UserId, user);

                string generatedPassword = AuthorizationUtilities.GeneratePassword();
                AuthorizationUtilities.SendPasswordtoUser(user.Email, generatedPassword);
                byte[] pwdhash = AuthorizationUtilities.hash(generatedPassword, user.Salt);
                //  user.Salt = salt;
                user.Password   = pwdhash;//AuthorizationUtilities.hash(generatedPassword, salt);
                user.ModifiedBy = currentUsrEmail;
                // user.UpdatedAt = DateTimeOffset.UtcNow;
                _context.Entry(user).State = System.Data.Entity.EntityState.Modified;
                _context.SaveChanges();
                return(Ok());
            }
            catch (HttpResponseException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                LGSELogger.Error(ex);
                return(InternalServerError(ex));
            }
        }
示例#3
0
        public async Task <IHttpActionResult> PostRole(RoleRequest item)
        {
            try
            {
                string currentUserEmail = HttpUtilities.GetUserNameFromToken(this.Request);
                string message          = ValidationUtilities.ValidateRole(item);
                if (string.IsNullOrEmpty(message))
                {
                    Mapper.Initialize(cfg => cfg.CreateMap <RoleRequest, Role>()
                                      .ForMember(i => i.CreatedBy, j => j.UseValue(currentUserEmail))
                                      );
                    var RoleMap = Mapper.Map <RoleRequest, Role>(item);
                    RoleMap.Id = Guid.NewGuid().ToString();
                    Role current = await InsertAsync(RoleMap);

                    return(CreatedAtRoute("Tables", new { id = current.Id }, current));
                }
                else
                {
                    return(BadRequest(message));
                }
            }
            catch (Exception ex)
            {
                HttpUtilities.ServerError(ex, Request);
                return(null);
            }
        }
示例#4
0
 public IHttpActionResult SendActivationLink(SendActivationReq req)
 {
     try
     {
         string currentUsrEmail = HttpUtilities.GetUserNameFromToken(this.Request);
         var    user            = _context.Users.FirstOrDefault(i => i.Id == req.UserId);
         if (user.IsActiveUser == false)
         {
             return(BadRequest(ErrorCodes.USER_DEACTIVATED_BY_ADMIN.ToString()));
         }
         else if (user.Domain.IsActive == false)
         {
             return(BadRequest(ErrorCodes.DOMAIN_IS_INACTIVE.ToString()));
         }
         ValidationUtilities.ValidateUserforActivationLink(req.UserId, user);
         string otpCode = AuthorizationUtilities.GenerateOTPCode();
         AuthorizationUtilities.SendOTPtoUser(user.Email, otpCode);
         user.OTPCode        = otpCode;
         user.OTPGeneratedAt = DateTimeOffset.UtcNow;
         user.ModifiedBy     = currentUsrEmail;
         // user.UpdatedAt = DateTimeOffset.UtcNow;
         _context.Entry(user).State = System.Data.Entity.EntityState.Modified;
         _context.SaveChanges();
         return(Ok());
     }
     catch (HttpResponseException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         LGSELogger.Error(ex);
         return(InternalServerError(ex));
     }
 }
示例#5
0
        public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Dictionary <string, Operation> > entity, RuleContext context)
        {
            // get all operation objects that are either of get or post type
            var serviceDefinition = (ServiceDefinition)context.Root;
            var listOperations    = entity.Values.SelectMany(opDict => opDict.Where(pair => pair.Key.ToLower().Equals("get") || pair.Key.ToLower().Equals("post")));

            foreach (var opPair in listOperations)
            {
                // if the operation id is already of the type _list we can skip this check
                if (ListRegex.IsMatch(opPair.Value.OperationId))
                {
                    continue;
                }

                var violatingPath = ValidationUtilities.GetOperationIdPath(opPair.Value.OperationId, entity).Key;
                if (ValidationUtilities.IsXmsPageableResponseOperation(opPair.Value))
                {
                    yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty(violatingPath).AppendProperty(opPair.Key).AppendProperty("operationId")), this, opPair.Value.OperationId, XmsPageableViolation));
                }
                else if (ValidationUtilities.IsArrayTypeResponseOperation(opPair.Value, serviceDefinition))
                {
                    yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty(violatingPath).AppendProperty(opPair.Key).AppendProperty("operationId")), this, opPair.Value.OperationId, ArrayTypeViolation));
                }
            }
        }
示例#6
0
        /// <summary>
        /// Reads exactly the specified number of bytes from a stream.
        /// </summary>
        ///
        /// <param name="stream">The stream to read from.</param>
        /// <param name="buffer">The array in which to store bytes.</param>
        /// <param name="offset">The index in <paramref name="buffer"/> of the first byte to
        ///     store.</param>
        /// <param name="count">The number of bytes to store.</param>
        /// <param name="throwIfNoData"><c>true</c> to throw an exception if the end of the stream
        ///     is reached before reading any data. If <c>false</c>, this method returns
        ///     <c>false</c> instead of throwing an exception. An exception is always thrown if
        ///     one or more bytes were read before reaching the end of the stream.</param>
        ///
        /// <returns><c>true</c> if the requested number of bytes were read from the underlying
        ///     stream, or <c>false</c> if the end of the stream was reached without reading any
        ///     bytes and <paramref name="throwIfNoData"/> is <c>true</c>.</returns>
        ///
        /// <exception cref="ArgumentNullException"><paramref name="stream"/> or
        ///     <paramref name="buffer"/> are <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException">The specified
        ///     <paramref name="offset"/> and <paramref name="count"/> fall outside the bounds of
        ///     the <paramref name="buffer"/> array.</exception>
        /// <exception cref="EndOfStreamException">The end of the stream was reached before the
        ///     requested number of bytes were read, and <paramref name="throwIfNoData"/> is
        ///     <c>true</c>.</exception>
        /// <exception cref="IOException">An I/O error occurred.</exception>
        /// <exception cref="NotSupportedException">The stream does not support
        ///     reading.</exception>
        /// <exception cref="ObjectDisposedException">The stream object has been
        ///     disposed.</exception>

        public static bool ReadExactly(this Stream stream, byte[] buffer, int offset, int count, bool throwIfNoData)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            ValidationUtilities.ValidateArraySlice(buffer, offset, count,
                                                   nameof(buffer), nameof(offset), nameof(count));

            int totalBytesRead = 0;

            while (count > 0)
            {
                int bytesRead = stream.Read(buffer, offset, count);
                Debug.Assert(bytesRead >= 0 && bytesRead <= count);

                if (bytesRead == 0)
                {
                    if (!throwIfNoData && totalBytesRead == 0)
                    {
                        return(false);
                    }
                    throw new EndOfStreamException();
                }

                count          -= bytesRead;
                offset         += bytesRead;
                totalBytesRead += bytesRead;
            }

            return(true);
        }
        public void TestValidateRuleThrowsException()
        {
            var vm = new TestViewModel();

            vm.AllRules.Add(new KeyValuePair <string, IValidationRule>(
                                nameof(vm.Property),
                                new DelegateValidationRule <int>(x => throw new Exception("test exception"))
                                ));
            vm.AllRules.Add(new KeyValuePair <string, IValidationRule>(
                                nameof(vm.Property),
                                new DelegateValidationRule <int>(x => new ValidationRuleResult(true, "error"))
                                ));

            ValidationRuleResult[] results = ValidationUtilities.Validate(vm, nameof(vm.Property))
                                             .ToArray();

            Assert.AreEqual(2, results.Length);

            // first rule throws an exception
            Assert.AreEqual(true, results[0].IsError);
            Assert.AreEqual("test exception", results[0].ErrorMessage);

            // second rule yields a failed result
            Assert.AreEqual(true, results[1].IsError);
            Assert.AreEqual("error", results[1].ErrorMessage);
        }
示例#8
0
 // POST tables/User
 public IHttpActionResult PostUser(RegisterRequest request)
 {
     try
     {
         string errorMessage = ValidationUtilities.ValidateUserDetails(request);
         var    domainObj    = DbUtilities.GetDomainDetails(request.Email);
         if (errorMessage.Equals(string.Empty))
         {
             string otpCode   = AuthorizationUtilities.GenerateOTPCode();
             string userEmail = HttpUtilities.GetUserNameFromToken(this.Request);
             DbUtilities.SaveTheUser(request, otpCode, domainObj, userEmail, request.IsActiveUser);
             AuthorizationUtilities.SendOTPtoUser(request.Email, otpCode);
             return(Ok(HttpUtilities.CustomResp(ErrorCodes.USER_CREATED.ToString())));
         }
         else
         {
             return(BadRequest(errorMessage));
         }
     }
     catch (Exception ex)
     {
         LGSELogger.Error(ex);
         return(InternalServerError(ex));
     }
     //return CreatedAtRoute("Tables", new { id = current.Id }, current);
 }
示例#9
0
 // PATCH tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
 public Task PatchUser(string id, Delta <UserEditRequest> patch)
 {
     try
     {
         //Admins can also modify user.
         ValidationUtilities.ValidateEditUserRequest(id, patch.GetEntity(), patch.GetChangedPropertyNames().ToList());
         string requesterEmail = HttpUtilities.GetUserNameFromToken(this.Request);
         var    user           = context.Users.FirstOrDefault(i => i.Email == requesterEmail);
         if (string.IsNullOrEmpty(requesterEmail) || user == null)
         {
             var response = HttpUtilities.FrameHTTPResp(System.Net.HttpStatusCode.BadRequest, Common.Utilities.ErrorCodes.INVALID_TOKEN, string.Empty);
             throw new HttpResponseException(response);
         }
         Delta <User> deltaDest = new Delta <User>();
         foreach (var item in patch.GetChangedPropertyNames())
         {
             object result;
             patch.TryGetPropertyValue(item, out result);
             deltaDest.TrySetPropertyValue(item, result);
         }
         deltaDest.TrySetPropertyValue("ModifiedBy", requesterEmail);
         deltaDest.TrySetPropertyValue("UpdatedAt", DateTimeOffset.UtcNow);
         return(UpdateAsync(id, deltaDest));
     }
     catch (HttpResponseException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         HttpUtilities.ServerError(ex, Request);
         return(null);
     }
 }
        /// <summary>
        /// Verifies whether an LRO PUT operation returns response models for
        /// 200/201 status codes
        /// </summary>
        /// <param name="definitions"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Dictionary <string, Operation> > paths, RuleContext context)
        {
            var serviceDefinition = (ServiceDefinition)context.Root;

            foreach (var path in paths)
            {
                var lroPutOps = path.Value.Where(val => val.Key.ToLower().Equals("put")).Select(val => val.Value);
                foreach (var op in lroPutOps)
                {
                    if (op.Responses == null)
                    {
                        // if put operation has no response model, let some other validation rule handle the violation
                        continue;
                    }
                    foreach (var resp in op.Responses)
                    {
                        if (resp.Key == "200" || resp.Key == "201")
                        {
                            var modelRef = resp.Value?.Schema?.Reference ?? string.Empty;
                            if (!serviceDefinition.Definitions.ContainsKey(modelRef.StripDefinitionPath()))
                            {
                                var violatingVerb = ValidationUtilities.GetOperationIdVerb(op.OperationId, path);
                                yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty(path.Key).AppendProperty(violatingVerb).AppendProperty("responses").AppendProperty(resp.Key)),
                                                                   this, op.OperationId, resp.Key));
                            }
                        }
                    }
                }
            }
        }
示例#11
0
        /// <summary>
        /// Verifies whether the location property for a tracked resource has the x-ms-mutability extension set correctly
        /// </summary>
        /// <param name="definitions"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Schema> definitions, RuleContext context)
        {
            var trackedResources = context.TrackedResourceModels;

            foreach (var resource in trackedResources)
            {
                var modelHierarchy         = ValidationUtilities.EnumerateModelHierarchy(resource, definitions);
                var modelsWithLocationProp = modelHierarchy.Where(model => (definitions[model].Required?.Contains("location") == true) &&
                                                                  (definitions[model].Properties?.ContainsKey("location") == true));
                if (modelsWithLocationProp.Any())
                {
                    var modelWithLocationProp = modelsWithLocationProp.First();
                    if (definitions[modelWithLocationProp].Properties["location"].Extensions?.ContainsKey("x-ms-mutability") != true)
                    {
                        yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty("properties").AppendProperty("location")), this, modelWithLocationProp));
                    }
                    else
                    {
                        var jObject = JsonConvert.DeserializeObject <object[]>(definitions[modelWithLocationProp].Properties["location"].Extensions["x-ms-mutability"].ToString());
                        // make sure jObject and the expected mutability properties have exact same elements
                        if (jObject.Except(LocationPropertyMutability).Any() || LocationPropertyMutability.Except(jObject).Any())
                        {
                            yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty("properties").AppendProperty("location").AppendProperty("x-ms-mutability")), this, resource));
                        }
                    }
                }
            }
        }
示例#12
0
        public async Task <string> Validate(RoleGetOptions options)
        {
            try
            {
                _logger.LogInformation("Start role validating.");

                string result = ValidationUtilities.ValidateRoleName(options.Name);
                if (!string.IsNullOrEmpty(result))
                {
                    return(result);
                }

                if (!options.Id.HasValue)
                {
                    var models = await _dao.Get(options);

                    if (models.Count() > 0)
                    {
                        string message = "Role with same user name have been already created. Please try another.";
                        _logger.LogInformation(message);
                        return(message);
                    }
                }

                _logger.LogInformation("Role successfuly validated.");
                return(null);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
        }
示例#13
0
        /// <summary>
        /// This rule passes if the paths contain reference to exactly one of the namespace resources
        /// </summary>
        /// <param name="paths"></param>
        /// <returns></returns>
        public override bool IsValid(Dictionary <string, Dictionary <string, Operation> > paths, RuleContext context, out object[] formatParameters)
        {
            IEnumerable <string> resourceProviders = ValidationUtilities.GetResourceProviders(paths);

            formatParameters = new [] { string.Join(", ", resourceProviders) };
            return(resourceProviders.ToList().Count <= 1);
        }
        // Verifies if a tracked resource has a corresponding PATCH operation
        public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Schema> definitions, RuleContext context)
        {
            ServiceDefinition serviceDefinition = (ServiceDefinition)context.Root;
            // enumerate all the PATCH operations
            IEnumerable <Operation> patchOperations = ValidationUtilities.GetOperationsByRequestMethod("patch", serviceDefinition);

            foreach (var op in patchOperations)
            {
                var reqModels = op.Parameters.Where(p => p.In == ParameterLocation.Body).Select(p => p.Schema?.Reference?.StripDefinitionPath()).Where(p => !string.IsNullOrEmpty(p));
                foreach (var reqModel in reqModels)
                {
                    // select all models that have properties set to required
                    var reqProps = ValidationUtilities.EnumerateRequiredProperties(reqModel, definitions);

                    // select all models that have properties with default values
                    var defValProps = ValidationUtilities.EnumerateDefaultValuedProperties(reqModel, definitions);

                    var modelHierarchy = ValidationUtilities.EnumerateModelHierarchy(reqModel, definitions);

                    foreach (var reqProp in reqProps)
                    {
                        var modelContainingReqProp = modelHierarchy.First(model => definitions[model].Required?.Contains(reqProp) == true);
                        yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty(modelContainingReqProp).AppendProperty("required")), this, "required", op.OperationId, modelContainingReqProp, reqProp));
                    }

                    foreach (var defValProp in defValProps)
                    {
                        var modelContainingDefValProp = modelHierarchy.First(model => definitions[model].Properties?.Contains(defValProp) == true);
                        yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty(modelContainingDefValProp).AppendProperty("properties").AppendProperty(defValProp.Key)), this, "default-valued", op.OperationId, modelContainingDefValProp, defValProp.Key));
                    }
                }
            }
        }
示例#15
0
 // Token: 0x06000CA3 RID: 3235 RVA: 0x0005572C File Offset: 0x0005392C
 private void DrawCheckAvailabilityButton(Rect position)
 {
     GUI.enabled = (!string.IsNullOrEmpty(this._characterName) && !this._checkButtonClicked && !this._waitingForWsReturn);
     if (GUITools.Button(new Rect(225f, 60f, 110f, 24f), new GUIContent("Check Availability"), BlueStonez.buttondark_small))
     {
         this.HideKeyboard();
         this._availableNames.Clear();
         this._checkButtonClicked = true;
         this._targetHeight       = 260f;
         if (!ValidationUtilities.IsValidMemberName(this._characterName, ApplicationDataManager.CurrentLocale.ToString()))
         {
             this._feedbackMessageColor = Color.red;
             this._errorMessage         = "'" + this._characterName + "' is not a valid name!";
         }
         else
         {
             this._waitingForWsReturn = true;
             UserWebServiceClient.IsDuplicateMemberName(this._characterName, new Action <bool>(this.IsDuplicatedNameCallback), delegate(Exception ex)
             {
                 this._waitingForWsReturn   = false;
                 this._feedbackMessageColor = Color.red;
                 this._errorMessage         = "Our server had an error, please try again.";
             });
         }
     }
     GUI.enabled = true;
 }
 private static bool ValidateValue(object value, ValidationContext validationContext,
                                   List <ValidationResult> validationResults, IEnumerable <ValidationAttribute> validationAttributes,
                                   string memberPath)
 {
     if (validationResults == null)
     {
         Validator.ValidateValue(value, validationContext, validationAttributes);
     }
     else
     {
         // todo, needs to be array aware
         List <ValidationResult> currentResults = new List <ValidationResult>();
         if (!Validator.TryValidateValue(value, validationContext, currentResults, validationAttributes))
         {
             // transform the validation results by applying the member path to the results
             if (!string.IsNullOrEmpty(memberPath))
             {
                 currentResults = ValidationUtilities.ApplyMemberPath(currentResults, memberPath).ToList();
             }
             validationResults.AddRange(currentResults);
             return(false);
         }
     }
     return(true);
 }
        /// <summary>
        /// This method recursively applies the specified validation errors to this instance
        /// and any nested instances (based on member paths specified in the validation results).
        /// Since this method correctly handles complex types, this method should be used rather
        /// than directly applying results to the collection.
        /// </summary>
        /// <param name="instance">The target entity or complex type to apply the errors to.</param>
        /// <param name="validationResults">The validation results to apply.</param>
        internal static void ApplyValidationErrors(object instance, IEnumerable <ValidationResult> validationResults)
        {
            // first apply the errors to this instance
            Entity entityInstance = instance as Entity;

            if (entityInstance != null)
            {
                entityInstance.ValidationResultCollection.ReplaceErrors(validationResults);
            }
            else
            {
                ((ComplexObject)instance).ValidationResultCollection.ReplaceErrors(validationResults);
            }

            // next enumerate all complex members and apply nested validation results
            MetaType metaType = MetaType.GetMetaType(instance.GetType());

            foreach (MetaMember complexMember in metaType.DataMembers.Where(p => p.IsComplex && !p.IsCollection))
            {
                // filter the results to only those with a member name that begins with a dotted path
                // starting at the current complex member
                IEnumerable <ValidationResult> results = validationResults.Where(p => p.MemberNames.Any(q => !string.IsNullOrEmpty(q) && q.StartsWith(complexMember.Member.Name + ".", StringComparison.Ordinal)));

                ComplexObject complexObject = (ComplexObject)complexMember.GetValue(instance);
                if (complexObject != null)
                {
                    results = ValidationUtilities.RemoveMemberPrefix(results, complexMember.Member.Name);
                    ApplyValidationErrors(complexObject, results);
                }
            }
        }
        public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Dictionary <string, Operation> > entity, RuleContext context)
        {
            // get all operation objects that are either of get or post type
            ServiceDefinition serviceDefinition = context.Root;
            var listOperations = entity.Values.SelectMany(opDict => opDict.Where(pair => pair.Key.ToLower().Equals("get") || pair.Key.ToLower().Equals("post")));

            foreach (var opPair in listOperations)
            {
                // if the operation id is not of type _list* or does not return an array type, skip
                if (!ListRegex.IsMatch(opPair.Value.OperationId) || !ValidationUtilities.IsXmsPageableResponseOperation(opPair.Value))
                {
                    continue;
                }

                string collType = opPair.Value.Responses.GetValueOrNull("200")?.Schema?.Reference?.StripDefinitionPath();
                // if no response type defined skip
                if (collType == null)
                {
                    continue;
                }

                var collTypeDef = serviceDefinition.Definitions[collType];
                // if collection object has 2 properties or less (x-ms-pageable objects can have the nextlink prop)
                // and the object does not have a property named "value", show the warning
                if ((collTypeDef.Properties?.Count <= 2) && collTypeDef.Properties.All(prop => !(prop.Key.ToLower().Equals("value") && prop.Value.Type == DataType.Array)))
                {
                    var violatingPath = ValidationUtilities.GetOperationIdPath(opPair.Value.OperationId, entity);
                    yield return(new ValidationMessage(new FileObjectPath(context.File,
                                                                          context.Path.AppendProperty(violatingPath.Key).AppendProperty(opPair.Key).AppendProperty("responses").AppendProperty("200").AppendProperty("schema")),
                                                       this, collType, opPair.Value.OperationId));
                }
            }
        }
示例#19
0
        /// <summary>
        /// Reads concatenated data from the underlying sequence of source readers.
        /// </summary>
        ///
        /// <param name="buffer">The array in which to store data.</param>
        /// <param name="index">The index in <paramref name="buffer"/> of the first byte to
        ///     store.</param>
        /// <param name="count">The maximum number of bytes to store.</param>
        ///
        /// <returns>The actual number of bytes read, which may be less than the amount requested
        ///     or zero if the end of the concatenated sources is reached.</returns>
        ///
        /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is
        ///     <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> or
        ///    <paramref name="count"/> are negative or fall outside the array
        ///    bounds.</exception>
        /// <exception cref="IOException">An I/O error occurred.</exception>
        /// <exception cref="ObjectDisposedException">This reader or one or more source readers
        ///     have been disposed.</exception>

        public override int Read(char[] buffer, int index, int count)
        {
            if (_sources == null)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            ValidationUtilities.ValidateArraySlice(buffer, index, count,
                                                   nameof(buffer), nameof(index), nameof(count));

            int total = 0;

            while (count > 0)
            {
                if (_sources.Count == 0)
                {
                    return(total);
                }
                int bytesRead = _sources.Peek().Read(buffer, index, count);
                if (bytesRead == 0)
                {
                    _sources.Dequeue().Dispose();
                }
                total += bytesRead;
                count -= bytesRead;
                index += bytesRead;
            }

            return(total);
        }
        public string Validate(Cart model)
        {
            try
            {
                _logger.LogInformation("Start cart validating.");
                StringBuilder builder = new StringBuilder();

                if (!ValidationUtilities.MoreThanValueRule(model.Count))
                {
                    builder.AppendLine("You can't add zero products to cart.");
                }

                string message = builder.ToString();
                if (!string.IsNullOrEmpty(message))
                {
                    return(message);
                }

                _logger.LogInformation("Cart successfuly validated.");
                return(null);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
        }
示例#21
0
        public void Init()
        {
            TestId = Guid.NewGuid().ToString("N").Substring(0, 8);
            Console.WriteLine("Running test " + TestId + ". If failed AND log uploaded is enabled, log can be find in " + Path.Combine(DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), TestId));
            if (_enableRealtimeLogUpload)
            {
                TimerTask = new Task(() =>
                {
                    TestTimer = new Timer()
                    {
                        Interval  = 1000,
                        Enabled   = true,
                        AutoReset = true
                    };
                    TestTimer.Elapsed += PeriodicUploadLog;
                    TestTimer.Start();
                });
                TimerTask.Start();
            }

            ValidationUtilities.ValidateEnvVariable("JAVA_HOME");

            if (!Directory.Exists(BinFolder))
            {
                throw new InvalidOperationException(BinFolder + " not found in current directory, cannot init test");
            }
        }
        /// <inheritdoc />
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            if (ForeignKey.ForeignColumns.Count > 0)
            {
                var ctxt = new ValidationContext(ForeignKey, validationContext.Items);
                ctxt.InitializeServiceProvider(validationContext.GetService);
                ValidationUtilities.TryCollectResults(ctxt, ForeignKey, results);
            }
            else
            {
                if (string.IsNullOrEmpty(ForeignKey.Name))
                {
                    results.Add(new ValidationResult(ErrorMessages.ForeignKeyNameCannotBeNullOrEmpty));
                }

                if (string.IsNullOrEmpty(ForeignKey.ForeignTable))
                {
                    results.Add(new ValidationResult(ErrorMessages.ForeignTableNameCannotBeNullOrEmpty));
                }
            }

            return(results);
        }
示例#23
0
        public async Task <string> Validate(DepartmentGetOptions options)
        {
            try
            {
                _logger.LogInformation("Start department validating.");

                string result = ValidationUtilities.ValidateDepartmentFullName(options.FullName);
                if (!string.IsNullOrEmpty(result))
                {
                    return(result);
                }

                var models = await _dao.Get(options);

                if (models.Count() > 0)
                {
                    string message = "Department with same name have been already created. Please try another.";
                    _logger.LogInformation(message);
                    return(message);
                }

                _logger.LogInformation("Department successfuly validated.");
                return(null);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
        }
示例#24
0
        public async Task<string> ValidateUser(UserGetOptions options)
        {
            try
            {
                _logger.LogInformation("Start user name and email validating.");

                string result = ValidationUtilities.ValidateUserName(options.Username);
                if (!string.IsNullOrEmpty(result))
                    return result;

                result = ValidationUtilities.ValidateEmail(options.Email);
                if (!string.IsNullOrEmpty(result))
                    return result;

                var users = await _dao.Get(options);
                if (users.Where(o => o.Username != options.Username).Count() > 0)
                {
                    string message = "User with same user name or email have been already created. Please try another or try to sign in.";
                    _logger.LogInformation(message);
                    return message;
                }

                _logger.LogInformation("User name and email successfuly validated.");
                return null;
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
        }
 // Token: 0x06000D02 RID: 3330 RVA: 0x00059AF8 File Offset: 0x00057CF8
 private void Login(string emailAddress, string password)
 {
     CmunePrefs.WriteKey <bool>(CmunePrefs.Key.Player_AutoLogin, this._rememberPassword);
     if (this._rememberPassword)
     {
         CmunePrefs.WriteKey <string>(CmunePrefs.Key.Player_Password, password);
         CmunePrefs.WriteKey <string>(CmunePrefs.Key.Player_Email, emailAddress);
     }
     this._errorAlpha = 1f;
     if (string.IsNullOrEmpty(emailAddress))
     {
         LoginPanelGUI.ErrorMessage = LocalizedStrings.EnterYourEmailAddress;
     }
     else if (string.IsNullOrEmpty(password))
     {
         LoginPanelGUI.ErrorMessage = LocalizedStrings.EnterYourPassword;
     }
     else if (!ValidationUtilities.IsValidEmailAddress(emailAddress))
     {
         LoginPanelGUI.ErrorMessage = LocalizedStrings.EmailAddressIsInvalid;
     }
     else if (!ValidationUtilities.IsValidPassword(password))
     {
         LoginPanelGUI.ErrorMessage = LocalizedStrings.PasswordIsInvalid;
     }
     else
     {
         this.Hide();
         UnityRuntime.StartRoutine(Singleton <AuthenticationManager> .Instance.StartLoginMemberEmail(emailAddress, password));
     }
 }
示例#26
0
 /// <summary>
 /// Populates list of resources, tracked resources and proxy resources
 /// </summary>
 private void PopulateResourceTypes(ServiceDefinition serviceDefinition)
 {
     this.ResourceModels              = ValidationUtilities.GetResourceModels(serviceDefinition).ToList();
     this.TrackedResourceModels       = ValidationUtilities.GetTrackedResources(this.ResourceModels, serviceDefinition.Definitions).ToList();
     this.ChildTrackedResourceModels  = ValidationUtilities.GetChildTrackedResourcesWithImmediateParent(serviceDefinition).ToList();
     this.ParentTrackedResourceModels = ValidationUtilities.GetParentTrackedResources(this.TrackedResourceModels, this.ChildTrackedResourceModels).ToList();
     this.ProxyResourceModels         = this.ResourceModels.Except(this.TrackedResourceModels).ToList();
 }
 // Token: 0x06001226 RID: 4646 RVA: 0x0006AF48 File Offset: 0x00069148
 public static bool ValidateMemberName(string name, LocaleType locale = LocaleType.en_US)
 {
     if (locale != LocaleType.ko_KR)
     {
         return(ValidationUtilities.IsValidMemberName(name));
     }
     return(ValidationUtilities.IsValidMemberName(name, "ko-KR"));
 }
        public string this[string columnName]
        {
            get
            {
                switch (columnName)
                {
                case nameof(Name):
                    if (string.IsNullOrWhiteSpace(Name))
                    {
                        return("Required");
                    }

                    if (ValidationUtilities.ValidateName(Name) != null)
                    {
                        return("Must be a valid identifier");
                    }

                    if (Name.StartsWith(" "))
                    {
                        return("Can't start with a space");
                    }

                    if (Name.EndsWith(" "))
                    {
                        return("Can't end with a space");
                    }

                    if (_existingNames != null && _existingNames.Any(s => string.Equals(s, Name, StringComparison.OrdinalIgnoreCase)))
                    {
                        return("Duplicated name");
                    }

                    return(null);

                case nameof(SelectedFieldType):
                    if (SelectedFieldType == null)
                    {
                        return("Required");
                    }
                    return(null);

                case nameof(Prompt):
                    if (string.IsNullOrWhiteSpace(Prompt))
                    {
                        return("Required");
                    }

                    if (ValidationUtilities.ValidateFieldPrompt(Prompt) != null)
                    {
                        return("Cannot end in a colon or space");
                    }

                    return(null);
                }
                return(null);
            }
        }
示例#29
0
        /// <summary>
        /// Initializes a new data stream using the specified data.
        /// </summary>
        ///
        /// <param name="data">The array to wrap.</param>
        /// <param name="offset">The index of the first byte to wrap.</param>
        /// <param name="count">The number of bytes to wrap.</param>
        ///
        /// <exception cref="ArgumentNullException"><paramref name="data"/> is
        ///     <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> and/or
        ///      <paramref name="count"/> fall outside the bounds of the array.</exception>

        public ProtocolReader(byte[] data, int offset, int count)
        {
            ValidationUtilities.ValidateArraySlice(data, offset, count,
                                                   nameof(data), nameof(offset), nameof(count));

            _buffer      = data;
            _position    = _originalPosition = offset;
            _endPosition = offset + count;
        }
        /// <summary>
        /// Validation fails iof tracked resource fails to meet one of the four required criteria.
        /// </summary>
        /// <param name="definitions">Operation Definition to validate</param>
        /// <param name="formatParameters">The noun to be put in the failure message</param>
        /// <returns></returns>
        public override bool IsValid(Dictionary <string, Schema> definitions, RuleContext context, out object[] formatParameters)
        {
            IEnumerable <Operation> getOperations = ValidationUtilities.GetOperationsByRequestMethod("get", (ServiceDefinition)context.Root);

            foreach (KeyValuePair <string, Schema> definition in definitions)
            {
                if (!exemptedNames.IsMatch(definition.Key) && ValidationUtilities.IsTrackedResource(definition.Value, definitions))
                {
                    bool getCheck = getOperations.Any(operation =>
                                                      operation.Responses.Any(response =>
                                                                              response.Key.Equals("200") &&
                                                                              response.Value.Schema != null &&
                                                                              response.Value.Schema.Reference != null &&
                                                                              response.Value.Schema.Reference.EndsWith("/" + definition.Key)
                                                                              )
                                                      );
                    if (!getCheck)
                    {
                        formatParameters    = new object[2];
                        formatParameters[0] = definition.Key;
                        formatParameters[1] = 1;
                        return(false);
                    }

                    bool listByResourceGroupCheck = this.ListByXCheck(getOperations, listByRgRegEx, definition.Key, definitions);
                    if (!listByResourceGroupCheck)
                    {
                        formatParameters    = new object[2];
                        formatParameters[0] = definition.Key;
                        formatParameters[1] = 2;
                        return(false);
                    }

                    bool listBySubscriptionIdCheck = this.ListByXCheck(getOperations, listBySidRegEx, definition.Key, definitions);
                    if (!listBySubscriptionIdCheck)
                    {
                        formatParameters    = new object[2];
                        formatParameters[0] = definition.Key;
                        formatParameters[1] = 3;
                        return(false);
                    }

                    bool schemaResult = this.HandleSchema(definition.Value, definitions);
                    if (!schemaResult)
                    {
                        formatParameters    = new object[2];
                        formatParameters[0] = definition.Key;
                        formatParameters[1] = 4;
                        return(false);
                    }
                }
            }

            formatParameters = new object[0];
            return(true);
        }