/// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the value to convert into an instance of <see cref="OperationDefinition" />.</param>
 /// <returns>
 /// an instance of <see cref="OperationDefinition" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public static object ConvertFrom(dynamic sourceValue)
 {
     if (null == sourceValue)
     {
         return(null);
     }
     try
     {
         OperationDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());
     }
     catch
     {
         // Unable to use JSON pattern
     }
     try
     {
         return(new OperationDefinition
         {
             Name = sourceValue.Name,
             Display = OperationDefinitionDisplayTypeConverter.ConvertFrom(sourceValue.Display),
         });
     }
     catch
     {
     }
     return(null);
 }
Beispiel #2
0
        protected override Expression VisitConstant(ConstantExpression node)
        {
            if (syntax.Root == null)
            {
                var query       = node.Value as IQuery;
                var mutation    = node.Value as IMutation;
                var queryEntity = node.Value as IQueryableValue;

                rootExpression = node;

                if (query != null)
                {
                    root = syntax.AddRoot(OperationType.Query, null);
                    return(RootDataParameter.AddIndexer("data"));
                }
                else if (mutation != null)
                {
                    root = syntax.AddRoot(OperationType.Mutation, null);
                    return(RootDataParameter.AddIndexer("data"));
                }
                else if (queryEntity != null)
                {
                    return(Visit(queryEntity.Expression));
                }
            }

            return(node);
        }
Beispiel #3
0
        private string PrintOperationDefinition(OperationDefinition definition)
        {
            var name         = PrintName(definition.Name);
            var directives   = Join(definition.Directives?.Select(PrintDirective) ?? Array.Empty <string>(), " ");
            var selectionSet = PrintSelectionSet(definition.SelectionSet);

            var variableDefinitions = Wrap(
                "(",
                Join(definition.VariableDefinitions?.Select(PrintVariableDefinition) ?? Array.Empty <string>(), ", "), ")");

            var operation = definition.Operation
                            .ToString()
                            .ToLower();

            return(string.IsNullOrWhiteSpace(name) &&
                   string.IsNullOrWhiteSpace(name) &&
                   string.IsNullOrWhiteSpace(name) &&
                   definition.Operation == OperationType.Query
                ? selectionSet
                : Join(
                       new[]
            {
                operation,
                Join(new[] { name, variableDefinitions }),
                directives,
                selectionSet
            },
                       " "));
        }
Beispiel #4
0
        private static async Task <ExecutionResult> ExecuteSubscriptionEventAsync(
            IExecutorContext context,
            OperationDefinition subscription,
            IReadOnlyDictionary <string, object?> coercedVariableValues,
            object evnt,
            Func <Exception, ExecutionError> formatError)
        {
            var subscriptionType = context.Schema.Subscription;
            var selectionSet     = subscription.SelectionSet;
            var path             = new NodePath();
            var data             = await SelectionSets.ExecuteSelectionSetAsync(
                context,
                selectionSet,
                subscriptionType,
                evnt,
                path).ConfigureAwait(false);

            var result = new ExecutionResult
            {
                Errors = context.FieldErrors.Select(formatError).ToList(),
                Data   = data?.ToDictionary(kv => kv.Key, kv => kv.Value)
            };

            return(result);
        }
Beispiel #5
0
 protected override void EnterOperationDefinition(PrinterContext context, OperationDefinition operationDefinition)
 {
     if (!operationDefinition.IsShort)
     {
         context.Append(operationDefinition.Operation.ToString().ToLowerInvariant());
     }
 }
