private void AssertParameterOfTypeIsSupported <T>()
        {
            Type type;
            Type nullableArg;
            bool isNullable = false;

            if (typeof(T).GetTypeInfo().IsNullable(out nullableArg))
            {
                type       = nullableArg;
                isNullable = true;
            }
            else
            {
                type = typeof(T);
            }

            string actionName = "Action_" + type.Name + (isNullable ? "_Nullable" : "");

            var discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.RouteSupportedParametersController));
            var ctrl       = discoverer.GetControllers(null).Single();
            var action     = ctrl.Actions.Single(x => x.Name == actionName.ToLower());

            var errors = new ParametersValidator().GetParametersErrors(action);

            Assert.Equal(isNullable, errors.Any());
        }
Пример #2
0
        public void InfoWithNoParametersInTheListIsValid()
        {
            var info = new Info();

            var parametersValidator = new ParametersValidator(info);
            Assert.True(parametersValidator.IsValid);
        }
Пример #3
0
 public ConsoleController(string finishRange, string instruction)
 {
     _checker       = new ParametersValidator(finishRange);
     _consoleViewer = new Viewer(DefaultSettings.START_MESSAGE);
     _finishRange   = finishRange;
     _instruction   = instruction;
 }
Пример #4
0
        public void InfoWithNoParametersInTheListIsValid()
        {
            var info = new Info();

            var parametersValidator = new ParametersValidator(info);

            Assert.True(parametersValidator.IsValid);
        }
Пример #5
0
        /// <summary>
        /// Gets property info based on property expression.
        /// </summary>
        /// <typeparam name="TEntity">Entity type.</typeparam>
        /// <typeparam name="TProperty">Member type.</typeparam>
        /// <param name="memberExpression">Member expression.</param>
        /// <returns>Member info.</returns>
        public static MemberInfo GetMemberInfo <TEntity, TProperty>(Expression <Func <TEntity, TProperty> > memberExpression)
        {
            ParametersValidator.IsNotNull(memberExpression, () => memberExpression);

            var memberAccess = (MemberExpression)memberExpression.Body;

            return(memberAccess.Member);
        }
Пример #6
0
        private ControllersValidator GetCtrlValidator()
        {
            var store           = new AuthorizationPolicyStore();
            var paramValidator  = new ParametersValidator();
            var actionValidator = new ActionsValidator(paramValidator, store);

            return(new ControllersValidator(actionValidator, store));
        }
 /// <summary>
 /// .ctor. Try to acquire lock with given timeout.
 /// <exception cref="InvalidOperationException"> If wrong SlimLockMode specified</exception>
 /// <exception cref="ApplicationException"> If lock cannot be acquired during timeout</exception>
 /// <exception cref="ArgumentNullException"> alock is null</exception>
 /// <exception cref="LockRecursionException">
 /// <see cref="ReaderWriterLockSlim.TryEnterReadLock(System.TimeSpan)"/>
 /// <see cref="ReaderWriterLockSlim.TryEnterUpgradeableReadLock(System.TimeSpan)"/>
 /// <see cref="ReaderWriterLockSlim.TryEnterWriteLock(System.TimeSpan)"/>
 /// </exception>
 /// </summary>
 /// <param name="alock">Lock object</param>
 /// <param name="mode">Mode to acquire lock</param>
 /// <param name="timeout">Timeout to acquire lock</param>
 public DisposableReaderWriterLockSlim(ReaderWriterLockSlim alock, TimeSpan timeout, SlimLockMode mode = SlimLockMode.Read)
 {
     ParametersValidator.IsNotNull(alock, () => alock);
     _lock    = alock;
     _mode    = mode;
     _timeout = timeout;
     AcquireLock();
     Logger.TraceFormat("lock created timeout={0}, mode ={1}", timeout, mode);
 }
