Exemplo n.º 1
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);
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        public BoundConstructor(ClassGen klass, Ctor constructor, bool useBase, CodeGenerationOptions opt, CodeGeneratorContext context)
        {
            this.constructor = constructor;
            this.opt         = opt;
            this.context     = context;

            Name = klass.Name;

            Comments.Add(string.Format("// Metadata.xml XPath constructor reference: path=\"{0}/constructor[@name='{1}'{2}]\"", klass.MetadataXPathReference, klass.JavaSimpleName, constructor.Parameters.GetMethodXPathPredicate()));

            Attributes.Add(new RegisterAttr(".ctor", constructor.JniSignature, string.Empty, additionalProperties: constructor.AdditionalAttributeString()));

            if (constructor.Deprecated != null)
            {
                Attributes.Add(new ObsoleteAttr(constructor.Deprecated.Replace("\"", "\"\"")));
            }

            if (constructor.CustomAttributes != null)
            {
                Attributes.Add(new CustomAttr(constructor.CustomAttributes));
            }

            if (constructor.Annotation != null)
            {
                Attributes.Add(new CustomAttr(constructor.Annotation));
            }

            SetVisibility(constructor.Visibility);
            IsUnsafe = true;

            BaseCall     = $"{(useBase ? "base" : "this")} (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)";
            context_this = context.ContextType.GetObjectHandleProperty("this");

            this.AddMethodParameters(constructor.Parameters, opt);
        }
Exemplo n.º 4
0
        public AggregateModule(IAggregateSchema <TAggregate> schema,
                               ICommandDispatcher commandDispatcher,
                               ILogger logger,
                               IServiceProvider serviceProvider)
        {
            foreach (var i in schema.Commands)
            {
                //TODO: should cache ctor for performance
                var binderType = typeof(PostBinder <>).MakeGenericType(typeof(TAggregate), i.Type);
                var binder     = Ctor <IBinder> .Create(binderType);

                binder.BindCommand(schema, this, commandDispatcher, logger);
            }

            Get(schema.Category + "/{id:Guid}", async(request, response) =>
            {
                var stream = serviceProvider.GetService <IAggregateEventStream <TAggregate> >();
                Guid id    = request.RouteValues.As <Guid>("id");
                var events = new List <IEvent>();
                await foreach (var e in stream.Get(id))
                {
                    events.Add(e);
                }
                await response.AsJson(events.ToArray());
            });
        }
Exemplo n.º 5
0
        public async Task <EventEnvelope[]> Append(Guid key, ulong version, Guid correlationId, IEnumerable <IEvent> published)
        {
            var  list   = _streams.GetOrAdd(key, k => new List <EventEnvelope>());
            uint i      = 0;
            var  result = published.Select(e =>
                                           new EventEnvelope(e, _metadataFactory.Create(key, correlationId, e, version + i++)))
                          .ToArray();

            lock (list)
            {
                if ((uint)list.Count == (version + 1))
                {
                    list.AddRange(result);
                }
                else
                {
                    throw new OptimisticConcurrencyException();
                }
            }
            LogEvents(key, version, result);
            foreach (var e in result)
            {
                var invoker = Ctor <IInvoker> .Create(typeof(Invoker <>).MakeGenericType(typeof(TAggregate), e.Event.GetType()));

                invoker.Invoke(_eventAggregator, e.Metadata, e.Event);
            }

            return(result);
        }
Exemplo n.º 6
0
        public async Task SubscribeFromProjectionStream(HubConnection connection, bool startFromBeginning, string projectionName, IEnumerable <Type> eventTypes)
        {
            await CheckConnection(connection);

            foreach (var e in eventTypes.Where(x => !_subscribedEvents.Contains(x)))
            {
                if (!_subscribedEvents.Contains(e))
                {
                    _subscribedEvents.Add(e);
                }
                else
                {
                    Debug.WriteLine($"Already subscribed for event-type: {e.Name}");
                }

                var configuratorType = typeof(ProjectionTypeStreamConfigurator <>).MakeGenericType(e);
                var configurator     = Ctor <IEventProjectionHandlerConfigurator> .Create(configuratorType);

                await configurator.Configure(startFromBeginning, connection, _dispatcher, _logger, projectionName);
            }
            if (startFromBeginning)
            {
                await connection.SubscribeToProjection(Guid.NewGuid(), StreamPosition.Beginning, projectionName);
            }
            else
            {
                await connection.SubscribeToProjection(Guid.NewGuid(), StreamPosition.Live, projectionName);
            }
        }