Beispiel #6
0
 internal static void Operation(this ILogger logger, OperationDefinition operation)
 {
     OperationAction(
         logger,
         operation.Operation.ToString().ToLowerInvariant(),
         operation.Name, null);
 }
        internal static OperationDefinition AddNarrative(OperationDefinition opDef)
        {
            // create display text for Organisation Resource
            string textString = string.Empty;

            try
            {
                XNamespace ns = "http://www.w3.org/1999/xhtml";

                var summary = new XElement(ns + "div",
                                           new XElement(ns + "h2", opDef.Name),
                                           new XElement(ns + "table",
                                                        new XElement(ns + "tr",
                                                                     new XElement(ns + "td", "Id"),
                                                                     new XElement(ns + "td", opDef.Id)
                                                                     ),
                                                        new XElement(ns + "tr",
                                                                     new XElement(ns + "td", "Description"),
                                                                     new XElement(ns + "td", opDef.Description.ToString())
                                                                     ),
                                                        new XElement(ns + "tr",
                                                                     new XElement(ns + "td", "Kind"),
                                                                     new XElement(ns + "td", opDef.Kind.ToString())
                                                                     ),
                                                        new XElement(ns + "tr",
                                                                     new XElement(ns + "td", "Resource"),
                                                                     new XElement(ns + "td", opDef.Resource)
                                                                     ),
                                                        new XElement(ns + "table",
                                                                     new XElement(ns + "tr",
                                                                                  new XElement(ns + "th", "Use"),
                                                                                  new XElement(ns + "th", "Name"),
                                                                                  new XElement(ns + "th", "Cardinality"),
                                                                                  new XElement(ns + "th", "Type")
                                                                                  ),
                                                                     from param in opDef.Parameter
                                                                     select new XElement(ns + "tr",
                                                                                         new XElement(ns + "td", param.Use.ToString()),
                                                                                         new XElement(ns + "td", param.Name),
                                                                                         new XElement(ns + "td", param.Min.ToString() + ".." + param.Max.ToString()),
                                                                                         new XElement(ns + "td", param.Type.ToString())
                                                                                         )
                                                                     )
                                                        )
                                           );

                textString = summary.ToString();
            }
            catch
            { }

            opDef.Text = new Narrative
            {
                Status = Narrative.NarrativeStatus.Generated,
                Div    = textString
            };

            return(opDef);
        }
        private static void SerializeWithContext <T>(string elementName, T value, uint dtoVersion, bool addEnvelope, Action <XRoadMessage, string> f)
        {
            var message = Globals.ServiceManager20.CreateMessage();

            message.IsMultipartContainer = true;
            message.BinaryMode           = BinaryMode.Attachment;

            using (message)
                using (var stream = new MemoryStream())
                    using (var tw = new StreamWriter(stream, Encoding.UTF8))
                        using (var writer = XmlWriter.Create(tw))
                        {
                            if (addEnvelope)
                            {
                                writer.WriteStartElement("Envelope");
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.SOAP_ENC, NamespaceConstants.XMLNS, NamespaceConstants.SOAP_ENC);
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.XSI, NamespaceConstants.XMLNS, NamespaceConstants.XSI);
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.XSD, NamespaceConstants.XMLNS, NamespaceConstants.XSD);
                                writer.WriteAttributeString(PrefixConstants.XMLNS, PrefixConstants.TARGET, NamespaceConstants.XMLNS, Globals.ServiceManager20.ProducerNamespace);
                            }

                            writer.WriteStartElement(elementName);

                            var propType   = typeof(X <>).MakeGenericType(typeof(T));
                            var methodInfo = propType.GetTypeInfo().GetMethod("Method");

                            var operationDefinition = new OperationDefinition("Method", null, methodInfo);
                            var requestDefinition   = new RequestDefinition(operationDefinition, _ => false);

                            var typeMap = Globals.ServiceManager20.GetSerializer(dtoVersion).GetTypeMap(typeof(T));
                            typeMap.Serialize(writer, XRoadXmlTemplate.EmptyNode, value, requestDefinition.Content, message);

                            writer.WriteEndElement();

                            if (addEnvelope)
                            {
                                writer.WriteEndElement();
                            }

                            writer.Flush();

                            stream.Position = 0;
                            using (var reader = new StreamReader(stream))
                            {
                                if (!addEnvelope)
                                {
                                    f(message, reader.ReadToEnd());
                                    return;
                                }

                                using (var xmlReader = XmlReader.Create(reader))
                                {
                                    xmlReader.MoveToElement(0, "Envelope");
                                    f(message, xmlReader.ReadInnerXml());
                                }
                            }
                        }
        }
Beispiel #9
0
        public override OperationDefinition EndVisitOperationDefinition(
            OperationDefinition definition)
        {
            {
                Tracker.LeaveOperationDefinition?.Invoke(definition);
            }

            return(base.EndVisitOperationDefinition(definition));
        }
Beispiel #10
0
 public GraphQLQuery(
     OperationDefinition operationDefinition,
     Expression <Func <JObject,
                       IEnumerable <TResult> > > expression)
 {
     OperationDefinition = operationDefinition;
     Expression          = expression;
     CompiledExpression  = expression.Compile();
 }
Beispiel #11
0
        public override OperationDefinition BeginVisitOperationDefinition(
            OperationDefinition definition)
        {
            {
                Tracker.EnterOperationDefinition?.Invoke(definition);
            }

            return(base.BeginVisitOperationDefinition(definition));
        }
