Ejemplo n.º 1
0
        public void Generate2FieldsFromText()
        {
            FieldCollector collector = new FieldCollector();
            String         path      = "C:\\Users\\nic_l\\Desktop\\Test_Cases_Text_Files\\Generate2FieldFromText.txt";

            Field field1 = new Field(4, 4);

            field1.InputGrid = new String[4] {
                "*...", "....", ".*..", "...."
            };

            Field field2 = new Field(3, 5);

            field2.InputGrid = new String[3] {
                "**...", ".....", ".*..."
            };

            List <Field> expected = new List <Field>();

            expected.Add(field1);
            expected.Add(field2);
            collector.GetFields(path);

            CollectionAssert.AreEqual(expected[1].InputGrid, collector.fields[1].InputGrid);
        }
Ejemplo n.º 2
0
        private IReadOnlyList <IFieldDescriptor> CreateFields(
            IComplexOutputType type,
            IEnumerable <ISelectionNode> selections,
            Func <string, bool> addField,
            Path path)
        {
            var fields = new Dictionary <string, FieldSelection>();

            foreach (FieldNode selection in selections.OfType <FieldNode>())
            {
                NameString responseName = selection.Alias == null
                    ? selection.Name.Value
                    : selection.Alias.Value;

                if (addField(responseName))
                {
                    FieldCollector.ResolveFieldSelection(
                        type,
                        selection,
                        path,
                        fields);
                }
            }

            return(fields.Values.Select(t =>
            {
                string responseName = (t.Selection.Alias ?? t.Selection.Name).Value;
                return new FieldDescriptor(
                    t.Field,
                    t.Selection,
                    t.Field.Type,
                    path.Append(responseName));
            }).ToList());
        }
Ejemplo n.º 3
0
        public void readEntireTextBLockUntil0_0()
        {
            FieldCollector collector = new FieldCollector();
            String         BLANK     = System.Environment.NewLine;
            String         path      = "C:\\Users\\nic_l\\Desktop\\Test_Cases_Text_Files\\ReadEntireTextBlockUntil0_0.txt";
            String         expected  = "4 4" + BLANK + "...." + BLANK + "...." + BLANK + "...." + BLANK + "....";

            collector.GetFields(path);
            Assert.AreEqual(expected, collector.infoBlock);
        }
Ejemplo n.º 4
0
        public void Generate1FieldFromText()
        {
            FieldCollector collector = new FieldCollector();
            String         path      = "C:\\Users\\nic_l\\Desktop\\Test_Cases_Text_Files\\Generate1FieldFromText.txt";
            Field          expected  = new Field(4, 4);

            expected.InputGrid = new String[4] {
                "*...", "....", ".*..", "...."
            };
            collector.GetFields(path);
            CollectionAssert.AreEqual(expected.InputGrid, collector.fields[0].InputGrid);
        }
Ejemplo n.º 5
0
        public ModelGeneratorContext(
            ISchema schema,
            IQueryDescriptor query,
            string clientName,
            string ns)
        {
            Schema     = schema ?? throw new ArgumentNullException(nameof(schema));
            Query      = query ?? throw new ArgumentNullException(nameof(query));
            ClientName = clientName ?? throw new ArgumentNullException(nameof(clientName));
            Namespace  = ns ?? throw new ArgumentNullException(nameof(ns));

            _collector = new FieldCollector(
                schema,
                new FragmentCollection(schema, query.OriginalDocument));
        }
Ejemplo n.º 6
0
        public void Generate1OutputFieldFromText()
        {
            FieldCollector collector = new FieldCollector();
            String         path      = "C:\\Users\\nic_l\\Desktop\\Test_Cases_Text_Files\\Generate2FieldFromText.txt";

            Field expected = new Field(4, 4);

            expected.OutputGrid = new String[4] {
                "*100", "2210", "1*10", "1110"
            };

            collector.GenerateOutput(path);

            CollectionAssert.AreEqual(expected.OutputGrid, collector.fields[0].OutputGrid);
        }
