コード例 #1
0
 private static IEnumerable <MemberDeclarationSyntax> LroPartialClasses(SourceFileContext ctx, ServiceDetails svc)
 {
     if (svc.Methods.Any(m => m is MethodDetails.Lro))
     {
         // Emit partial class to give access to an LRO operations client.
         var grpcOuterCls = Class(Public | Static | Partial, svc.GrpcClientTyp.DeclaringTyp);
         using (ctx.InClass(grpcOuterCls))
         {
             var grpcInnerClass = Class(Public | Partial, svc.GrpcClientTyp);
             using (ctx.InClass(grpcInnerClass))
             {
                 var callInvoker = Property(Private, ctx.TypeDontCare, "CallInvoker");
                 var opTyp       = ctx.Type <Operations.OperationsClient>();
                 var createOperationsClientMethod = Method(Public | Virtual, opTyp, "CreateOperationsClient")()
                                                    .WithBody(New(opTyp)(callInvoker))
                                                    .WithXmlDoc(
                     XmlDoc.Summary("Creates a new instance of ", opTyp, " using the same call invoker as this client."),
                     XmlDoc.Returns("A new Operations client for the same target as this client.")
                     );
                 grpcInnerClass = grpcInnerClass.AddMembers(createOperationsClientMethod);
             }
             grpcOuterCls = grpcOuterCls.AddMembers(grpcInnerClass);
         }
         yield return(grpcOuterCls);
     }
 }
コード例 #2
0
        private static ResultFile GenerateCSharpCode(PackageModel package)
        {
            var ctx = SourceFileContext.CreateFullyQualified(SystemClock.Instance);
            var ns  = Namespace(package.PackageName);

            using (ctx.InNamespace(ns))
            {
                var serviceClass     = package.GenerateServiceClass(ctx);
                var baseRequestClass = package.GenerateBaseRequestClass(ctx);
                ns = ns.AddMembers(serviceClass, baseRequestClass);

                foreach (var resource in package.Resources)
                {
                    var resourceClass = resource.GenerateClass(ctx);
                    ns = ns.AddMembers(resourceClass);
                }
            }
            var dataNs = Namespace(package.PackageName + ".Data");

            using (ctx.InNamespace(dataNs))
            {
                foreach (var dataModel in package.DataModels.Where(dm => dm.Parent is null))
                {
                    dataNs = dataNs.AddMembers(dataModel.GenerateClass(ctx));
                }
            }
            var syntax = ctx.CreateCompilationUnit(ns).AddMembers(dataNs);

            return(new ResultFile($"{package.PackageName}.cs", syntax));
        }
コード例 #3
0
        private static ResultFile GenerateCSharpCode(PackageModel package)
        {
            var ctx = SourceFileContext.CreateFullyQualified(SystemClock.Instance);
            var ns  = Namespace(package.PackageName);

            using (ctx.InNamespace(ns))
            {
                var serviceClass     = package.GenerateServiceClass(ctx);
                var baseRequestClass = package.GenerateBaseRequestClass(ctx);
                ns = ns.AddMembers(serviceClass, baseRequestClass);

                foreach (var resource in package.Resources)
                {
                    var resourceClass = resource.GenerateClass(ctx);
                    ns = ns.AddMembers(resourceClass);
                }
            }
            var dataNs = Namespace(package.PackageName + ".Data");

            using (ctx.InNamespace(dataNs))
            {
                var dataModels = package.DataModels
                                 .Where(dm => dm.Parent is null && !dm.IsPlaceholder)
                                 .OrderBy(dm => dm.Typ.Name, StringComparer.Ordinal);
                foreach (var dataModel in dataModels)
                {
                    dataNs = dataNs.AddMembers(dataModel.GenerateClass(ctx));
                }
            }
            var syntax = ctx.CreateCompilationUnit(ns).AddMembers(dataNs);

            string content = ApplyIfDirectives(CodeFormatter.Format(syntax).ToFullString());

            return(new ResultFile($"{package.PackageName}/{package.PackageName}.cs", content));
        }