Exemplo n.º 7
0
        public async Task SubscribeAll(IEnumerable <Type> events)
        {
            foreach (var e in events)
            {
                var configuratorType = typeof(EventHandlerConfigurator <>).MakeGenericType(e);
                var configurator     = Ctor <IEventHandlerConfigurator> .Create(configuratorType);

                await configurator.Configure(_connection, _dispatcher, _logger);
            }
        }
Exemplo n.º 8
0
        public async Task SubscribeFromEventStream(HubConnection connection, bool isPersistent, IEnumerable <Type> eventTypes)
        {
            await CheckConnection(connection);

            foreach (var e in eventTypes.Where(x => !_subscribedEvents.Contains(x)))
            {
                _subscribedEvents.Add(e);
                var configuratorType = typeof(EventTypeStreamConfigurator <>).MakeGenericType(e);
                var configurator     = Ctor <IEventStreamHandlerConfigurator> .Create(configuratorType);

                await configurator.Configure(isPersistent, connection, _dispatcher, _logger);
            }
        }
        public ClassDeclarationSyntax GenerateClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, Typ)
                      .WithXmlDoc(XmlDoc.Summary($"The \"{Name}\" collection of methods."));

            using (ctx.InClass(Typ))
            {
                // TODO: validate that lower camel case is the right option here.
                var resourceString = Field(Modifier.Private | Modifier.Const, ctx.Type <string>(), "Resource")
                                     .WithInitializer(Name.ToLowerCamelCase(upperAfterDigit: null));

                var service = Field(Modifier.Private | Modifier.Readonly, ctx.Type <IClientService>(), "service")
                              .WithXmlDoc(XmlDoc.Summary("The service which this resource belongs to."));

                var subresources = Subresources.Select(subresource => (property: subresource.GenerateProperty(ctx), resource: subresource));

                var ctorParameter = Parameter(ctx.Type <IClientService>(), "service");
                var ctor          = Ctor(Modifier.Public, cls)(ctorParameter)
                                    .WithBlockBody(
                    new[] { service.AssignThisQualified(ctorParameter) }
                    .Concat(subresources.Select(pair => pair.property.Assign(New(ctx.Type(pair.resource.Typ))(ctorParameter))))
                    .ToArray()
                    )
                                    .WithXmlDoc(XmlDoc.Summary("Constructs a new resource."));

                cls = cls.AddMembers(resourceString, service, ctor);

                foreach (var subresourceProperty in subresources)
                {
                    cls = cls.AddMembers(subresourceProperty.property, subresourceProperty.resource.GenerateClass(ctx));
                }

                foreach (var method in Methods)
                {
                    cls = cls.AddMembers(method.GenerateDeclarations(ctx).ToArray());
                }
            }
            return(cls);
        }
Exemplo n.º 10
0
        public static async Task BindToSignalHub(this IEventStoreFacade connection,
                                                 IEventConverter eventConverter,
                                                 IProjectionSchemaRegister projectionSchema,
                                                 IHubContext <EventStoreHub> hubConnection, Serilog.ILogger logger)
        {
            foreach (var e in projectionSchema.Events)
            {
                var configuratorType = typeof(SignalRConfigurator <>).MakeGenericType(e);
                var configurator     = Ctor <ISignalRConfigurator> .Create(configuratorType);

                await configurator.Configure(connection, eventConverter, hubConnection, logger);
            }
        }
        public Task ConfigureServices(IServiceProvider serviceProvider)
        {
            var aggregator = serviceProvider.GetRequiredService <IEventAggregator>();
            var dispatcher = serviceProvider.GetRequiredService <ICommandDispatcher>();
            var logger     = serviceProvider.GetRequiredService <ILogger>();

            foreach (var e in _commands)
            {
                logger.Information("Invocation of {CommandName} is configured to use local command-handler.", e.Type.Name);
                var configuratorType = typeof(AggregateConfigurator <>).MakeGenericType(e.Type);
                var configurator     = Ctor <IAggregateConfigurator> .Create(configuratorType);

                configurator.Configure(aggregator, dispatcher, logger);
            }
            return(Task.CompletedTask);
        }