Ejemplo n.º 7
0
        public void ConfirmGeneratedOutputFromFile()
        {
            FieldCollector collector  = new FieldCollector();
            String         BLANK      = System.Environment.NewLine;
            String         InputPath  = "C:\\Users\\nic_l\\Desktop\\Test_Cases_Text_Files\\Generate2FieldFromText.txt";
            String         OutputPath = "C:\\Users\\nic_l\\Desktop\\Test_Cases_Text_Files\\Output.txt";

            String expected = "Field #1:" + BLANK + "*100" + BLANK + "2210" + BLANK + "1*10" + BLANK + "1110" + BLANK + BLANK +
                              "Field #2:" + BLANK + "**100" + BLANK + "33200" + BLANK + "1*100" + BLANK;

            collector.GenerateOutput(InputPath);

            String result;

            using (StreamReader reader = new StreamReader(OutputPath))
            {
                result = reader.ReadToEnd();
            }
            Assert.AreEqual(expected, result);
        }
Ejemplo n.º 8
0
        public CodeModelGenerator(
            ISchema schema,
            IQueryDescriptor query,
            ISet <string> usedNames,
            string clientName,
            string ns)
        {
            _schema     = schema ?? throw new ArgumentNullException(nameof(schema));
            _query      = query ?? throw new ArgumentNullException(nameof(query));
            _usedNames  = usedNames ?? throw new ArgumentNullException(nameof(usedNames));
            _clientName = clientName ?? throw new ArgumentNullException(nameof(clientName));
            _namespace  = ns ?? throw new ArgumentNullException(nameof(ns));

            _document       = query.OriginalDocument;
            _fieldCollector = new FieldCollector(
                new FragmentCollection(schema, query.OriginalDocument));

            Descriptors = Array.Empty <ICodeDescriptor>();
            FieldTypes  = new Dictionary <FieldNode, string>();
        }
Ejemplo n.º 9
0
        public async Task <OperationResult> ExecuteRequestAsync(
            string queryText,
            IDictionary <string, object> variableValues,
            string operationName    = null,
            CancellationToken token = default)
        {
            Check.IsNotNullOrWhiteSpace(queryText, nameof(queryText));

            var document = new Parser().Parse(new Lexer().Tokenize(queryText));

            var operations = document.Definitions
                             .OfType <OperationDefinition>();

            if (operationName != null)
            {
                operations = operations
                             .Where(x => x.Name == operationName);
            }

            var operationCount = operations
                                 .Take(2)
                                 .Count();

            if (operationCount == 0)
            {
                throw new InvalidOperationException("No operations defined");
            }
            else if (operationCount > 1)
            {
                throw new InvalidOperationException("Multiple operations defined");
            }

            var operation = operations
                            .First();

            var fragments = document.Definitions
                            .OfType <FragmentDefinition>()
                            .ToList();

            if (operation.OperationType != OperationType.Query && mutationFactory == null)
            {
                throw new InvalidOperationException("No mutation defined");
            }

            var asyncBatch = new AsyncBatch(operation.OperationType == OperationType.Query);
            var target     = operation.OperationType == OperationType.Query
                ? (GraphQLObject)queryFactory(asyncBatch)
                : mutationFactory(asyncBatch);

            var errors = new List <GraphQLError>();
            var variableDefinitions = (operation.VariableDefinitions ?? Enumerable.Empty <VariableDefinition>())
                                      .ToDictionary(x => x.Name, x => x);
            var variableTypes = (operation.VariableDefinitions ?? Enumerable.Empty <VariableDefinition>())
                                .ToDictionary(x => x.Name, x => x.Type);
            var variables = new VariableValues((operation.VariableDefinitions ?? Enumerable.Empty <VariableDefinition>())
                                               .ToDictionary(x => x.Name, x => variableValues.TryGetValue(x.Name, out var value) ? value : x.DefaultValue));
            var fields = await FieldCollector.CollectFields(variables, variableTypes, target, operation.SelectionSet, fragments, errors, logger, exceptionFilter, token);

            errors.AddRange(variables.UnusedVariables
                            .Select(x => new GraphQLError($"Variable '${x}' is not used. ", new[] { variableDefinitions[x].Location }))
                            .ToList()
                            );

            if (errors.Any())
            {
                return(new OperationResult(null, errors));
            }

            try
            {
                await asyncBatch.ExecuteAsync(token);
            }
            catch (GraphQLException ex)
            {
                return(new OperationResult(null, ex.Errors));
            }

            var result = Apply(null, fields, errors);

            return(new OperationResult(result, errors));
        }