コード例 #4
0
        public void DataParserTest()
        {
            var s       = "'a',1,'c',2,'2017-10-01 14:15:16'\n'a1',1.1,c1,3,'2017-10-04";
            var context = new SourceFileContext();
            var stream  = GetStreamFromString(s);

            context.Stream            = new StreamReader(stream);
            context.FileConfiguration = new File
            {
                Delimiter = ",",
                Qualifier = "'"
            };
            var log    = new ConsoleLogger();
            var reader = context.BufferedRead(log).CsvReader(context, log);
            var parser = reader.ParseData(getConfig(), new ConsoleLogger());
            var row    = parser();

            Assert.IsNotNull(row);
            Assert.IsTrue(string.IsNullOrEmpty(row.Error));
            Assert.AreEqual(5, row.Columns.Count);
            Assert.AreEqual("a", row["A"].ToString());
            Assert.AreEqual("1", row["B"].ToString());
            Assert.AreEqual("c", row["C"].ToString());
            Assert.AreEqual("2", row["D"].ToString());
            Assert.AreEqual("01/10/2017", row["E"].ToString("dd/MM/yyyy"));
            Assert.IsInstanceOfType(row["B"], typeof(IValue <decimal>));
            Assert.AreEqual(1, ((IValue <decimal>)row["B"]).GetValue());
            row = parser();
            Assert.IsTrue(string.IsNullOrEmpty(row.Error));
            Assert.AreEqual(5, row.Columns.Count);
            Assert.AreEqual("1.1", row["B"].ToString());
            Assert.IsInstanceOfType(row["B"], typeof(IValue <decimal>));
            Assert.AreEqual((decimal)1.1, ((IValue <decimal>)row["B"]).GetValue());
        }
コード例 #5
0
        internal CompilationUnitSyntax GenerateCompilationUnit()
        {
            var ctx = SourceFileContext.CreateFullyQualified(SystemClock.Instance);
            var ns  = Namespace(PackageName);

            using (ctx.InNamespace(ns))
            {
                var serviceClass     = GenerateServiceClass(ctx);
                var baseRequestClass = GenerateBaseRequestClass(ctx);
                ns = ns.AddMembers(serviceClass, baseRequestClass);

                foreach (var resource in Resources)
                {
                    var resourceClass = resource.GenerateClass(ctx);
                    ns = ns.AddMembers(resourceClass);
                }
            }
            var dataNs = Namespace(PackageName + ".Data");

            using (ctx.InNamespace(dataNs))
            {
                var dataModels = DataModels
                                 .Where(dm => !dm.IsPlaceholder)
                                 .OrderBy(dm => dm.Typ.Name, StringComparer.Ordinal);
                foreach (var dataModel in dataModels)
                {
                    dataNs = dataNs.AddMembers(dataModel.GenerateClass(ctx));
                }
            }
            return(ctx.CreateCompilationUnit(ns).AddMembers(dataNs));
        }
コード例 #6
0
        public ClassDeclarationSyntax GenerateBaseRequestClass(SourceFileContext ctx)
        {
            var cls = Class(
                Modifier.Public,
                Typ.Generic(Typ.Manual(PackageName, $"{ClassName}BaseServiceRequest"), Typ.GenericParam("TResponse")),
                ctx.Type(Typ.Generic(typeof(ClientServiceRequest <>), Typ.GenericParam("TResponse"))))
                      .WithXmlDoc(XmlDoc.Summary($"A base abstract class for {ClassName} requests."));

            var serviceParam = Parameter(ctx.Type <IClientService>(), "service");
            var ctor         = Ctor(Modifier.Protected, cls, BaseInitializer(serviceParam))(serviceParam)
                               .WithBody()
                               .WithXmlDoc(XmlDoc.Summary($"Constructs a new {ClassName}BaseServiceRequest instance."));

            cls = cls.AddMembers(ctor);

            var parameters = _discoveryDoc.Parameters.Select(p => new ParameterModel(p.Key, p.Value))
                             .OrderBy(p => p.PropertyName)
                             .ToList();

            cls = cls.AddMembers(parameters.Select(p => p.GenerateProperty(ctx)).ToArray());

            var initParameters = Method(Modifier.Protected | Modifier.Override, VoidType, "InitParameters")()
                                 .WithBlockBody(
                BaseExpression().Call("InitParameters")(),
                parameters.Select(p => p.GenerateInitializer(ctx)).ToArray())
                                 .WithXmlDoc(XmlDoc.Summary($"Initializes {ClassName} parameter list."));

            cls = cls.AddMembers(initParameters);
            return(cls);
        }