Пример #8
0
        /// <summary>
        /// Gets Where expression by object type, property name and selector value.
        /// </summary>
        /// <typeparam name="T">Object type.</typeparam>
        /// <param name="property">Property name.</param>
        /// <param name="value">Object value.</param>
        /// <returns></returns>
        public static Expression <Func <T, bool> > GetWhereEqualExpression <T>(string property, object value) where T : class
        {
            ParametersValidator.IsNotNullOrWhiteSpace(property, () => property);
            ParametersValidator.IsNotNull(value, () => value);

            var propertyInfo = typeof(T).GetProperty(property);

            return(GetWhereEqualExpression <T>(propertyInfo, value));
        }
 /// <summary>
 /// Wraps action into try/finally statement with getting a read lock in try and releasing in finally.
 /// </summary>
 /// <param name="alock">Lock to handle</param>
 /// <param name="action">Action to execute</param>
 /// <param name="timeout">Timeout to get lock</param>
 public static void WithReadLock(this ReaderWriterLockSlim alock, Action action, TimeSpan timeout)
 {
     ParametersValidator.IsNotNull(alock, () => alock);
     ParametersValidator.IsNotNull(action, () => action);
     Logger.TraceFormat("Runnig action {0} with slim lock {1} and timeout {2} with read lock", action, alock, timeout);
     using (new DisposableReaderWriterLockSlim(alock, timeout))
     {
         action();
     }
 }
 /// <summary>
 /// Wraps action into try/finally statement with getting a write lock in try and releasing in finally.
 /// Default timeout of <see cref="DisposableReaderWriterLockSlim"/> is used.
 /// </summary>
 /// <param name="alock">Lock to handle</param>
 /// <param name="action">Action to execute</param>
 /// <param name="timeout">TImeout to get write lock</param>
 public static void WithWriteLock(this ReaderWriterLock alock, Action action, TimeSpan timeout)
 {
     ParametersValidator.IsNotNull(alock, () => alock);
     ParametersValidator.IsNotNull(action, () => action);
     Logger.TraceFormat("Runnig action {0} with lock {1} with write lock and timeout {2}", action, alock, timeout);
     using (new DisposableReaderWriterLock(alock, timeout, LockMode.Write))
     {
         action();
     }
 }
 /// <summary>
 /// Wraps action into try/finally statement with getting a write lock in try and releasing in finally.
 /// Default timeout of <see cref="DisposableReaderWriterLockSlim"/> is used.
 /// </summary>
 /// <param name="alock">Lock to handle</param>
 /// <param name="action">Action to execute</param>
 public static void WithWriteLock(this ReaderWriterLockSlim alock, Action action)
 {
     ParametersValidator.IsNotNull(alock, () => alock);
     ParametersValidator.IsNotNull(action, () => action);
     Logger.TraceFormat("Runnig action {0} with slim lock {1} with write lock", action, alock);
     using (new DisposableReaderWriterLockSlim(alock, SlimLockMode.Write))
     {
         action();
     }
 }
 /// <summary>
 /// Wraps any action into a using statement
 /// </summary>
 /// <param name="d">Disposable to handle</param>
 /// <param name="action">Action to execute</param>
 public static void RunSafe(this IDisposable d, Action action)
 {
     ParametersValidator.IsNotNull(d, () => d);
     ParametersValidator.IsNotNull(action, () => action);
     Logger.TraceFormat("Runnig action {0} with disposable {1}", action, d);
     using (d)
     {
         action();
     }
 }
 /// <summary>
 /// Wraps action into try/finally statement with getting a read lock in try and releasing in finally.
 /// Default timeout of <see cref="DisposableReaderWriterLockSlim"/> is used.
 /// </summary>
 /// <param name="alock">Lock to handle</param>
 /// <param name="action">Action to execute</param>
 public static void WithReadLock(this ReaderWriterLock alock, Action action)
 {
     ParametersValidator.IsNotNull(alock, () => alock);
     ParametersValidator.IsNotNull(action, () => action);
     Logger.TraceFormat("Runnig action {0} with lock {1} with read lock", action, alock);
     using (new DisposableReaderWriterLock(alock))
     {
         action();
     }
 }
