public LongRunningOperation(OperationGroup operationGroup, Operation operation, BuildContext context) : base(context)
        {
            Debug.Assert(operation.IsLongRunning);

            var clientClass = context.Library.FindClient(operationGroup);

            Debug.Assert(clientClass != null, "clientClass != null, LROs should be disabled when public clients are disables");

            DefaultName   = clientClass.RestClient.ClientPrefix + operation.CSharpName() + "Operation";
            FinalStateVia = operation.LongRunningFinalStateVia switch
            {
                "azure-async-operation" => OperationFinalStateVia.AzureAsyncOperation,
                "location" => OperationFinalStateVia.Location,
                "original-uri" => OperationFinalStateVia.OriginalUri,
                null => OperationFinalStateVia.Location,
                _ => throw new ArgumentException($"Unknown final-state-via value: {operation.LongRunningFinalStateVia}")
            };

            var    finalResponse       = operation.LongRunningFinalResponse;
            Schema?finalResponseSchema = finalResponse.ResponseSchema;

            if (finalResponseSchema != null)
            {
                ResultType          = TypeFactory.GetOutputType(context.TypeFactory.CreateType(finalResponseSchema, false));
                ResultSerialization = new SerializationBuilder().Build(finalResponse.HttpResponse.KnownMediaType, finalResponseSchema, ResultType);
            }
            else
            {
                ResultType = typeof(Response);
            }

            Description          = BuilderHelpers.EscapeXmlDescription(operation.Language.Default.Description);
            DefaultAccessibility = clientClass.Declaration.Accessibility;
        }
示例#2
0
        private IEnumerable <ClientMethod> BuildMethods()
        {
            foreach (var operation in _operationGroup.Operations)
            {
                if (operation.IsLongRunning || operation.Language.Default.Paging != null)
                {
                    continue;
                }

                foreach (var request in operation.Requests)
                {
                    var name = operation.CSharpName();
                    RestClientMethod startMethod = RestClient.GetOperationMethod(request);

                    yield return(new ClientMethod(
                                     name,
                                     startMethod,
                                     BuilderHelpers.EscapeXmlDescription(operation.Language.Default.Description),
                                     new Diagnostic($"{Declaration.Name}.{name}", Array.Empty <DiagnosticAttribute>())));
                }
            }
        }
示例#3
0
 private static string CreateDescription(RequestParameter requestParameter)
 {
     return(string.IsNullOrWhiteSpace(requestParameter.Language.Default.Description) ?
            $"The {requestParameter.Schema.Name} to use." :
            BuilderHelpers.EscapeXmlDescription(requestParameter.Language.Default.Description));
 }
示例#4
0
 protected static string CreateDescription(OperationGroup operationGroup, string clientPrefix)
 {
     return(string.IsNullOrWhiteSpace(operationGroup.Language.Default.Description) ?
            $"The {clientPrefix} service client." :
            BuilderHelpers.EscapeXmlDescription(operationGroup.Language.Default.Description));
 }