Exemplo n.º 12
0
        private object CreateSingleton(params object[] parameters)
        {
            // Simple lock to prevent 2 different threads from
            // trying to store a singleton at the same time
            lock (locker)
            {
                // If Instance isn't null then another thread
                // already stored an instance.
                if (Instance == null)
                {
                    Instance = Ctor.Invoke(parameters);
                }
            }

            return(Instance);
        }
        public StringOverloadConstructor(ClassGen klass, Ctor constructor, bool useBase, CodeGenerationOptions opt, CodeGeneratorContext context) :
            base(klass, constructor, useBase, opt, context)
        {
            Comments.Clear();
            Parameters.Clear();

            // TODO: This is likely incorrect but done for compat with old generator.
            // A string overload for an obsolete ctor will not be marked obsolete.
            var obsolete_attr = Attributes.OfType <ObsoleteAttr> ().FirstOrDefault();

            if (obsolete_attr != null)
            {
                Attributes.Remove(obsolete_attr);
            }

            this.AddMethodParametersStringOverloads(constructor.Parameters, opt);
        }
Exemplo n.º 14
0
        public Expression BuildExpression(TypeMapPlanBuilder builder)
        {
            if (!CanResolve)
            {
                return(null);
            }

            var ctorArgs = CtorParams.Select(p => p.CreateExpression(builder));

            ctorArgs =
                ctorArgs.Zip(Ctor.GetParameters(),
                             (exp, pi) => exp.Type == pi.ParameterType ? exp : Convert(exp, pi.ParameterType))
                .ToArray();
            var newExpr = New(Ctor, ctorArgs);

            return(newExpr);
        }
Exemplo n.º 15
0
        public ConstructorInfo GetCtor(System.Type param)
        {
            int count = 0;

            if (Ctors != null)
            {
                count = Ctors.Length;
                for (int i = 0; i < count; ++i)
                {
                    if (Ctors[i].param == param)
                    {
                        return(Ctors[i].info);
                    }
                }
            }

            var p = param;

            while (p != null)
            {
                IL.Help.OneType[0] = p;
                var ctor = type.GetConstructor(Flags, null, IL.Help.OneType, null);
                if (ctor != null)
                {
                    System.Array.Resize(ref Ctors, count + 1);
                    Ctors[count] = new Ctor()
                    {
                        param = param, info = ctor
                    };
                    return(ctor);
                }

                p = p.BaseType;
            }

            System.Array.Resize(ref Ctors, count + 1);
            Ctors[count] = new Ctor()
            {
                param = param, info = null
            };
            return(null);
        }
Exemplo n.º 16
0
        public override IEnumerable <Variable> FindVariables(IMethodVariables chain)
        {
            var parameters = Ctor.GetParameters();

            for (var i = 0; i < parameters.Length; i++)
            {
                if (Parameters[i] == null)
                {
                    var parameter = parameters[i];
                    Parameters[i] = chain.FindVariable(parameter.ParameterType);
                }
            }

            foreach (var parameter in Parameters)
            {
                yield return(parameter);
            }

            foreach (var setter in Setters)
            {
                setter.FindVariable(chain);
            }

            foreach (var setter in Setters)
            {
                yield return(setter.Variable);
            }


            if (ActivatorFrames.Any())
            {
                var standin = new StandinMethodVariables(Variable, chain);

                foreach (var frame in ActivatorFrames)
                {
                    foreach (var variable in frame.FindVariables(standin))
                    {
                        yield return(variable);
                    }
                }
            }
        }
Exemplo n.º 17
0
        public Expression BuildExpression(
            TypeMapRegistry typeMapRegistry,
            ParameterExpression srcParam,
            ParameterExpression ctxtParam)
        {
            if (!CanResolve)
            {
                return(null);
            }

            var ctorArgs = CtorParams.Select(p => p.CreateExpression(typeMapRegistry, srcParam, ctxtParam));

            ctorArgs =
                ctorArgs.Zip(Ctor.GetParameters(),
                             (exp, pi) => exp.Type == pi.ParameterType ? exp : Convert(exp, pi.ParameterType))
                .ToArray();
            var newExpr = New(Ctor, ctorArgs);

            return(newExpr);
        }