コード例 #7
0
        private MethodDeclarationSyntax GenerateMethodDeclaration(SourceFileContext ctx)
        {
            var parameters            = CreateParameterList(RequestTyp);
            var docs                  = new List <DocumentationCommentTriviaSyntax>();
            var methodParameters      = parameters.TakeWhile(p => p.IsRequired).ToList();
            var parameterDeclarations = methodParameters.Select(p => Parameter(ctx.Type(p.Typ), p.CodeParameterName)).ToList();

            if (_restMethod.Description is object)
            {
                docs.Add(XmlDoc.Summary(_restMethod.Description));
            }
            docs.AddRange(methodParameters.Zip(parameterDeclarations).Select(pair => XmlDoc.Param(pair.Second, pair.First.Description)));
            if (BodyTyp is object)
            {
                parameterDeclarations.Insert(0, Parameter(ctx.Type(BodyTyp), "body"));
                docs.Insert(1, XmlDoc.Param(parameterDeclarations[0], "The body of the request."));
            }

            var ctorArguments = new object[] { Field(0, ctx.Type <IClientService>(), "service") }
            .Concat(parameterDeclarations)
            .ToArray();
            var method = Method(Modifier.Public | Modifier.Virtual, ctx.Type(RequestTyp), PascalCasedName)(parameterDeclarations.ToArray())
                         .WithBlockBody(Return(New(ctx.Type(RequestTyp))(ctorArguments)))
                         .WithXmlDoc(docs.ToArray());

            return(method);
        }
コード例 #8
0
        public static MethodDeclarationSyntax ModifyRequestPartialMethod(SourceFileContext ctx, MethodDetails method)
        {
            var requestParam  = Parameter(ctx.Type(method.RequestTyp), "request").Ref();
            var settingsParam = Parameter(ctx.Type <CallSettings>(), "settings").Ref();

            return(PartialMethod(method.ModifyRequestMethodName)(requestParam, settingsParam));
        }
        private static MethodDeclarationSyntax GenerateMethod(SourceFileContext ctx, ServiceDetails service)
        {
            var name = $"Add{service.ClientAbstractTyp.Name}";
            var serviceCollection = ctx.Type <IServiceCollection>();
            var services          = Parameter(serviceCollection, "services")
                                    .WithModifiers(SyntaxTokenList.Create(Token(SyntaxKind.ThisKeyword).WithTrailingSpace()));
            var actionType = ctx.Type(Typ.Generic(typeof(Action <>), service.BuilderTyp));
            var action     = Parameter(actionType, "action", @default: Null);

            var builderType = ctx.Type(service.BuilderTyp);
            var builder     = Local(builderType, "builder");

            var provider = Parameter(ctx.Type <IServiceProvider>(), "provider");
            var lambda   = Lambda(provider)(
                builder.WithInitializer(New(builderType)()),
                action.Call("Invoke", true)(builder),
                Return(builder.Call("Build")(provider))
                );

            return(Method(Public | Static, serviceCollection, name)(services, action)
                   .WithBody(services.Call("AddSingleton")(lambda))
                   .WithXmlDoc(
                       XmlDoc.Summary("Adds a singleton ", ctx.Type(service.ClientAbstractTyp), " to ", services, "."),
                       XmlDoc.Param(services, "The service collection to add the client to. The services are used to configure the client when requested."),
                       XmlDoc.Param(action, "An optional action to invoke on the client builder. This is invoked before services from ", services, " are used.")
                       ));
        }
コード例 #10
0
 public ResourceClassBuilder(SourceFileContext ctx, ResourceDetails.Definition def)
 {
     _ctx = ctx;
     _def = def;
     ResourceNameTypeTyp = Typ.Nested(def.ResourceNameTyp, "ResourceNameType", isEnum: true);
     PatternDetails      = _def.Patterns.Where(x => !x.IsWildcard).Select(x => new PatternDetails(ctx, def, x)).ToList();
 }
コード例 #11
0
ファイル: ReaderTests.cs プロジェクト: HerrDmitry/DataMover
        public void CsvReadTest3()
        {
            var s       = "'a''b',,'c'\n'd','e\ne',f";
            var context = new SourceFileContext();
            var stream  = GetStreamFromString(s);

            context.Stream            = new StreamReader(stream);
            context.FileConfiguration = new File
            {
                Delimiter = ",",
                Qualifier = "'",
                Name      = "Test"
            };
            var log = new ConsoleLogger();

            var reader = context.BufferedRead(log).CsvReader(context, log);

            Assert.IsNotNull(reader);
            var row = reader();

            Assert.IsNotNull(row);
            Assert.AreEqual("a'b", row.Fields[0].ToString());
            Assert.IsTrue(row.Fields[1].Source == null);
            Assert.AreEqual("c", row.Fields[2].ToString());
        }