Ejemplo n.º 10
0
 public TableMappingConfiguration()
 {
     TableMappingColumnFactory = new BasicTableMappingColumnFactory();
     PropertyCollector         = new StandardWrappedPublicPropertyCollector();
     FieldCollector            = new NullFieldCollector();
 }
Ejemplo n.º 11
0
        private List <PropertyTypeNode> ExtractPropertyNodesFrom(
            SemanticModel model, SemanticInformationCollector collector)
        {
            if (model == null)
            {
                throw new Exception("Invalid semantic model for property node introspection (null).");
            }

            var nodes = new List <PropertyTypeNode>();

            var typePerFullTypename = new Dictionary <string, PropertyTypeNode>();

            // Expect a top -> bottom tree traversal, so it means that the
            // list contains types declared in order.

            foreach (var type in collector.ContainerTypes)
            {
                var tag = PropertyTypeNode.TypeTag.Class;
                if (type is StructDeclarationSyntax)
                {
                    tag = PropertyTypeNode.TypeTag.Struct;
                }

                var symbol = model.GetDeclaredSymbol(type);

                var typePath = new ContainerTypeTreePath
                {
                    Namespace = NamespaceForType(type)
                };

                var fullTypeNamePath = symbol.ToString().Replace(typePath.Namespace, "").Trim('.').Split('.');
                fullTypeNamePath = fullTypeNamePath.Take(fullTypeNamePath.Length - 1).ToArray();
                foreach (var pathPart in fullTypeNamePath)
                {
                    typePath.TypePath.Push(pathPart);
                }

                var node = new PropertyTypeNode
                {
                    Tag                      = tag,
                    TypePath                 = typePath,
                    TypeName                 = symbol.Name,
                    IsAbstractClass          = symbol.IsAbstract,
                    OverrideDefaultBaseClass = symbol.AllInterfaces.Any(i => i.Name == typeof(IPropertyContainer).Name)
                        ? string.Empty : symbol.BaseType.Name
                };

                var fieldCollector = new FieldCollector(model);

                fieldCollector.Visit(type);

                foreach (var field in fieldCollector.Properties)
                {
                    var genericProperty = new RoslynProperty(field.Symbol);
                    if (!genericProperty.IsValid)
                    {
                        continue;
                    }

                    // Parse

                    var property = new PropertyTypeNode()
                    {
                        PropertyName     = PropertyNameFromFieldName(field.Symbol.Name),
                        Tag              = genericProperty.TypeTag,
                        TypeName         = genericProperty.TypeID,
                        Of               = genericProperty.ListOf,
                        IsReadonly       = genericProperty.IsReadonly,
                        IsPublicProperty = field.SyntaxNode.Modifiers.Any(SyntaxKind.PublicKeyword)
                    };

                    // Extract info about backing fields

                    var initializer = field.SyntaxNode.Declaration.Variables.First().Initializer;
                    if (initializer?.Value is ExpressionSyntax)
                    {
/*
 *                      // @TODO
 *                      var initializerExpression = initializer.Value;
 *
 *                      // @TODO
 *                      var symbolNames = model.LookupSymbols(initializerExpression.SpanStart).Select(s => s.Name).ToList();
 */

                        // property.DefaultValue =
                        property.PropertyBackingAccessor = string.Empty;
                    }

                    if (!string.IsNullOrEmpty(property.PropertyName))
                    {
                        node.Properties.Add(property);
                    }
                }

                var containingSymbolFullName = symbol.ContainingSymbol.ToDisplayString();
                // symbol.ContainingSymbol.Name
                if (typePerFullTypename.ContainsKey(containingSymbolFullName))
                {
                    // This is a nested node

                    var parent = typePerFullTypename[containingSymbolFullName];

                    node.TypePath = new ContainerTypeTreePath(parent.TypePath);

                    node.TypePath.TypePath.Push(parent.TypeName);

                    parent.NestedContainers.Add(node);
                }
                else
                {
                    // This is a new node

                    typePerFullTypename[node.FullTypeName] = node;
                    nodes.Add(node);
                }
            }

            return(nodes);
        }