Exemplo n.º 18
0
        public static void Wire(ViewModelBase <T> vm, ICommandsCollection collection)
        {
            if (_commands == null)
            {
                var viewModelType = typeof(T);
                lock (typeof(CommandCollectionFactory <T>))
                {
                    _commands = new List <ICommandFactory <T> >();
                    var tupleType = typeof(ValueTuple <,>);

                    var methods = viewModelType
                                  .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
                                  .ToArray();

                    foreach (var m in methods.Where(m => m.ReturnType.IsGenericType && m.ReturnType.GetGenericTypeDefinition() == tupleType))
                    {
                        var args        = m.ReturnType.GetGenericArguments();
                        var keyType     = args[0];
                        var commandType = args[1];

                        if (!typeof(ICommand).IsAssignableFrom(commandType))
                        {
                            throw new InvalidViewModelStructureException($"'{commandType.FullName}' is expected to implement interface ICommand, because it was found in method '{m.Name}' of class '{typeof(T).FullName}'.");
                        }

                        var factoryType =
                            typeof(CommandFactory <, ,>).MakeGenericType(viewModelType, keyType, commandType);
                        var factory = Ctor <ICommandFactory <T> > .Create(factoryType);

                        factory.Configure(m);
                        _commands.Add(factory);
                    }
                }
            }

            foreach (var i in _commands)
            {
                var cmd = i.Create((T)vm);
                collection.Add(i.CommandName, cmd);
            }
        }
Exemplo n.º 19
0
        public void Render()
        {
            _writer.BaseStream.SetLength(0);
            _writer.BaseStream.Position = 0;

            Usings.RenderStart(_writer);
            Usings.RenderCode(_writer);
            Usings.RenderEnd(_writer);

            Namespace.RenderStart(_writer);
            Namespace.RenderCode(_writer);

            Attributes.RenderStart(_writer);
            Attributes.RenderCode(_writer);
            Attributes.RenderEnd(_writer);

            Declaration.RenderStart(_writer);
            Declaration.RenderCode(_writer);

            PrivateFieldsRegion.RenderStart(_writer);
            PrivateFieldsRegion.RenderCode(_writer);
            PrivateFieldsRegion.RenderEnd(_writer);

            Ctor.RenderStart(_writer);
            Ctor.RenderCode(_writer);
            Ctor.RenderEnd(_writer);

            PropertyRegion.RenderStart(_writer);
            PropertyRegion.RenderCode(_writer);
            PropertyRegion.RenderEnd(_writer);

            Methods.RenderStart(_writer);
            Methods.RenderCode(_writer);
            Methods.RenderEnd(_writer);

            Declaration.RenderEnd(_writer);

            Namespace.RenderEnd(_writer);

            _writer.Flush();
        }
Exemplo n.º 20
0
        //返回带参数的构造器
        public ConstructorInfo GetCtor(System.Type param)
        {
            int count = 0;

            if (null != ctors)
            {
                count = ctors.Length;
                foreach (var ctor in ctors)
                {
                    if (ctor.param == param)
                    {
                        return(ctor.info);
                    }
                }
            }

            var p = param;

            while (null != p)
            {
                Help.OneType[0] = p;
                var ctor = type.GetConstructor(Help.Flags, null, Help.OneType, null);
                if (null != ctor)
                {
                    System.Array.Resize(ref ctors, count + 1);
                    ctors[count] = new Ctor()
                    {
                        param = param, info = ctor
                    };
                    return(ctor);
                }
                p = p.BaseType;
            }

            System.Array.Resize(ref ctors, count + 1);
            ctors[count] = new Ctor()
            {
                param = param, info = null
            };
            return(null);
        }