コード例 #12
0
        public IEnumerable <PropertyDeclarationSyntax> GeneratePropertyDeclarations(SourceFileContext ctx)
        {
            var propertyTyp = SchemaTypes.GetTypFromSchema(Parent.Package, _schema, Name, ctx.CurrentTyp, inParameter: false);

            if (propertyTyp.FullName == "System.Nullable<System.DateTime>")
            {
                // DateTime values generate two properties: one raw as a string, and one DateTime version.
                var rawProperty = AutoProperty(Modifier.Public | Modifier.Virtual, ctx.Type <string>(), PropertyName + "Raw", hasSetter: true)
                                  .WithAttribute(ctx.Type <JsonPropertyAttribute>())(Name);
                if (_schema.Description is object)
                {
                    rawProperty = rawProperty.WithXmlDoc(XmlDoc.Summary(_schema.Description));
                }
                yield return(rawProperty);

                var valueParameter = Parameter(ctx.Type(propertyTyp), "value");
                yield return(Property(Modifier.Public | Modifier.Virtual, ctx.Type(propertyTyp), PropertyName)
                             .WithAttribute(ctx.Type <JsonIgnoreAttribute>())()
                             .WithXmlDoc(XmlDoc.Summary(XmlDoc.SeeAlso(ctx.Type <DateTime>()), " representation of ", rawProperty, "."))
                             .WithGetBody(Return(ctx.Type(typeof(Utilities)).Call(nameof(Utilities.GetDateTimeFromString))(rawProperty)))
                             .WithSetBody(rawProperty.Assign(ctx.Type(typeof(Utilities)).Call(nameof(Utilities.GetStringFromDateTime))(valueParameter))));
            }
            else
            {
                var property = AutoProperty(Modifier.Public | Modifier.Virtual, ctx.Type(propertyTyp), PropertyName, hasSetter: true)
                               .WithAttribute(ctx.Type <JsonPropertyAttribute>())(Name);
                if (_schema.Description is object)
                {
                    property = property.WithXmlDoc(XmlDoc.Summary(_schema.Description));
                }
                yield return(property);
            }
        }
コード例 #13
0
        private static IEnumerable <MemberDeclarationSyntax> PaginatedPartialClasses(SourceFileContext ctx, ServiceDetails svc, HashSet <Typ> seenPaginatedResponseTyps)
        {
            var paginatedMethods = svc.Methods.OfType <MethodDetails.Paginated>();

            foreach (var representingMethod in paginatedMethods
                     .GroupBy(m => m.RequestTyp)
                     .Select(typMethodGrp => typMethodGrp.First()))
            {
                yield return(PaginatedPartialInterfaceClass(ctx, representingMethod.RequestTyp, representingMethod.RequestMessageDesc));
            }

            foreach (var method in paginatedMethods)
            {
                if (seenPaginatedResponseTyps.Add(method.ResponseTyp))
                {
                    var cls = Class(Public | Partial, method.ResponseTyp, baseTypes: ctx.Type(Typ.Generic(typeof(IPageResponse <>), method.ResourceTyp)));
                    using (ctx.InClass(cls))
                    {
                        var propertyName         = method.ResourcesFieldName;
                        var genericGetEnumerator = Method(Public, ctx.Type(Typ.Generic(typeof(IEnumerator <>), method.ResourceTyp)), "GetEnumerator")()
                                                   .WithBody(Property(Public, ctx.TypeDontCare, propertyName).Call(nameof(IEnumerable <int> .GetEnumerator))())
                                                   .WithXmlDoc(XmlDoc.Summary("Returns an enumerator that iterates through the resources in this response."));
                        var getEnumerator = Method(None, ctx.Type <IEnumerator>(), "GetEnumerator")()
                                            .WithExplicitInterfaceSpecifier(ctx.Type <IEnumerable>())
                                            .WithBody(This.Call(genericGetEnumerator)());
                        cls = cls.AddMembers(genericGetEnumerator, getEnumerator);
                    }
                    yield return(cls);
                }
            }
        }