Пример #14
0
        public void InfoWithParametersWithValueAndValueNameIsValid()
        {
            var info = new Info();
            var value = "123";
            var valueName = "HSAS";
            var parameter = new Parameter(valueName, value);
            info.Parameters.Add(parameter);

            var parametersValidator = new ParametersValidator(info);
            Assert.True(parametersValidator.IsValid);
        }
Пример #15
0
        /// <summary>
        /// Joins two expressions with logical Or.
        /// </summary>
        /// <typeparam name="T">Object type.</typeparam>
        /// <param name="first">First expression.</param>
        /// <param name="second">Second expression.</param>
        /// <returns>Join of two expressions with logical And.</returns>
        public static Expression <Func <T, bool> > Or <T>(Expression <Func <T, bool> > first, Expression <Func <T, bool> > second)
        {
            ParametersValidator.IsNotNull(first, () => first);
            ParametersValidator.IsNotNull(second, () => second);

            var invokedExpr   = System.Linq.Expressions.Expression.Invoke(second, first.Parameters);
            var andExpression = System.Linq.Expressions.Expression.OrElse(first.Body, invokedExpr);
            var result        = System.Linq.Expressions.Expression.Lambda <Func <T, bool> >(andExpression, first.Parameters[0]);

            return(result);
        }
Пример #16
0
        public void InfoWithParametersWithValueAndValueNameNullIsInvalid()
        {
            var info = new Info();
            var value = "13123";
            string valueName = null;
            var parameter = new Parameter(valueName, value);
            info.Parameters.Add(parameter);

            var parametersValidator = new ParametersValidator(info);
            Assert.False(parametersValidator.IsValid);
            Assert.Equal(typeof(ParameterError), parametersValidator.Errors.ElementAt(0).GetType());
        }
Пример #17
0
        public void InfoWithParametersWithValueAndValueNameIsValid()
        {
            var info      = new Info();
            var value     = "123";
            var valueName = "HSAS";
            var parameter = new Parameter(valueName, value);

            info.Parameters.Add(parameter);

            var parametersValidator = new ParametersValidator(info);

            Assert.True(parametersValidator.IsValid);
        }
Пример #18
0
        /// <summary>
        /// Gets Where expression by object type, property info and selector value.
        /// </summary>
        /// <typeparam name="T">Object type.</typeparam>
        /// <param name="property">Property info.</param>
        /// <param name="value">Object value.</param>
        /// <returns></returns>
        public static Expression <Func <T, bool> > GetWhereEqualExpression <T>(PropertyInfo property, object value) where T : class
        {
            ParametersValidator.IsNotNull(property, () => property);
            ParametersValidator.IsNotNull(value, () => value);

            var parameter          = System.Linq.Expressions.Expression.Parameter(typeof(T), "x");
            var propertyExpression = System.Linq.Expressions.Expression.MakeMemberAccess(parameter, property);
            var constExpression    = System.Linq.Expressions.Expression.Constant(value, value.GetType());
            var body   = System.Linq.Expressions.Expression.Equal(propertyExpression, constExpression);
            var result = System.Linq.Expressions.Expression.Lambda <Func <T, bool> >(body, parameter);

            return(result);
        }
Пример #19
0
        public void InfoWithParametersWithValueAndValueNameNullIsInvalid()
        {
            var    info      = new Info();
            var    value     = "13123";
            string valueName = null;
            var    parameter = new Parameter(valueName, value);

            info.Parameters.Add(parameter);

            var parametersValidator = new ParametersValidator(info);

            Assert.False(parametersValidator.IsValid);
            Assert.Equal(typeof(NamedValueError <Parameter>), parametersValidator.Errors.ElementAt(0).GetType());
        }