Exemplo n.º 21
0
        public IOption <object> Create(IMap <string, object> values)
        {
            var parameters = Ctor.GetParameters().Select(p => values[p.Name]).ToArray();

            if (!parameters.IsSome)
            {
                return(Option <object> .None());
            }

            var instance = Ctor.Invoke(parameters.Value);

            foreach (var p in Dependencies.OfType <PropertyDependency>())
            {
                var propOption = values[p.Name];
                if (propOption.IsSome)
                {
                    p.SetValue(instance, propOption.Value);
                }
            }

            return(instance.Some());
        }
Exemplo n.º 22
0
        public async Task <EventEnvelope[]> Append(Guid key, Guid correlationId,
                                                   IEnumerable <IEvent> published)
        {
            var  list   = _streams.GetOrAdd(key, k => new List <EventEnvelope>());
            uint i      = 0;
            var  result = published.Select(e =>
                                           new EventEnvelope(e, _metadataFactory.Create(key, correlationId, e, 0)))
                          .ToArray();

            lock (list)
            {
                list.AddRange(result);
            }
            LogEvents(key, 0, result);
            foreach (var e in result)
            {
                var invoker = Ctor <IInvoker> .Create(typeof(Invoker <>).MakeGenericType(typeof(TAggregate), e.Event.GetType()));

                invoker.Invoke(_eventAggregator, e.Metadata, e.Event);
            }

            return(result);
        }
Exemplo n.º 23
0
        private ClassDeclarationSyntax GenerateRequestType(SourceFileContext ctx)
        {
            var baseType = ctx.Type(Typ.Generic(Package.GenericBaseRequestTypDef, ResponseTyp));
            var cls      = Class(Modifier.Public, RequestTyp, baseType);

            if (_restMethod.Description is object)
            {
                cls = cls.WithXmlDoc(XmlDoc.Summary(_restMethod.Description));
            }

            using (ctx.InClass(RequestTyp))
            {
                // Service and optionally "body"
                var             serviceParam    = Parameter(ctx.Type <IClientService>(), "service");
                ParameterSyntax bodyParam       = null;
                var             extraParameters = new List <ParameterSyntax> {
                    serviceParam
                };

                var bodyDeclarations = new MemberDeclarationSyntax[0];
                if (BodyTyp is object)
                {
                    var bodyProperty = AutoProperty(Modifier.None, ctx.Type(BodyTyp), "Body", hasSetter: true)
                                       .WithXmlDoc(XmlDoc.Summary("Gets or sets the body of this request."));
                    var bodyMethod = Method(Modifier.Protected | Modifier.Override, ctx.Type <object>(), "GetBody")()
                                     .WithBody(Return(bodyProperty))
                                     .WithXmlDoc(XmlDoc.Summary("Returns the body of the request."));
                    bodyDeclarations = new MemberDeclarationSyntax[] { bodyProperty, bodyMethod };
                    bodyParam        = Parameter(ctx.Type(BodyTyp), "body");
                    extraParameters.Add(bodyParam);
                }

                var mediaDownloaderProperty = SupportsMediaDownload
                    ? AutoProperty(Modifier.Public, ctx.Type <IMediaDownloader>(), "MediaDownloader", hasSetter: true, setterIsPrivate: true)
                                              .WithXmlDoc(XmlDoc.Summary("Gets the media downloader."))
                    : null;

                var parameters         = CreateParameterList(RequestTyp);
                var requiredParameters = parameters
                                         .TakeWhile(p => p.IsRequired)
                                         .Select(p => (param: p, decl: Parameter(ctx.Type(p.Typ), p.CodeParameterName)))
                                         .ToList();

                var assignments = requiredParameters
                                  .Select(p => Field(0, ctx.Type(p.param.Typ), p.param.PropertyName).Assign(p.decl)).ToList();

                if (BodyTyp is object)
                {
                    var bodyProperty = (PropertyDeclarationSyntax)bodyDeclarations[0];
                    assignments.Add(bodyProperty.Assign(bodyParam));
                }

                if (SupportsMediaDownload)
                {
                    assignments.Add(mediaDownloaderProperty.Assign(New(ctx.Type <MediaDownloader>())(serviceParam)));
                }

                var allCtorParameters = extraParameters.Concat(requiredParameters.Select(p => p.decl)).ToArray();

                var ctor = Ctor(Modifier.Public, cls, BaseInitializer(serviceParam))(allCtorParameters)
                           .WithXmlDoc(XmlDoc.Summary($"Constructs a new {PascalCasedName} request."))
                           .WithBlockBody(assignments.Concat <object>(new[] { InvocationExpression(IdentifierName("InitParameters")) }).ToArray());

                var methodName = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "MethodName")
                                 .WithGetBody(Name)
                                 .WithXmlDoc(XmlDoc.Summary("Gets the method name."));

                var httpMethod = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "HttpMethod")
                                 .WithGetBody(_restMethod.HttpMethod)
                                 .WithXmlDoc(XmlDoc.Summary("Gets the HTTP method."));

                var restPath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "RestPath")
                               .WithGetBody(_restMethod.Path)
                               .WithXmlDoc(XmlDoc.Summary("Gets the REST path."));

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

                // TODO: Media downloader members

                cls = cls.AddMembers(ctor);
                cls = cls.AddMembers(parameters.SelectMany(p => p.GenerateDeclarations(ctx)).ToArray());
                cls = cls.AddMembers(bodyDeclarations);
                cls = cls.AddMembers(methodName, httpMethod, restPath, initParameters);

                if (SupportsMediaDownload)
                {
                    cls = cls.AddMembers(mediaDownloaderProperty);
                    cls = AddMediaDownloadMethods(mediaDownloaderProperty, cls, ctx);
                }
            }
            return(cls);
        }