コード例 #14
0
        private static IEnumerable <MemberDeclarationSyntax> MixinPartialClasses(SourceFileContext ctx, ServiceDetails svc)
        {
            if (svc.Mixins.Any())
            {
                // Emit partial class to give access to clients for mixin APIs.
                // (We may well have one of these *and* an LRO partial class, but that's okay.)
                var grpcOuterCls = Class(Public | Static | Partial, svc.GrpcClientTyp.DeclaringTyp);
                using (ctx.InClass(grpcOuterCls))
                {
                    var grpcInnerClass = Class(Public | Partial, svc.GrpcClientTyp);
                    using (ctx.InClass(grpcInnerClass))
                    {
                        var callInvoker = Property(Private, ctx.TypeDontCare, "CallInvoker");

                        foreach (var mixin in svc.Mixins)
                        {
                            var grpcClientType     = ctx.Type(mixin.GrpcClientType);
                            var createClientMethod = Method(Public | Virtual, grpcClientType, "Create" + mixin.GrpcClientType.Name)()
                                                     .WithBody(New(grpcClientType)(callInvoker))
                                                     .WithXmlDoc(
                                XmlDoc.Summary("Creates a new instance of ", grpcClientType, " using the same call invoker as this client."),
                                XmlDoc.Returns("A new ", grpcClientType, " for the same target as this client.")
                                );
                            grpcInnerClass = grpcInnerClass.AddMembers(createClientMethod);
                        }
                    }
                    grpcOuterCls = grpcOuterCls.AddMembers(grpcInnerClass);
                }
                yield return(grpcOuterCls);
            }
        }
コード例 #15
0
        public ClassDeclarationSyntax GenerateBaseRequestClass(SourceFileContext ctx)
        {
            var cls = Class(
                Modifier.Public | Modifier.Abstract,
                BaseRequestTyp,
                ctx.Type(Typ.Generic(typeof(ClientServiceRequest <>), Typ.GenericParam("TResponse"))))
                      .WithXmlDoc(XmlDoc.Summary($"A base abstract class for {ClassName} requests."));

            using (ctx.InClass(BaseRequestTyp))
            {
                var serviceParam = Parameter(ctx.Type <IClientService>(), "service");
                var ctor         = Ctor(Modifier.Protected, cls, BaseInitializer(serviceParam))(serviceParam)
                                   .WithBody()
                                   .WithXmlDoc(XmlDoc.Summary($"Constructs a new {ClassName}BaseServiceRequest instance."));

                var parameters = CreateParameterList(BaseRequestTyp);

                cls = cls.AddMembers(ctor);
                cls = cls.AddMembers(parameters.SelectMany(p => p.GenerateDeclarations(ctx)).ToArray());

                var initParameters = Method(Modifier.Protected | Modifier.Override, VoidType, "InitParameters")()
                                     .WithBlockBody(
                    BaseExpression().Call("InitParameters")(),
                    parameters.Select(p => p.GenerateInitializer(ctx)).ToArray())
                                     .WithXmlDoc(XmlDoc.Summary($"Initializes {ClassName} parameter list."));

                cls = cls.AddMembers(initParameters);
            }
            return(cls);
        }
コード例 #16
0
        public ClassDeclarationSyntax GenerateClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, Typ.Manual(Package.PackageName, ClassName))
                      // FIXME: Wirename is broken
                      .WithXmlDoc(XmlDoc.Summary($"The {WireName} collection of methods."));

            return(cls);
        }
コード例 #17
0
        public IEnumerable <MemberDeclarationSyntax> GenerateDeclarations(SourceFileContext ctx)
        {
            yield return(GenerateProperty(ctx));

            if (EnumModel is object)
            {
                yield return(EnumModel.GenerateDeclaration(ctx));
            }
        }
コード例 #18
0
        public ClassDeclarationSyntax GenerateClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, Typ);

            if (_schema.Description is string description)
            {
                cls = cls.WithXmlDoc(XmlDoc.Summary(description));
            }
            return(cls);
        }
コード例 #19
0
        public EnumMemberDeclarationSyntax GenerateDeclaration(SourceFileContext ctx)
        {
            var declaration = EnumMember(MemberName, NumericValue)
                              .WithAttribute(ctx.Type <StringValueAttribute>())(OriginalValue);

            if (Description is object)
            {
                declaration = declaration.WithXmlDoc(XmlDoc.Summary(Description));
            }
            return(declaration);
        }
