예제 #1
0
        private TypeDefinition _CreateTypeDefinition(ClassDeclarationSyntax inputClassDeclaration, CompilationUnitSyntax rootNode)
        {
            var _typeDefinition = TypeDefinition.Create(
                inputClassDeclaration.Identifier.ToString(),
                ((NamespaceDeclarationSyntax)inputClassDeclaration.Parent).Name.ToString());

            _typeDefinition = _typeDefinition
                              .AddUsings(rootNode.Usings);

            var _typeValidationMethod = inputClassDeclaration.Members
                                        .Where(_member => _member.Kind() == SyntaxKind.MethodDeclaration)
                                        .Cast <MethodDeclarationSyntax>()
                                        .Where(_method => _method.Modifiers.Any(SyntaxKind.StaticKeyword))
                                        .Where(_method => _method.ParameterList.Parameters.Count == 1)
                                        .SingleOrDefault(_method => _method.Identifier.Text == NameHelper.TextToPublicMethodIdentifier("IsValid").Text);

            if (_typeValidationMethod != null)
            {
                var _valueParameter = _typeValidationMethod.ParameterList.Parameters[_typeValidationMethod.ParameterList.Parameters.Count - 1];

                Must.Assert(_valueParameter.Type.ToString() == _typeDefinition.Name);

                _typeDefinition = _typeDefinition
                                  .WithValidateMethodName(SyntaxFactory.IdentifierName(_typeValidationMethod.Identifier));
            }

            _typeDefinition = _typeDefinition.AddProperties(_CreatePropertyDefinitions(inputClassDeclaration));
            return(_typeDefinition);
        }
예제 #2
0
 public Result <Game> Deploy(CountryId country, Army army)
 => Must.BeInPhase(GamePhase.Deploy)
 | (g => g.Must.BeActivePlayer(army.Owner))
 | (g => g.Must.Exist(country))
 | (g => g.Must.BeOwnedBy(country, army.Owner))
 | (g => g.Must.NotExceedArmyBuffer(army))
 | (g => g.ApplyEvent(new Deployed(country, army)));
        public PerformanceCounterDefinition(string path)
        {
            Must.NotBeNull(() => path);

            if (!path.StartsWith("\\"))
            {
                throw new ArgumentException("'path' must begin with a '\\'");
            }

            var keyTokens = path.Split(KeySeparator);

            if (keyTokens.Length < 3)
            {
                throw new ArgumentException("'path' must contain a Category and Counter", path);
            }

            CategoryName = keyTokens[1];
            CounterName  = keyTokens[2];

            if (CategoryName.Contains("(") && CategoryName.Contains(")"))
            {
                var categoryNameTokens = CategoryName.Split('(', ')');
                CategoryName = categoryNameTokens[0];
                InstanceName = categoryNameTokens[1];
            }
        }
예제 #4
0
 public Result <Game> Reinforce(CountryId from, CountryId to, Army army)
 => Must.BeInPhase(GamePhase.Reinforce)
 | (g => g.Must.Exist(from))
 | (g => g.Must.Exist(to))
 | (g => g.Must.BeOwnedBy(from, army.Owner))
 | (g => g.Must.BeOwnedBy(to, army.Owner))
 | (g => g.Must.BeReachable(to, by: from))
 | (g => g.ApplyEvent(new Reinforced(from, to, army)));
예제 #5
0
 private ValueAttribute(string converter, Must condition, object argument, bool hasValue)
 {
     Converter = converter;
     Condition = condition;
     Argument  = argument;
     HasValue  = hasValue;
     ValidatesOnTargetUpdated = false;
 }