示例#5
0
        private RestClientMethod BuildMethod(Operation operation, HttpRequest httpRequest, ICollection <RequestParameter> requestParameters, ResponseHeaderGroupType?responseHeaderModel)
        {
            HttpWithBodyRequest?httpRequestWithBody         = httpRequest as HttpWithBodyRequest;
            Dictionary <string, PathSegment> uriParameters  = new Dictionary <string, PathSegment>();
            Dictionary <string, PathSegment> pathParameters = new Dictionary <string, PathSegment>();
            List <QueryParameter>            query          = new List <QueryParameter>();
            List <RequestHeader>             headers        = new List <RequestHeader>();
            Dictionary <RequestParameter, ReferenceOrConstant> allParameters    = new Dictionary <RequestParameter, ReferenceOrConstant>();
            Dictionary <RequestParameter, Parameter>           methodParameters = new Dictionary <RequestParameter, Parameter>();

            RequestBody?body = null;

            (RequestParameter, ReferenceOrConstant)? bodyParameter = null;
            RequestParameter[] parameters = operation.Parameters.Concat(requestParameters).ToArray();
            foreach (RequestParameter requestParameter in parameters)
            {
                string defaultName    = requestParameter.Language.Default.Name;
                string serializedName = requestParameter.Language.Default.SerializedName ?? defaultName;
                ReferenceOrConstant constantOrReference;
                Schema valueSchema = requestParameter.Schema;

                if (requestParameter.Implementation == ImplementationLocation.Method)
                {
                    Parameter?parameter = null;
                    // TODO: always generate virtual parameters
                    if (!(requestParameter is VirtualParameter) &&
                        requestParameter.Schema is ConstantSchema constant)
                    {
                        constantOrReference = ParseConstant(constant);
                        valueSchema         = constant.ValueType;
                    }
                    else
                    {
                        parameter = BuildParameter(requestParameter);

                        if (requestParameter.GroupedBy is RequestParameter groupedByParameter)
                        {
                            var groupModel = (ObjectType)_context.TypeFactory.CreateType(groupedByParameter.Schema, false).Implementation;
                            var property   = groupModel.GetPropertyForGroupedParameter(requestParameter);

                            constantOrReference = new Reference($"{groupedByParameter.CSharpName()}.{property.Declaration.Name}", property.Declaration.Type);
                        }
                        else
                        {
                            constantOrReference = parameter;
                        }
                    }

                    allParameters.Add(requestParameter, constantOrReference);

                    if (parameter != null &&
                        requestParameter.Flattened != true &&
                        requestParameter.GroupedBy == null)
                    {
                        methodParameters.Add(requestParameter, parameter);
                    }
                }
                else
                {
                    constantOrReference = _parameters[requestParameter.Language.Default.Name];
                }

                if (requestParameter.Protocol.Http is HttpParameter httpParameter)
                {
                    SerializationFormat serializationFormat = BuilderHelpers.GetSerializationFormat(valueSchema);
                    bool skipEncoding = requestParameter.Extensions !.TryGetValue("x-ms-skip-url-encoding", out var value) && Convert.ToBoolean(value);
                    switch (httpParameter.In)
                    {
                    case ParameterLocation.Header:
                        headers.Add(new RequestHeader(serializedName, constantOrReference, GetSerializationStyle(httpParameter, valueSchema), serializationFormat));
                        break;

                    case ParameterLocation.Query:
                        query.Add(new QueryParameter(serializedName, constantOrReference, GetSerializationStyle(httpParameter, valueSchema), !skipEncoding, serializationFormat));
                        break;

                    case ParameterLocation.Path:
                        pathParameters.Add(serializedName, new PathSegment(constantOrReference, !skipEncoding, serializationFormat));
                        break;

                    case ParameterLocation.Body:
                        bodyParameter = (requestParameter, constantOrReference);
                        break;

                    case ParameterLocation.Uri:
                        uriParameters.Add(serializedName, new PathSegment(constantOrReference, !skipEncoding, serializationFormat, isRaw: true));
                        break;
                    }
                }
            }

            if (bodyParameter is var(bodyRequestParameter, bodyParameterValue))
            {
                Debug.Assert(httpRequestWithBody != null);
                if (httpRequestWithBody.KnownMediaType == KnownMediaType.Binary)
                {
                    body = new BinaryRequestBody(bodyParameterValue);
                }
                else if (httpRequestWithBody.KnownMediaType == KnownMediaType.Text)
                {
                    body = new TextRequestBody(bodyParameterValue);
                }
                else
                {
                    var serialization = _serializationBuilder.Build(
                        httpRequestWithBody.KnownMediaType,
                        bodyRequestParameter.Schema,
                        bodyParameterValue.Type);

                    // This method has a flattened body
                    if (bodyRequestParameter.Flattened == true)
                    {
                        var objectType        = (ObjectType)_context.Library.FindTypeForSchema(bodyRequestParameter.Schema);
                        var virtualParameters = requestParameters.OfType <VirtualParameter>().ToArray();

                        List <ObjectPropertyInitializer> initializationMap = new List <ObjectPropertyInitializer>();
                        foreach (var virtualParameter in virtualParameters)
                        {
                            var actualParameter = allParameters[virtualParameter];

                            initializationMap.Add(new ObjectPropertyInitializer(
                                                      objectType.GetPropertyForSchemaProperty(virtualParameter.TargetProperty, true),
                                                      actualParameter));
                        }

                        body = new FlattenedSchemaRequestBody(objectType, initializationMap.ToArray(), serialization);
                    }
                    else
                    {
                        body = new SchemaRequestBody(bodyParameterValue, serialization);
                    }
                }
            }

            PathSegment[] pathSegments = GetPathSegments(httpRequest.Uri, uriParameters, isRaw: true)
                                         .Concat(GetPathSegments(httpRequest.Path, pathParameters))
                                         .ToArray();
            Request request = new Request(
                httpRequest.Method.ToCoreRequestMethod() ?? RequestMethod.Get,
                pathSegments,
                query.ToArray(),
                headers.ToArray(),
                body
                );

            string operationName = operation.CSharpName();

            List <Response> clientResponse = new List <Response>();

            if (operation.IsLongRunning)
            {
                // Ignore response body and headers for LROs as the ArmOperationHelpers figures out them dynamically
                responseHeaderModel = null;
            }

            foreach (var response in operation.Responses)
            {
                clientResponse.Add(new Response(
                                       operation.IsLongRunning ? null : BuildResponseBody(response),
                                       response.HttpResponse.IntStatusCodes.ToArray()
                                       ));
            }

            var responseType = ReduceResponses(clientResponse);

            return(new RestClientMethod(
                       operationName,
                       BuilderHelpers.EscapeXmlDescription(operation.Language.Default.Description),
                       responseType,
                       request,
                       OrderParameters(methodParameters.Values),
                       clientResponse.ToArray(),
                       responseHeaderModel
                       ));
        }