コード例 #20
0
        public EnumDeclarationSyntax GenerateDeclaration(SourceFileContext ctx)
        {
            var declaration = Enum(Modifier.Public, Typ.Nested(ctx.CurrentTyp, TypeName, isEnum: true))
                                  (Members.Select(m => m.GenerateDeclaration(ctx)).ToArray());

            if (Description is string description)
            {
                declaration = declaration.WithXmlDoc(XmlDoc.Summary(description));
            }
            return(declaration);
        }
コード例 #21
0
        public static CompilationUnitSyntax GeneratePackageApiMetadata(string ns, SourceFileContext ctx, IEnumerable <FileDescriptor> packageFileDescriptors)
        {
            var namespaceDeclaration = Namespace(ns);

            using (ctx.InNamespace(namespaceDeclaration))
            {
                var descriptorClass = GenerateClass(ns, ctx, packageFileDescriptors);
                namespaceDeclaration = namespaceDeclaration.AddMembers(descriptorClass);
            }
            return(ctx.CreateCompilationUnit(namespaceDeclaration));
        }
コード例 #22
0
 public IEnumerable <ClassDeclarationSyntax> GenerateAnonymousModels(SourceFileContext ctx)
 {
     if (_schema.AdditionalProperties is object && DataModel.GetProperties(_schema.AdditionalProperties) is object)
     {
         var dataModel = new DataModel(Parent.Package, Parent, (Name + "Element").ToAnonymousModelClassName(Parent.Package, Parent.Typ.Name, true), _schema.AdditionalProperties);
         yield return(dataModel.GenerateClass(ctx));
     }
     else if (DataModel.GetProperties(_schema) is object)
     {
         var dataModel = new DataModel(Parent.Package, Parent, Name.ToAnonymousModelClassName(Parent.Package, Parent.Typ.Name, false), _schema);
         yield return(dataModel.GenerateClass(ctx));
     }
 }
コード例 #23
0
        private PropertyDeclarationSyntax GenerateProperty(SourceFileContext ctx)
        {
            var propertyType       = ctx.Type(Typ);
            var locationExpression = ctx.Type <RequestParameterType>().Access(Location.ToString());
            var property           = AutoProperty(Modifier.Public | Modifier.Virtual, propertyType, PropertyName, hasSetter: true, setterIsPrivate: IsRequired)
                                     .WithAttribute(ctx.Type <RequestParameterAttribute>())(Name, locationExpression);

            if (_schema.Description is string description)
            {
                property = property.WithXmlDoc(XmlDoc.Summary(description));
            }
            return(property);
        }
コード例 #24
0
        public PropertyDeclarationSyntax GenerateProperty(SourceFileContext ctx)
        {
            var property = AutoProperty(Modifier.Public | Modifier.Virtual, ctx.Type <string>(), PropertyName)
                           // TODO: Attribute arguments
                           // TODO: Default, Minimum, Maximum? Commented out...
                           .WithAttribute(ctx.Type <RequestParameterAttribute>());

            if (_schema.Description is string description)
            {
                property = property.WithXmlDoc(XmlDoc.Summary(description));
            }
            return(property);
        }
コード例 #25
0
        public IEnumerable <MemberDeclarationSyntax> GenerateDeclarations(SourceFileContext ctx)
        {
            yield return(GenerateMethodDeclaration(ctx));

            yield return(GenerateRequestType(ctx));

            if (SupportsMediaUpload)
            {
                foreach (var member in GenerateUploadMembers(ctx))
                {
                    yield return(member);
                }
            }
        }