예제 #6
0
 /* {
  *   "id": 1,
  *   "name": "Leanne Graham",
  *   "username": "******",
  *   "email": "*****@*****.**",
  *   "address": {
  *     "street": "Kulas Light",
  *     "suite": "Apt. 556",
  *     "city": "Gwenborough",
  *     "zipcode": "92998-3874",
  *     "geo": {
  *       "lat": "-37.3159",
  *       "lng": "81.1496"
  *     }
  *   },
  *   "phone": "1-770-736-8031 x56442",
  *   "website": "hildegard.org",
  *   "company": {
  *     "name": "Romaguera-Crona",
  *     "catchPhrase": "Multi-layered client-server neural-net",
  *     "bs": "harness real-time e-markets"
  *   }
  * }
  */
 public UserValidator()
 {
     When(Any)
     .Then(Field("id", Is.Required() & Must.Be.Integer() & Must.Be.GreaterOrEqualTo(1))
           & Field("name", Is.Required() & Must.Be.String() & Must.Have.MinLength(5))
           & Field("username", Is.Required())
           & Field("email", Is.Required() & Must.Match("\\w+\\@\\w+\\.\\w+"))
           );
 }
예제 #7
0
    public static Result <TAggregate> HaveVersion <TAggregate>(this Must <TAggregate> must, int expected)
        where TAggregate : AggregateRoot <TAggregate>, new()
    {
        Guard.NotNull(must, nameof(must));
        Guard.NotNegative(expected, nameof(expected));
        int actual = ((dynamic)must.Subject).Version;

        return(must.Be(actual == expected, ConcurrencyIssue.VersionMismatch(expected, actual)));
    }
        private void CanOnlyContainAlphanumericOrUnderscore(string querySource)
        {
            Must.NotBeNull(() => querySource);

            if (!querySource.All(l => char.IsLetterOrDigit(l) || l == '_'))
            {
                throw new ArgumentException("The query source specified for a WMI query can only contain letters, digits or underscore ('_')", querySource);
            }
        }
예제 #9
0
        public async Task Exec_FuncTaskCalls()
        {
            var must = new Must(0, source.Token);
            var res  = await must.Exec(async() =>
            {
                await Task.Delay(1);
                return(Value);
            }, 10);

            Assert.AreEqual(res, Value);
        }
예제 #10
0
 /// <summary>
 ///   Constructs a ComponentModel
 /// </summary>
 public ComponentModel(ComponentName name, ICollection <Type> services, Type implementation, Arguments extendedProperties)
 {
     componentName           = Must.NotBeNull(name, "name");
     Implementation          = Must.NotBeNull(implementation, "implementation");
     this.extendedProperties = extendedProperties;
     services = Must.NotBeEmpty(services, "services");
     foreach (var type in services)
     {
         AddService(type);
     }
 }
예제 #11
0
        private static string Sanitise(string formatted)
        {
            Must.NotBeNull(() => formatted);

            var charArray = formatted.ToCharArray();

            charArray = Array.FindAll(charArray, c => char.IsLetterOrDigit(c) ||
                                      c == '-' ||
                                      c == '_' ||
                                      c == '.');
            return(new string(charArray));
        }