Exemplo n.º 24
0
 public StandardObjectMapping(string namingContext,
                              IEnumerable <IPropertyMapping> propertyMappings, string objectCategory, bool includeObjectCategory, IEnumerable <string> objectClass, bool includeObjectClasses)
     : base(namingContext, propertyMappings, objectCategory, includeObjectCategory, objectClass, includeObjectClasses)
 {
     _constructor = DelegateBuilder.BuildCtor <T>();
 }
Exemplo n.º 25
0
 public void NonNullCtorParameterTest()
 {
     var c = new Ctor(new object());
 }
 static void Load(this JavaConstructor ctor, Ctor gc)
 {
     ((JavaMethodBase)ctor).Load(gc);
 }
Exemplo n.º 27
0
 /// <summary>
 /// Creates a proxy that implements INotifyPropertyChanted interface
 /// </summary>
 /// <returns></returns>
 public static T Create()
 {
     return(Ctor <T> .Create(ProxyType));
 }
Exemplo n.º 28
0
        public ClassDeclarationSyntax GenerateServiceClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, ServiceTyp, ctx.Type <BaseClientService>()).WithXmlDoc(XmlDoc.Summary($"The {ClassName} Service."));

            using (ctx.InClass(cls))
            {
                var discoveryVersionTyp = Typ.Manual("Google.Apis.Discovery", "DiscoveryVersion");
                var version             = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), "Version")
                                          .WithInitializer(ApiVersion)
                                          .WithXmlDoc(XmlDoc.Summary("The API version."));
                var discoveryVersion = Field(Modifier.Public | Modifier.Static, ctx.Type(discoveryVersionTyp), "DiscoveryVersionUsed")
                                       .WithInitializer(ctx.Type(discoveryVersionTyp).Access(nameof(DiscoveryVersion.Version_1_0)))
                                       .WithXmlDoc(XmlDoc.Summary("The discovery version used to generate this service."));

                var parameterlessCtor = Ctor(Modifier.Public, cls, ThisInitializer(New(ctx.Type <BaseClientService.Initializer>())()))()
                                        .WithBody()
                                        .WithXmlDoc(XmlDoc.Summary("Constructs a new service."));

                var initializerParam = Parameter(ctx.Type <BaseClientService.Initializer>(), "initializer");

                var featuresArrayInitializer = ApiFeatures.Any()
                    ? NewArray(ctx.ArrayType(Typ.Of <string[]>()))(ApiFeatures.ToArray())
                    : NewArray(ctx.ArrayType(Typ.Of <string[]>()), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
                var features = Property(Modifier.Public | Modifier.Override, ctx.Type <IList <string> >(), "Features")
                               .WithGetBody(featuresArrayInitializer)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service supported features."));

                var nameProperty = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "Name")
                                   .WithGetBody(ApiName)
                                   .WithXmlDoc(XmlDoc.Summary("Gets the service name."));

                // Note: the following 4 properties have special handling post-generation, in terms
                // of adding the #if directives in.
                var baseUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BaseUri")
                              .WithGetBody(IdentifierName("BaseUriOverride").NullCoalesce(BaseUri))
                              .WithXmlDoc(XmlDoc.Summary("Gets the service base URI."));

                var basePath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BasePath")
                               .WithGetBody(BasePath)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service base path."));

                var batchUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchUri")
                               .WithGetBody(BatchUri)
                               .WithXmlDoc(XmlDoc.Summary("Gets the batch base URI; ", XmlDoc.C("null"), " if unspecified."));
                var batchPath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchPath")
                                .WithGetBody(BatchPath)
                                .WithXmlDoc(XmlDoc.Summary("Gets the batch base path; ", XmlDoc.C("null"), " if unspecified."));

                var resourceProperties = Resources.Select(resource => resource.GenerateProperty(ctx)).ToArray();

                var parameterizedCtor = Ctor(Modifier.Public, cls, BaseInitializer(initializerParam))(initializerParam)
                                        .WithBlockBody(resourceProperties.Zip(Resources).Select(pair => pair.First.Assign(New(ctx.Type(pair.Second.Typ))(This))).ToArray())
                                        .WithXmlDoc(
                    XmlDoc.Summary("Constructs a new service."),
                    XmlDoc.Param(initializerParam, "The service initializer."));

                cls = cls.AddMembers(version, discoveryVersion, parameterlessCtor, parameterizedCtor, features, nameProperty, baseUri, basePath, batchUri, batchPath);

                if (AuthScopes.Any())
                {
                    var scopeClass = Class(Modifier.Public, Typ.Manual(PackageName, "Scope"))
                                     .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scopes for use with the {Title}."));
                    using (ctx.InClass(scopeClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Static, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeClass = scopeClass.AddMembers(field);
                        }
                    }

                    var scopeConstantsClass = Class(Modifier.Public | Modifier.Static, Typ.Manual(PackageName, "ScopeConstants"))
                                              .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scope constants for use with the {Title}."));
                    using (ctx.InClass(scopeConstantsClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeConstantsClass = scopeConstantsClass.AddMembers(field);
                        }
                    }

                    cls = cls.AddMembers(scopeClass, scopeConstantsClass);
                }

                // TODO: Find an example of this...
                foreach (var method in Methods)
                {
                    cls = cls.AddMembers(method.GenerateDeclarations(ctx).ToArray());
                }

                cls = cls.AddMembers(resourceProperties);
            }
            return(cls);
        }