コード例 #26
0
        private PropertyDeclarationSyntax GenerateRepeatedOptionalEnumProperty(SourceFileContext ctx)
        {
            var propertyType       = ctx.Type(Typ.Generic(Typ.Of(typeof(Repeatable <>)), Typ.GenericArgTyps.Single()));
            var locationExpression = ctx.Type <RequestParameterType>().Access(Location.ToString());
            var property           = AutoProperty(Modifier.Public | Modifier.Virtual, propertyType, PropertyName + "List", hasSetter: true)
                                     .WithAttribute(ctx.Type <RequestParameterAttribute>())(Name, locationExpression);

            if (_schema.Description is string description)
            {
                property = property.WithXmlDoc(
                    XmlDoc.Summary(description),
                    XmlDoc.Remarks($"Use this property to set one or more values for the parameter. Do not set both this property and ", IdentifierName(PropertyName), "."));
            }
            return(property);
        }
        public static CompilationUnitSyntax GenerateExtensions(SourceFileContext ctx, List <ServiceDetails> packageServiceDetails)
        {
            var ns = typeof(IServiceCollection).Namespace;
            var namespaceDeclaration = Namespace(ns);

            using (ctx.InNamespace(namespaceDeclaration))
            {
                var cls = Class(Public | Static | Partial, Typ.Manual(ns, ClassName))
                          .WithXmlDoc(XmlDoc.Summary("Static class to provide extension methods to configure API clients."));

                cls = cls.AddMembers(packageServiceDetails.Select(m => GenerateMethod(ctx, m)).ToArray());
                namespaceDeclaration = namespaceDeclaration.AddMembers(cls);
            }
            return(ctx.CreateCompilationUnit(namespaceDeclaration));
        }
コード例 #28
0
        public static CompilationUnitSyntax Generate(SourceFileContext ctx, ServiceDetails svc, HashSet <Typ> seenPaginatedResponseTyps)
        {
            var ns = Namespace(svc.Namespace);

            using (ctx.InNamespace(ns))
            {
                var settingsClass       = ServiceSettingsCodeGenerator.Generate(ctx, svc);
                var builderClass        = ServiceBuilderCodeGenerator.Generate(ctx, svc);
                var abstractClientClass = ServiceAbstractClientClassCodeGenerator.Generate(ctx, svc);
                var implClientClass     = ServiceImplClientClassGenerator.Generate(ctx, svc);
                ns = ns.AddMembers(settingsClass, builderClass, abstractClientClass, implClientClass);

                ns = ns.AddMembers(PaginatedPartialClasses(ctx, svc, seenPaginatedResponseTyps).ToArray());
                ns = ns.AddMembers(LroPartialClasses(ctx, svc).ToArray());
            }
            return(ctx.CreateCompilationUnit(ns));
        }
コード例 #29
0
                public PathElement(SourceFileContext ctx, ResourceDetails.Definition def, string rawPathElement)
                {
                    var nameWithoutId = rawPathElement.RemoveSuffix("_id");
                    var nameWithId    = $"{nameWithoutId}_id";

                    UpperCamel           = nameWithoutId.ToUpperCamelCase();
                    LowerCamel           = nameWithoutId.ToLowerCamelCase();
                    Parameter            = RoslynBuilder.Parameter(ctx.Type <string>(), nameWithId.ToLowerCamelCase());
                    ParameterWithDefault = RoslynBuilder.Parameter(ctx.Type <string>(), nameWithId.ToLowerCamelCase(), @default: Null);
                    ParameterXmlDoc      = XmlDoc.Param(Parameter, "The ", XmlDoc.C(nameWithoutId.ToUpperCamelCase()), " ID. Must not be ", null, " or empty.");
                    var summarySuffix = def.Patterns.Count > 1 ?
                                        new object[] { "May be ", null, ", depending on which resource name is contained by this instance." } :
                    new object[] { "Will not be ", null, ", unless this instance contains an unparsed resource name." };

                    Property = AutoProperty(Public, ctx.Type <string>(), nameWithId.ToUpperCamelCase())
                               .WithXmlDoc(XmlDoc.Summary(new object[] { "The ", XmlDoc.C(nameWithoutId.ToUpperCamelCase()), " ID. " }.Concat(summarySuffix).ToArray()));
                }
コード例 #30
0
        private PropertyDeclarationSyntax GenerateProperty(SourceFileContext ctx)
        {
            var propertyType       = ctx.Type(Typ);
            var locationExpression = ctx.Type <RequestParameterType>().Access(Location.ToString());
            var property           = AutoProperty(Modifier.Public | Modifier.Virtual, propertyType, PropertyName, hasSetter: true, setterIsPrivate: IsRequired)
                                     .WithAttribute(ctx.Type <RequestParameterAttribute>())(Name, locationExpression);

            if (_schema.Description is string description)
            {
                var summary = XmlDoc.Summary(description);
                var docs    = IsRepeatedOptionalEnum
                    ? new[] { summary, XmlDoc.Remarks($"Use this property to set a single value for the parameter, or ", IdentifierName(PropertyName + "List"), " to set multiple values. Do not set both properties.") }
                    : new[] { summary };
                property = property.WithXmlDoc(docs);
            }
            return(property);
        }