예제 #12
0
        public async Task <Project> PatchProjectAsync(Project project, CancellationToken cancellationToken = default(CancellationToken))
        {
            var _modified = false;
            var _project  = project;

            foreach (var _documentId in project.DocumentIds)
            {
                var _document = _project.GetDocument(_documentId);

                if (_document.SupportsSyntaxTree)
                {
                    var _syntaxTree = await _document.GetSyntaxRootAsync(cancellationToken);

                    CompilationUnitSyntax _compilationUnit;
                    if (_syntaxTree?.Language == LanguageNames.CSharp && (_compilationUnit = _syntaxTree as CompilationUnitSyntax) != null)
                    {
                        var _typeDefinition = _TypeDefinitionGenerator.GenerateTypeDefinition(_compilationUnit);
                        if (_typeDefinition != null)
                        {
                            Must.Assert(!(Path.GetFileNameWithoutExtension(_document.Name) ?? string.Empty).EndsWith(_GeneratedImmutablerFileSufix, StringComparison.OrdinalIgnoreCase));

                            var _generatedImmutablerSyntax       = _SyntaxBuilder.BuildSyntaxFromTypeDefinition(_typeDefinition);
                            var _generatedImmutablerDocumentName = Path.GetFileNameWithoutExtension(_document.Name) + _GeneratedImmutablerFileSufix + Path.GetExtension(_document.Name);
                            var _generatedImmutablerDocument     = _project.Documents.SingleOrDefault(_d => _d.Name.Equals(_generatedImmutablerDocumentName, StringComparison.OrdinalIgnoreCase));
                            Must.Assert(_generatedImmutablerDocument == null || _generatedImmutablerDocument.Name.Equals(_generatedImmutablerDocumentName, StringComparison.Ordinal));
                            if (_generatedImmutablerDocument == null)
                            {
                                _generatedImmutablerDocument = _project.AddDocument(
                                    _generatedImmutablerDocumentName,
                                    _generatedImmutablerSyntax,
                                    folders: _document.Folders);
                                _project  = _generatedImmutablerDocument.Project;
                                _modified = true;
                            }
                            else
                            {
                                var _existingGeneratedImmutablerSyntax = await _generatedImmutablerDocument.GetSyntaxRootAsync(cancellationToken);

                                if (!string.Equals(_generatedImmutablerSyntax.ToFullString(), _existingGeneratedImmutablerSyntax.ToFullString(), StringComparison.Ordinal))
                                {
                                    _generatedImmutablerDocument = _generatedImmutablerDocument.WithSyntaxRoot(_generatedImmutablerSyntax);
                                    _project  = _generatedImmutablerDocument.Project;
                                    _modified = true;
                                }
                            }
                        }
                    }
                }
            }

            return(_modified ? _project : null);
        }
 private ValueAttribute(string converter, Must condition, object argument, bool hasValue)
 {
     Converter = converter;
     Condition = condition;
     Argument  = argument;
     HasValue  = hasValue;
     ValidatesOnTargetUpdated = false;
     if (condition == Must.Fail)
     {
         OnActivation   = ValidationAction.ValidateField;
         OnDeactivation = ValidationAction.ValidateField;
     }
 }
        public FakeValidator()
        {
            //TOOD: This is not working. - One error is in the BasicJsonRule - When we select an item, if there is no items, we have a empty result.
            When(Field("gender", Is.Defined()) | Field("sex", Is.Defined()))
            .Then(Field("gender", Must.Be.In("male", "female")) | Field("sex", Must.Be.In("male", "female")));
            //When("gender", Is.Defined()).Then(Field("gender", Must.Be.In("male", "female")) | Field("sex", Must.Be.In("male", "female")));

            When("name", Is.Defined()).Then(It, Must.Have.LengthBetween(10, 50) & Must.Match("^[A-Za-z\\s]+$") | Have.ExactLength(5));
            When("age", Is.Defined()).Then(It, Must.Be.Integer() & Be.GreaterThan(0));
            When(Any).Then("fox", Is.Required());

            //When("missing", Is.Defined()).Then(It, Must.Be.Boolean());
        }
예제 #15
0
        public ViewConventions()
        {
            Must
            .HaveNamespaceStartsWith("Hexenstein.UI")
            .HaveNameEndWith("View");

            Should
            .BeAConcreteClass();

            BaseName = t => t.Name.Substring(0, t.Name.Length - 4);

            Variants
            .StartWithBaseName();
        }
예제 #16
0
        public ViewModelConventions()
        {
            Must
            .HaveNamespaceStartsWith("Hexenstein.UI")
            .HaveNameEndWith("ViewModel");

            Should
            .BeAConcreteClass()
            .Implement <INotifyPropertyChanged>();

            BaseName = t => t.Name.Substring(0, t.Name.Length - 9);

            Variants
            .StartWithBaseName();
        }
예제 #17
0
        public AttachmentConventions()
        {
            Must
            .HaveNamespaceStartsWith("Hexenstein.UI")
            .HaveNameEndWith("Attachment");

            Should
            .BeAConcreteClass()
            .Implement <IAttachment>();

            BaseName = t => t.Name.Substring(0, t.Name.Length - 10);

            Variants
            .StartWithBaseName();
        }