Exemplo n.º 29
0
        private IEnumerable <MemberDeclarationSyntax> GenerateUploadMembers(SourceFileContext ctx)
        {
            var uploadTyp = Typ.Nested(ctx.CurrentTyp, PascalCasedName + "MediaUpload");

            var baseTypArgument1 = BodyTyp ?? Typ.Of <string>();
            var baseTyp          = _restMethod.Response is object
                                   ?Typ.Generic(Typ.Of(typeof(ResumableUpload <,>)), baseTypArgument1, ResponseTyp)
                                       : Typ.Generic(Typ.Of(typeof(ResumableUpload <>)), baseTypArgument1);

            var uploadCls = Class(Modifier.Public, uploadTyp, ctx.Type(baseTyp))
                            .WithXmlDoc(XmlDoc.Summary($"{PascalCasedName} media upload which supports resumable upload."));

            var parameters         = CreateParameterList(uploadTyp);
            var requiredParameters = parameters
                                     .TakeWhile(p => p.IsRequired)
                                     .Select(p => (param: p, decl: Parameter(ctx.Type(p.Typ), p.CodeParameterName)))
                                     .ToList();

            var insertMethodParameters = new List <ParameterSyntax>();

            if (BodyTyp is object)
            {
                insertMethodParameters.Add(Parameter(ctx.Type(BodyTyp), "body"));
            }
            insertMethodParameters.AddRange(requiredParameters.Select(pair => pair.decl));
            var streamParam = Parameter(ctx.Type <Stream>(), "stream");

            var contentTypeParam = Parameter(ctx.Type <string>(), "contentType");

            insertMethodParameters.Add(streamParam);
            insertMethodParameters.Add(contentTypeParam);

            // This doc comment is common between the method and the constructor.
            var remarks = XmlDoc.Remarks("Considerations regarding ", streamParam, ":",
                                         XmlDoc.BulletListOfItemNodes(
                                             XmlDoc.Item("If ", streamParam, " is seekable, then the stream position will be reset to ", 0, " before reading commences. If ", streamParam, " is not seekable, then it will be read from its current position"),
                                             XmlDoc.Item("Caller is responsible for maintaining the ", streamParam, " open until the upload is completed"),
                                             XmlDoc.Item("Caller is responsible for closing the ", streamParam)));

            var methodDocComments = new List <DocumentationCommentTriviaSyntax>
            {
                XmlDoc.Summary(_restMethod.Description),
                remarks
            };

            if (BodyTyp is object)
            {
                methodDocComments.Add(XmlDoc.Param(Parameter(ctx.Type(BodyTyp), "body"), "The body of the request."));
            }

            methodDocComments.AddRange(requiredParameters.Select(pair => XmlDoc.Param(pair.decl, pair.param.Description)));
            methodDocComments.Add(XmlDoc.Param(streamParam, "The stream to upload. See remarks for further information."));
            methodDocComments.Add(XmlDoc.Param(contentTypeParam, "The content type of the stream to upload."));

            // We're taking it from the field in the parent type, but it becomes a parameter for the constructor...
            // So long as it appears as "service" we don't really mind.
            var serviceParam   = Parameter(ctx.Type <IClientService>(), "service");
            var ctorParameters = new List <ParameterSyntax> {
                serviceParam
            };

            ctorParameters.AddRange(insertMethodParameters);

            var insertMethod = Method(Modifier.Public | Modifier.Virtual, ctx.Type(uploadTyp), PascalCasedName)(insertMethodParameters.ToArray())
                               .WithBlockBody(Return(New(ctx.Type(uploadTyp))(ctorParameters)))
                               .WithXmlDoc(methodDocComments.ToArray());

            using (ctx.InClass(uploadTyp))
            {
                var baseInitializerArgs = new List <object>
                {
                    serviceParam,
                    ctx.Type <string>().Call(nameof(string.Format))("/{0}/{1}{2}", "upload", serviceParam.Access("BasePath"), _restMethod.Path),
                    _restMethod.HttpMethod,
                    streamParam,
                    contentTypeParam
                };
                var baseInitializer = BaseInitializer(baseInitializerArgs).WithAdditionalAnnotations(Annotations.LineBreakAnnotation);
                var assignments     = requiredParameters.Select(p => Field(0, ctx.Type(p.param.Typ), p.param.PropertyName).Assign(p.decl)).ToList();

                if (BodyTyp is object)
                {
                    // The Body property is in the base class.
                    var bodyProperty = Property(Modifier.Public, ctx.Type(BodyTyp), "Body");
                    assignments.Add(bodyProperty.Assign(Parameter(ctx.Type(BodyTyp), "body")));
                }

                // The parameters to the constructor are the same as for the method.
                var uploadCtor = Ctor(Modifier.Public, uploadCls, baseInitializer)(ctorParameters.ToArray())
                                 .WithBlockBody(assignments)
                                 .WithXmlDoc(XmlDoc.Summary($"Constructs a new {PascalCasedName} media upload instance."), remarks);

                uploadCls = uploadCls.AddMembers(Package.CreateParameterList(uploadTyp).SelectMany(p => p.GenerateDeclarations(ctx)).ToArray());
                uploadCls = uploadCls.AddMembers(parameters.SelectMany(p => p.GenerateDeclarations(ctx)).ToArray());
                uploadCls = uploadCls.AddMembers(uploadCtor);
            }

            yield return(insertMethod);

            yield return(uploadCls);
        }
Exemplo n.º 30
0
        protected override void InnerSetValue(object obj, object value)
        {
            object oo = Ctor.Invoke(new object[] { Convert.ToBoolean(value) });

            MemberInfo.SetValue(obj, oo);
        }