Пример #20
0
        public static ParametersValidationResult CreateSession(ISessionParameters parameters, out ISession session)
        {
            ParametersValidator validator = new ParametersValidator(parameters);
            var validationResult          = validator.Validate();

            if (validationResult == ParametersValidationResult.Valid)
            {
                session = new Session(parameters);
                System.Diagnostics.Debug.WriteLine("validtionResult: {0}", validationResult);
            }
            else
            {
                session = null;
            }
            return(validationResult);
        }
Пример #21
0
        public override Filter Preprocess()
        {
            Filter delegateFilter;

            if (string.IsNullOrEmpty(this.SqlExpression))
            {
                throw new FilterException(SRClient.PropertyIsNullOrEmpty("SqlExpression"));
            }
            if (this.SqlExpression.Length > 1024)
            {
                throw new FilterException(SRClient.SqlFilterStatmentTooLong(this.SqlExpression.Length, 1024));
            }
            this.EnsureCompatibilityLevel();
            try
            {
                SqlFilter.CompiledItem compiledItem = (SqlFilter.CompiledItem)SqlFilter.compiledDelegateCache.Get(this.SqlExpression, null);
                if (compiledItem == null)
                {
                    SqlFilterParserOutput sqlFilterParserOutput = SqlFilterParser.Parse(this.SqlExpression);
                    (new SqlFilter.ExpressionValidator()).Validate(sqlFilterParserOutput.ExpressionTree);
                    Func <BrokeredMessage, IDictionary <string, object>, bool?> func = sqlFilterParserOutput.ExpressionTree.Compile();
                    compiledItem = new SqlFilter.CompiledItem(func, sqlFilterParserOutput.RequiredParameters);
                    SqlFilter.CompiledItem compiledItem1 = (SqlFilter.CompiledItem)SqlFilter.compiledDelegateCache.AddOrGetExisting(this.SqlExpression, compiledItem, SqlFilter.defaultCachePolicy, null);
                    if (compiledItem1 != null)
                    {
                        compiledItem = compiledItem1;
                    }
                }
                ParametersValidator.Validate(true, compiledItem.RequiredParameters, this.Parameters);
                delegateFilter = new DelegateFilter(compiledItem.Delegate, this.Parameters);
            }
            catch (FilterException filterException)
            {
                throw;
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                if (!Fx.IsFatal(exception))
                {
                    throw new FilterException(exception.Message, exception);
                }
                throw;
            }
            return(delegateFilter);
        }
Пример #22
0
        static void Main(string[] args)
        {
            var parametersValidator = new ParametersValidator();
            var parametersAreValid  = parametersValidator.Validate(args);

            if (parametersAreValid)
            {
                string nameOfFile;
                var    parameters = CommandLineParser.Parse(args);
                if (parameters.TryGetValue("nameoffile", out nameOfFile))
                {
                    string analyzerType, startDate, finishDate;
                    parameters.TryGetValue("analyzer", out analyzerType);
                    parameters.TryGetValue("startdate", out startDate);
                    parameters.TryGetValue("finishdate", out finishDate);

                    var logReader = new LogFileReader();
                    var records   = logReader.GiveAllRecordsInFile(nameOfFile);

                    var dateFilter = new DateFilter
                    {
                        Records = records
                    };
                    records = dateFilter.Filtrate(startDate, finishDate);

                    var analyzerByType = new FileAnalyzer
                    {
                        Records = records
                    };

                    Console.WriteLine(analyzerByType.AnalyzeByType(analyzerType));
                }
                else
                {
                    Console.WriteLine("Входные параметры не соответствуют шаблону.");
                }
            }
            else
            {
                Console.WriteLine(parametersValidator.ValidationInformation);
            }
            Console.ReadKey();
        }