예제 #18
0
 public Result <Game> AutoAttack(
     CountryId attacker,
     CountryId defender,
     IGenerator rnd)
 => Must.BeInPhase(GamePhase.Attack)
 | (g => g.Must.Exist(attacker))
 | (g => g.Must.Exist(defender))
 | (g => g.Must.BeOwnedBy(attacker, ActivePlayer))
 | (g => g.Must.NotBeOwnedBy(defender, ActivePlayer))
 | (g => g.Must.BeReachable(defender, by: attacker))
 | (g => g.Must.HaveArmiesToAttack(attacker))
 | (g => g.Attack(attacker, defender, Dice
                  .AutoAttack(
                      Countries.ById(attacker).Army,
                      Countries.ById(defender).Army,
                      rnd)));
예제 #19
0
        /* {
         *   "albumId": 100,
         *   "id": 5000,
         *   "title": "error quasi sunt cupiditate voluptate ea odit beatae",
         *   "url": "http://placehold.it/600/6dd9cb",
         *   "thumbnailUrl": "http://placehold.it/150/6dd9cb"
         * }
         */
        public PhotoValidator()
        {
            When(Any)
            .Then(Field("id", Is.Required() & Must.Be.Integer() & Must.Be.GreaterOrEqualTo(1))
                  & Field("albumId", Is.Required() & Must.Be.Integer() & Must.Be.GreaterOrEqualTo(1))
                  & Field("title", Is.Required() & Has.MinLength(1))
                  & Field("url", Is.Required() & Must.Match("http://\\w+\\.\\w+/\\d+/[0-9A-Za-z]{3,6}"))
                  );

            When(Any)
            .Then("thumbnailUrl", ComparedTo("url", ctx =>
            {
                string value = (string)(JValue)ctx;
                return(Is.EqualTo(value.Replace("/600/", "/150/")));
            }));
        }
        public TestValidator()
        {
            When(Any).Then("x", Must.Have.MinLength(3));

            When("name", x => true, "is true").Then(It, Must.Match(x => true, "be true"));

            When("name", Is.Defined()).Then("test", Must.Have.MaxLength(200));
            When("surname", Is.Defined()).Then("test", Must.Have.MaxLength(25));

            When(Field("test", Has.MinLength(5))).Then(Field("other", Should.Be.Equal("0")));

            When(Field("A", Is.Defined()) | Field("B", Is.Defined()))
            .Then(
                Field("A", Must.Be.Equal("") | Must.Be.Equal(""))
                & Field("B", Must.Be.Equal("")));
        }