Beispiel #12
0
 private IGraphQlScalarResult Resolve(Document ast, OperationDefinition def, IDictionary <string, IGraphQlParameterInfo> arguments)
 {
     var operation = def.OperationType switch
     {
         OperationType.Query => options.Query,
         OperationType.Mutation => options.Mutation,
         OperationType.Subscription => options.Subscription,
         _ => throw new NotSupportedException()
     } ?? throw new NotSupportedException();
Beispiel #13
0
 public virtual OperationDefinition BeginVisitOperationDefinition(
     OperationDefinition definition)
 {
     if (definition.VariableDefinitions != null)
     {
         BeginVisitVariableDefinitions(definition.VariableDefinitions);
     }
     BeginVisitNode(definition.SelectionSet);
     return(EndVisitOperationDefinition(definition));
 }
Beispiel #14
0
 public void Deconstruct(out ISchema schema, out ExecutableDocument document,
                         out OperationDefinition operation, out object initialValue,
                         out IReadOnlyDictionary <string, object?> coercedVariableValues)
 {
     schema                = Schema;
     document              = Document;
     operation             = OperationDefinition;
     initialValue          = InitialValue;
     coercedVariableValues = CoercedVariableValues;
 }
Beispiel #15
0
 private OperationDTO _CreateDTO(OperationDefinition Definition, MemoryAddress Address, IMemoryBank Bank)
 {
     return(new OperationDTO
            (
                Definition.OpCode,
                Definition.DataSize == 0 ?
                new byte[] {} :
                _ReadData(Definition.DataSize, Address + new MemoryAddress(1), Bank)
            ));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleQuery{TResult}"/> class.
        /// </summary>
        /// <param name="operationDefinition">The GraphQL operation definition.</param>
        /// <param name="resultBuilder">
        /// A function which transforms JSON data into the final result.
        /// </param>
        public SimpleQuery(
            OperationDefinition operationDefinition,
            Expression <Func <JObject, TResult> > resultBuilder)
        {
            var serializer = new QuerySerializer();

            OperationDefinition = operationDefinition;
            Query         = serializer.Serialize(operationDefinition);
            ResultBuilder = ExpressionCompiler.Compile(resultBuilder);
        }
Beispiel #17
0
 protected override void ExitOperationDefinition(PrinterContext context, OperationDefinition operationDefinition)
 {
     if (context.Parent is ICollectionNode <OperationDefinition> )
     {
         if (context.CurrentArray?.Count > 0 && !context.CurrentArray.IsLast)
         {
             context.Append(" ");
         }
     }
 }
Beispiel #18
0
        public string Serialize(OperationDefinition operation)
        {
            StringBuilder builder = new StringBuilder();

            switch (operation.Type)
            {
            case OperationType.Query:
                builder.Append("query");
                break;

            case OperationType.Mutation:
                builder.Append("mutation");
                break;

            case OperationType.Subscription:
                throw new NotImplementedException();

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (operation.Name != null)
            {
                builder.Append(' ').Append(operation.Name);
            }

            if (operation.VariableDefinitions.Count > 0)
            {
                builder.Append('(');

                var first = true;
                foreach (var v in operation.VariableDefinitions)
                {
                    if (!first)
                    {
                        builder.Append(comma);
                    }
                    builder.Append('$').Append(v.Name).Append(colon).Append(v.Type);
                    first = false;
                }

                builder.Append(')');
            }

            SerializeSelections(operation, builder);

            foreach (var fragment in operation.FragmentDefinitions.Values)
            {
                builder.Append(Environment.NewLine);
                SerializeFragment(fragment, builder);
            }

            return(builder.ToString());
        }
        private IEnumerable <CSharpParameter> GetMethodParameters(OperationDefinition operation)
        {
            foreach (ParameterDefinition parameter in operation.Parameters)
            {
                CSharpParameter result = new CSharpParameter(
                    parameter.Name,
                    parameter.Type.GetCSharpName());

                yield return(result);
            }
        }
Beispiel #20
0
        public ProtoBufServiceMap(ISerializerCache serializerCache, OperationDefinition operationDefinition, RequestValueDefinition requestValueDefinition, ResponseValueDefinition responseValueDefinition, ITypeMap inputTypeMap, ITypeMap outputTypeMap)
            : base(serializerCache, operationDefinition, requestValueDefinition, responseValueDefinition, inputTypeMap, outputTypeMap)
        {
            var requestType  = RequestValueDefinition.ParameterInfo?.ParameterType;
            var responseType = ResponseValueDefinition.ParameterInfo?.ParameterType;

            readRequestMethod   = BuildReadValueMethod(requestType);
            readResponseMethod  = BuildReadValueMethod(responseType);
            writeRequestMethod  = BuildWriteValueMethod(requestType);
            writeResponseMethod = BuildWriteValueMethod(responseType);
        }
Beispiel #21
0
        public TestSystemServiceMap(XName operationName)
        {
            var methodInfo = typeof(Implementation).GetTypeInfo().GetMethod("Execute");

            OperationDefinition = new OperationDefinition(operationName, null, methodInfo);
            RequestDefinition   = new RequestDefinition(OperationDefinition, _ => false);
            ResponseDefinition  = new ResponseDefinition(OperationDefinition, _ => false)
            {
                ContainsNonTechnicalFault = true
            };
        }
    private void VisitOperationDefinition(OperationDefinition node)
    {
        EnterNode(node);

        Visit(node.VariableDefinitions);

        Visit(node.Directives);

        Visit(node.SelectionSet);

        ExitNode(node);
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleQuery{TResult}"/> class.
 /// </summary>
 /// <param name="operationDefinition">The GraphQL operation definition.</param>
 /// <param name="resultBuilder">
 /// A function which transforms JSON data into the final result.
 /// </param>
 /// <param name="parentIds">
 /// A function which given the data from the master query, returns the IDs of the
 /// entities which can be auto-paged.
 /// </param>
 /// <param name="pageInfo">
 /// A function which given the data from the sub-query, returns the paging info.
 /// </param>
 /// <param name="parentPageInfo">
 /// A function which given the data from the master query, returns the paging info
 /// for all entities which can be auto-paged.
 /// </param>
 public SimpleSubquery(
     OperationDefinition operationDefinition,
     Expression <Func <JObject, TResult> > resultBuilder,
     Expression <Func <JObject, IEnumerable <JToken> > > parentIds,
     Expression <Func <JObject, JToken> > pageInfo,
     Expression <Func <JObject, IEnumerable <JToken> > > parentPageInfo)
     : base(operationDefinition, resultBuilder)
 {
     ParentIds      = ExpressionCompiler.Compile(parentIds);
     PageInfo       = ExpressionCompiler.Compile(pageInfo);
     ParentPageInfo = ExpressionCompiler.Compile(parentPageInfo);
 }
        public string Serialize(OperationDefinition operation)
        {
            StringBuilder builder = new StringBuilder();

            if (operation.Type != OperationType.Query || operation.Name != null)
            {
                builder.Append("query ").Append(operation.Name);
            }

            SerializeSelections(operation, builder);
            return(builder.ToString());
        }
Beispiel #25
0
        /// <summary>
        /// Initialize new `listMethods` service map.
        /// </summary>
        public ListMethodsServiceMap(XName operationName)
        {
            var methodInfo = typeof(Implementation).GetTypeInfo().GetMethod("Execute");

            OperationDefinition     = new OperationDefinition(operationName, null, methodInfo);
            RequestValueDefinition  = new RequestValueDefinition(OperationDefinition);
            ResponseValueDefinition = new ResponseValueDefinition(OperationDefinition)
            {
                ContainsNonTechnicalFault = true,
                ResponseElementName       = operationName.NamespaceName == NamespaceConstants.XTEE ? "keha" : "response"
            };
        }
Beispiel #26
0
        public GraphQLQuery <TResult> Build <TResult>(IQueryable <TResult> query)
        {
            root             = null;
            syntax           = new SyntaxTree();
            lambdaParameters = new Dictionary <ParameterExpression, LambdaParameter>();

            var rewritten  = Visit(query.Expression);
            var expression = Expression.Lambda <Func <JObject, IEnumerable <TResult> > >(
                rewritten.AddCast(typeof(IQueryable <TResult>)),
                RootDataParameter);

            return(new GraphQLQuery <TResult>(root, expression));
        }
Beispiel #27
0
        /// <summary>
        /// Determines whether or not an operation's return type is a <see cref="Task" />.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <param name="returnType">
        /// The return type of the operation.
        /// This unwraps the <see cref="Task{T}"/> type.
        /// </param>
        /// <returns>True if the operation should be considered asynchronous, otherwise false.</returns>
        public static bool ReturnsTask(this OperationDefinition operation, out Type returnType)
        {
            bool isAsync = operation.ReturnsTask();

            Type type = operation.ReturnType;

            // Unwrap the Task<T> type if necessary
            returnType = isAsync
                ? type.GenericTypeArguments?.SingleOrDefault() ?? typeof(void)
                : type;

            return(isAsync);
        }
Beispiel #28
0
        /// <summary>
        /// Determines whether or not an operation's return type is a <see cref="Task" />.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <returns>True if the operation should be considered asynchronous, otherwise false.</returns>
        public static bool ReturnsTask(this OperationDefinition operation)
        {
            if (operation == null)
            {
                throw new ArgumentNullException(nameof(operation));
            }

            Type type = operation.ReturnType;

            bool isAsync = type.IsGenericType
                ? type.GetGenericTypeDefinition() == typeof(Task <>)
                : type == typeof(Task);

            return(isAsync);
        }
Beispiel #29
0
        /// <summary>
        /// Initializes new ServiceMap entity using settings specified in operationDefinition.
        /// <param name="serializer">Provides TypeMap lookup.</param>
        /// <param name="operationDefinition">Operation which this ServiceMap represents.</param>
        /// <param name="requestDefinition">Defines operation request message.</param>
        /// <param name="responseDefinition">Defines operation response message.</param>
        /// <param name="inputTypeMap">Default TypeMap of the operation request root element.</param>
        /// <param name="outputTypeMap"> Default TypeMap of the operation response root element.</param>
        /// </summary>
        public ServiceMap(ISerializer serializer, OperationDefinition operationDefinition, RequestDefinition requestDefinition, ResponseDefinition responseDefinition, ITypeMap inputTypeMap, ITypeMap outputTypeMap)
        {
            this.serializer = serializer;

            RequestDefinition   = requestDefinition;
            ResponseDefinition  = responseDefinition;
            OperationDefinition = operationDefinition;

            this.inputTypeMap = inputTypeMap is IContentTypeMap inputContentTypeMap && requestDefinition.Content.UseXop
                ? inputContentTypeMap.GetOptimizedContentTypeMap()
                : inputTypeMap;

            this.outputTypeMap = outputTypeMap is IContentTypeMap outputContentTypeMap && responseDefinition.Content.UseXop
                ? outputContentTypeMap.GetOptimizedContentTypeMap()
                : outputTypeMap;
        }
Beispiel #30
0
    public void OperationDefinition_EnterAndLeave()
    {
        /* Given */
        OperationDefinition definition = @"{ field }";

        var visitor = Substitute.For <VisitAllBase>();
        var sut     = new ReadOnlyExecutionDocumentWalker(
            new ExecutionDocumentWalkerOptions().Add(visitor));

        /* When */
        sut.Visit(definition);

        /* Then */
        visitor.Received().Enter(definition);
        visitor.Received().Leave(definition);
    }
        public Task<ILifecycleContext> Execute(ILifecycleContext context)
        {
            var serviceDefinition = new ServiceDefinition(context.ServiceDefinition);

            foreach (var normalOp in context.NormalizationContext.Operations)
            {
                var op = new OperationDefinition(NormalizeOperationPath(normalOp), normalOp.AsMetadata())
                {
                    ConsumesOctetStream = normalOp.SupportsStreaming,
                    Description = normalOp.Description,
                    HttpMethod = normalOp.HttpMethod,
                    Name = ExtractName(normalOp),
                    ResourceName = normalOp.ResourcePath.ResourceNameFromPath(),
                    Response = NormalizeResponseDefinition(normalOp)
                };

                normalOp.Parameters
                    .Select(NormalizeParameterDefinition)
                    .ToList()
                    .ForEach(x => op.AddParameter(x));

                if (serviceDefinition.Operations.Any(x => x.ResourceName == op.ResourceName && x.Name == op.Name))
                {
                    var pathParams = op.Parameters.Where(x => x.Type == ParameterType.Path && x.IsRequired).OrderBy(x => x.Name);
                    op.Name += string.Join("And", pathParams.Select(x => "By" + x.Name.UCFirst()));
                }

                serviceDefinition.AddOperation(op);
            }

            var ctx = new LifecycleContext(context)
            {
                ServiceDefinition = serviceDefinition,
                State = LifecycleState.Continue
            };
            return Task.FromResult<ILifecycleContext>(ctx);
        }
Beispiel #32
0
 public ServiceDefinition AddOperation(OperationDefinition operation)
 {
     operation.Context = this;
     Operations.Add(operation);
     return this;
 }