Пример #23
0
        public IDictionary <string, string> Parse(string commandLine)
        {
            ParametersValidator.IsNotNull(commandLine, () => commandLine);
            Logger.DebugFormat("Parsing command line {0}", commandLine);
            var result = new Dictionary <string, string>();
            var re     = new Regex(@"(?<switch> -{1,2}\S*)(?:[=:]?|\s+)(?<value> [^-\s].*?)?(?=\s+[-\/]|$)",
                                   RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var matches = re.Matches(commandLine);

            foreach (Match m in matches)
            {
                var sw = m.Groups["switch"].Value;
                sw = sw.TrimStart(' ', '-');
                var val = m.Groups["value"].Value;
                val        = val.Trim();
                result[sw] = val;
            }
            Logger.DebugFormat("Parsed command line {0}, {1} matches", commandLine, result.Count);
            return(result);
        }
Пример #24
0
        public override RuleAction Preprocess()
        {
            RuleAction delegateRuleAction;

            this.EnsureCompatibilityLevel();
            try
            {
                SqlRuleAction.CompiledItem compiledItem = (SqlRuleAction.CompiledItem)SqlRuleAction.compiledCache.Get(this.SqlExpression, null);
                if (compiledItem == null)
                {
                    SqlActionParserOutput sqlActionParserOutput = SqlActionParser.Parse(this.SqlExpression);
                    Action <BrokeredMessage, IDictionary <string, object> > action = sqlActionParserOutput.ExpressionTree.Compile();
                    compiledItem = new SqlRuleAction.CompiledItem(action, sqlActionParserOutput.RequiredParameters);
                    SqlRuleAction.CompiledItem compiledItem1 = (SqlRuleAction.CompiledItem)SqlRuleAction.compiledCache.AddOrGetExisting(this.SqlExpression, compiledItem, SqlRuleAction.defaultCachePolicy, null);
                    if (compiledItem1 != null)
                    {
                        compiledItem = compiledItem1;
                    }
                }
                ParametersValidator.Validate(false, compiledItem.RequiredParameters, this.Parameters);
                delegateRuleAction = new DelegateRuleAction(compiledItem.Delegate, this.Parameters);
            }
            catch (RuleActionException ruleActionException)
            {
                throw;
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                if (!Fx.IsFatal(exception))
                {
                    throw new RuleActionException(exception.Message, exception);
                }
                throw;
            }
            return(delegateRuleAction);
        }
Пример #25
0
        public void Run()
        {
            try
            {
                ParametersValidator validator = new ParametersValidator(_args[0]);
                ApplicationMode     mode      = (ApplicationMode)_args.Length;

                switch (mode)
                {
                case ApplicationMode.CountString:
                    if (validator.IsExistFile &&
                        !validator.IsStringEmpty(_args[1]))
                    {
                        ExecuteCountedMode();
                    }
                    break;

                case ApplicationMode.ReplaceString:
                    if (validator.IsExistFile &&
                        !validator.IsStringEmpty(_args[1]) &&
                        !validator.IsStringEmpty(_args[2]))
                    {
                        ExecuteReplacedMode();
                    }
                    break;

                default:
                    //todo instruction
                    break;
                }
            }
            catch (IOException)                   // todo
            {
                Console.WriteLine("Instruction"); // todo
            }
        }
        public void IsNotNullOrEmptyPassTest()
        {
            const string st = "Test String";

            ParametersValidator.IsNotNullOrEmpty(st, () => st);
        }
        public void OneParamIsEmptyIEnumerableTest()
        {
            var array = new object[] { };

            ParametersValidator.IsNotNullOrEmpty(() => array);
        }
 public void OneParamIsNullIEnumerableTest()
 {
     object[] array = null;
     ParametersValidator.IsNotNullOrEmpty(() => array);
 }
        public void OneParamIsNotNullThrowTest()
        {
            object obj = null;

            ParametersValidator.IsNotNull(() => obj);
        }
        public void OneParamIsNotNullOrWhiteSpacePassTest()
        {
            const string st = "Test String";

            ParametersValidator.IsNotNullOrWhiteSpace(() => st);
        }
        public void OneParamIsNotNullOrWhiteSpaceWithNullTest()
        {
            string st = null;

            ParametersValidator.IsNotNullOrWhiteSpace(() => st);
        }
        public void OneParamIsNotNullOrWhiteSpaceWithEmptyTest()
        {
            var st = String.Empty;

            ParametersValidator.IsNotNullOrWhiteSpace(() => st);
        }
Пример #33
0
        static void Main(string[] args)
        {
            var parametersValidator = new ParametersValidator();
            var parametersAreValid  = parametersValidator.Validate(args);

            if (parametersAreValid)
            {
                string nameOfFile;
                string numberOfLines;
                string numberOfUniqueIp;
                var    parametersDictionary = CommandLineParser.Parse(args);
                if (parametersDictionary.TryGetValue("nameoffile", out nameOfFile) && parametersDictionary.TryGetValue("numberoflines", out numberOfLines) && parametersDictionary.TryGetValue("numberofuniqueip", out numberOfUniqueIp))
                {
                    var      uniqueIpCount    = Convert.ToInt32(numberOfUniqueIp);
                    var      linesLength      = Convert.ToInt32(numberOfLines);
                    var      configFileReader = new Settings.ConfigFileReader(@"D:\Univercity\Univercity\3курс-лабы\config.yaml");
                    string[] methods          =
                    {
                        "POST",   "LINK", "DELETE", "PUT", "PATCH", "GET", "OPTIONS", "HEAD", "TRACE",
                        "UNLINK", "CONNECT"
                    };
                    string[]  extensions                = { "txt", "pdf", "doc", "exe", "jmp", "cpp", "obj", "iso" };
                    string[]  protocols                 = { "http", "https" };
                    string[]  serverResponseCodes       = { "200", "401", "204", "404", "501" };
                    const int minIntervalInMilliseconds = 100;
                    const int maxIntervalInMilliseconds = 100000;
                    const int minNumberOfFolders        = 3;
                    const int maxNumberOfFolders        = 7;
                    const int minNumberOfCharacters     = 3;
                    const int maxNumberOfCharacters     = 7;
                    const int minSizeOfResponse         = 100;
                    const int maxSizeOfResponse         = 10000;

                    var recordFormat = new RecordFormat
                    {
                        IpIsPresent                 = true,
                        QueryTimeIsPresent          = true,
                        QueryMethodIsPresent        = true,
                        FileNameIsPresent           = true,
                        ExtensionIsPresent          = true,
                        ProtocolIsPresent           = true,
                        ServerResponseCodeIsPresent = true,
                        SizeOfTheResponseIsPresent  = true
                    };
                    var generator = new Generator
                    {
                        Extensions                = extensions,
                        Protocols                 = protocols,
                        Methods                   = methods,
                        Settings                  = configFileReader.Settings,
                        ServerResponseCodes       = serverResponseCodes,
                        MinIntervalInMilliseconds = minIntervalInMilliseconds,
                        MaxIntervalInMilliseconds = maxIntervalInMilliseconds,
                        MinNumberOfCharacters     = minNumberOfCharacters,
                        MaxNumberOfCharacters     = maxNumberOfCharacters,
                        MinNumberOfFolders        = minNumberOfFolders,
                        MaxNumberOfFolders        = maxNumberOfFolders,
                        MinSizeOfResponse         = minSizeOfResponse,
                        MaxSizeOfResponse         = maxSizeOfResponse,
                        NumberOfUniqueIp          = uniqueIpCount
                    };
                    var allRecords = generator.GenerateRecords(linesLength);
                    var rows       = ApacheLogFormat.RecordsToString(allRecords, recordFormat);
                    SaveToFile.SaveRowsToFile(nameOfFile, rows);
                    Console.WriteLine("Save succesed!");
                }
                else
                {
                    Console.WriteLine("Входные параметры не соответствуют шаблону.");
                }
            }
            else
            {
                Console.WriteLine(parametersValidator.ValidationInformation);
            }
            Console.ReadKey();
        }