예제 #21
0
 public void Exec_ActionToken()
 {
     Assert.Throws <TaskCanceledException>(() =>
     {
         var must = new Must(10, source.Token);
         var t    = must.Exec(token => throw new Exception());
         Task.Run(() => source.Cancel());
         try
         {
             t.Wait();
         }
         catch (AggregateException e)
         {
             throw (TaskCanceledException)e.InnerException;
         }
     });
 }
        public WindowsManagementInstrumentationDefinition(string path)
        {
            Must.NotBeNull(() => path);

            var keyTokens = path.Split(KeySeparator);

            if (keyTokens.Length < 3)
            {
                throw new ArgumentException("'path' must contain a QuerySource and PropertyName", path);
            }

            QuerySource = keyTokens[1];

            CanOnlyContainAlphanumericOrUnderscore(QuerySource);

            PropertyName = keyTokens[2];
        }
        private static bool _ReadBoolFromConfiguration(string configurationKey, bool defaultValue)
        {
            var _value = ConfigurationManager.AppSettings[configurationKey];

            if (string.Equals(_value, "true", StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            if (string.Equals(_value, "false", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            Must.Assert(string.IsNullOrEmpty(_value), $"Value of configuration setting {configurationKey} is not a valid boolean. Must be empty, 'true' or 'false'.");

            return(defaultValue);
        }
예제 #24
0
        public async Task ExecAttempts_ActionOnError()
        {
            var log        = new List <string>();
            int sleepCount = 2;
            var must       = new Must(0, source.Token);

            must.OnError += e => { log.Add(e.Message); };

            await must.Exec(token =>
            {
                if (step++ < sleepCount)
                {
                    throw new Exception(step.ToString());
                }
            }, 1);

            for (int i = 0; i < sleepCount; i++)
            {
                Assert.AreEqual(log[i], (i + 1).ToString());
            }
        }
예제 #25
0
 public void ExecAttempts_FuncToken()
 {
     Assert.Throws <TaskCanceledException>(() =>
     {
         var must = new Must(0, source.Token);
         var t    = must.ExecAttempts(token =>
         {
             throw new Exception();
             return(Value);
         }, int.MaxValue);
         Task.Run(() => source.Cancel());
         try
         {
             t.Wait();
         }
         catch (AggregateException e)
         {
             throw (TaskCanceledException)e.InnerException;
         }
     });
 }
예제 #26
0
        public CompilationUnitSyntax BuildSyntaxFromTypeDefinition(TypeDefinition typeDefinition)
        {
            Must
            .Assert(typeDefinition != null);

            var _outputClass = _CreateOutputClass(typeDefinition);

            var _outputDeclaration = SyntaxFactory
                                     .CompilationUnit()
                                     .AddUsings(typeDefinition.Usings.ToArray())
                                     .WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(SyntaxFactory
                                                                                                        .NamespaceDeclaration(SyntaxFactory.IdentifierName(typeDefinition.Namespace))
                                                                                                        .AddMembers(_outputClass)));

            _outputDeclaration = _outputDeclaration
                                 .RemoveNodes(_outputDeclaration.DescendantNodes().OfType <EmptyStatementSyntax>(), SyntaxRemoveOptions.KeepUnbalancedDirectives)
                                 .NormalizeWhitespace()
                                 .WithTrailingTrivia(_outputDeclaration.GetTrailingTrivia().Append(SyntaxFactory.EndOfLine(string.Empty)));

            return(_outputDeclaration);
        }
예제 #27
0
        public async Task ExecAttempts_Action()
        {
            var watch      = new Stopwatch();
            int sleep      = 60;
            int sleepCount = 5;
            int value      = 1;
            var must       = new Must(sleep);
            await must.ExecAttempts(token =>
            {
                if (!watch.IsRunning)
                {
                    watch.Start();
                }
                if (step++ < sleepCount)
                {
                    throw new Exception();
                }
                watch.Stop();
            }, 100, sleep);

            Assert.IsTrue(watch.ElapsedMilliseconds >= sleep * sleepCount);
        }
예제 #28
0
        public async Task Exec_Action()
        {
            var a          = new MustDo.Must(100);
            var watch      = new Stopwatch();
            int sleep      = 60;
            int sleepCount = 5;
            var must       = new Must(sleep);
            await must.Exec(token =>
            {
                if (!watch.IsRunning)
                {
                    watch.Start();
                }
                if (step++ < sleepCount)
                {
                    throw new Exception();
                }
                watch.Stop();
            });

            Console.WriteLine();
            Assert.IsTrue(watch.ElapsedMilliseconds >= sleep * sleepCount);
        }
예제 #29
0
        public async Task ExecAttempts_Func()
        {
            var watch      = new Stopwatch();
            int sleep      = 60;
            int sleepCount = 5;
            var must       = new Must(sleep);
            int res        = await must.ExecAttempts(token =>
            {
                if (!watch.IsRunning)
                {
                    watch.Start();
                }
                if (step++ < sleepCount)
                {
                    throw new Exception();
                }
                watch.Stop();
                return(Value);
            }, 100, sleep);

            Assert.AreEqual(Value, res);
            Assert.IsTrue(watch.ElapsedMilliseconds >= sleep * sleepCount);
        }
예제 #30
0
 public Task ExecAttempts_ActionThrowsAttemptsOverException()
 {
     Assert.Throws <AttemptsOverException>(() =>
     {
         int sleep      = 60;
         int sleepCount = 5;
         var must       = new Must(sleep);
         try
         {
             must.ExecAttempts(token =>
             {
                 if (step++ < sleepCount)
                 {
                     throw new Exception();
                 }
             }, sleepCount - 1, sleep).Wait();
         }
         catch (AggregateException e)
         {
             throw (AttemptsOverException)e.InnerException;
         }
     });
     return(Task.CompletedTask);
 }