示例#6
0
        private IEnumerable <ObjectTypeProperty> BuildProperties()
        {
            // WORKAROUND: https://github.com/Azure/autorest.modelerfour/issues/261
            var existingProperties = EnumerateHierarchy()
                                     .Skip(1)
                                     .SelectMany(type => type.Properties)
                                     .Select(p => p.SchemaProperty?.Language.Default.Name)
                                     .ToHashSet();

            foreach (var objectSchema in GetCombinedSchemas())
            {
                foreach (Property property in objectSchema.Properties !)
                {
                    if (existingProperties.Contains(property.Language.Default.Name))
                    {
                        // WORKAROUND: https://github.com/Azure/autorest.modelerfour/issues/261
                        continue;
                    }

                    var name = BuilderHelpers.DisambiguateName(Type, property.CSharpName());
                    SourceMemberMapping?memberMapping = _sourceTypeMapping?.GetForMember(name);
                    bool isNotInput = (objectSchema.IsOutput || objectSchema.IsException) && !objectSchema.IsInput;
                    bool isReadOnly = IsStruct ||
                                      isNotInput ||
                                      property.ReadOnly == true ||
                                      // Required properties of input objects should be readonly
                                      (property.Required == true && objectSchema.IsInputOnly);

                    if (property.IsDiscriminator == true)
                    {
                        // Discriminator properties should be writeable
                        isReadOnly = false;
                    }

                    CSharpType type = _typeFactory.CreateType(
                        property.Schema,
                        property.IsNullable());

                    if (!_objectSchema.IsInput)
                    {
                        type = TypeFactory.GetOutputType(type);
                    }

                    var accessibility = property.IsDiscriminator == true ? "internal" : "public";

                    CSharpType?initializeWithType = memberMapping?.Initialize == true?TypeFactory.GetImplementationType(type) : null;

                    yield return(new ObjectTypeProperty(
                                     BuilderHelpers.CreateMemberDeclaration(name, type, accessibility, memberMapping?.ExistingMember, _typeFactory),
                                     BuilderHelpers.EscapeXmlDescription(property.Language.Default.Description),
                                     isReadOnly,
                                     property,
                                     initializeWithType,
                                     memberMapping?.EmptyAsUndefined ?? false));
                }
            }

            if (AdditionalPropertiesProperty is ObjectTypeProperty additionalPropertiesProperty)
            {
                yield return(additionalPropertiesProperty);
            }
        }
示例#7
0
 private static string CreateDescription(ChoiceValue choiceValue)
 {
     return(string.IsNullOrWhiteSpace(choiceValue.Language.Default.Description) ? choiceValue.Value : BuilderHelpers.EscapeXmlDescription(choiceValue.Language.Default.Description));
 }