Пример #1
0
        public TelegramClient(string phoneNumber, ITelegramPersist persist)
        {
            _phoneNumber = phoneNumber;

            try
            {
                var schema = new ApiSchema();

                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(Shemas.Schema)))
                    schema.Load(ms);
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(Shemas.SchemaMtProto)))
                    schema.Load(ms);
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(Shemas.SchemaEndToEnd)))
                    schema.Load(ms);

                _provider             = new Provider(schema, Address, Port, phoneNumber.Replace("+", ""), persist);
                _provider.Updates    += OnUpdate;
                _provider.Difference += OnDifference;
            }
            catch (TlException)
            {
                throw;
            }
            catch (Exception e)
            {
                e = e is AggregateException ? e.InnerException : e;
                throw new TlException(e);
            }
        }
        public void Register(ApiSchema schema)
        {
            // Queries
            schema.Query.AddQuery <TestMap, IdInput>(GetTest);

            //Mutations
        }
Пример #3
0
        public void SetUp()
        {
            SerializerSettings = new JsonSerializerSettings()
            {
                TypeNameHandling      = TypeNameHandling.None,
                Formatting            = Formatting.Indented,
                ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            SerializerSettings.Converters.Add(new StringEnumConverter());
            Container        = new GraphQLContainer();
            Data             = new Data();
            AuthorizationMap = new AuthorizationMap()
            {
                AllowMissingAuthorizations = true
            };

            Container.Register <IContainer>(() => Container);
            Container.Register(() => Data);
            Container.Register(() => AuthorizationMap);
            Container.Register <AllOperations>();
            Container.Verify();

            Executer = new DocumentExecuter();
            Schema   = new ApiSchema(Container, Assembly.GetExecutingAssembly(), typeof(AllOperations).Assembly);
        }
Пример #4
0
    private NamespaceDeclarationSyntax GenerateCodeForEnum(
        ref CompilationUnitSyntax compilationUnit)
    {
        IsEnum = true;

        // Create a namespace
        var @namespace = SyntaxProjectFactory.CreateNamespace(
            ApiProjectOptions,
            NameConstants.Contracts);

        var apiEnumSchema = ApiSchema.GetEnumSchema();

        // Create an enum
        var enumDeclaration = SyntaxEnumFactory.Create(apiEnumSchema.Item1.EnsureFirstCharacterToUpper(), apiEnumSchema.Item2);

        if (enumDeclaration.HasAttributeOfAttributeType(typeof(FlagsAttribute)))
        {
            // Add using statement to compilationUnit
            compilationUnit = compilationUnit.AddUsingStatements(new[] { "System" });
        }

        if (enumDeclaration.HasAttributeOfAttributeType(typeof(SuppressMessageAttribute)))
        {
            // Add using statement to compilationUnit
            compilationUnit = compilationUnit.AddUsingStatements(new[] { "System.Diagnostics.CodeAnalysis" });
        }

        // Add the enum to the namespace.
        @namespace = @namespace.AddMembers(enumDeclaration);
        return(@namespace);
    }
Пример #5
0
 public CoinMarketCapClient(ApiSchema apischema, string apikey)
 {
     if (string.IsNullOrEmpty(apikey))
     {
         throw new CoinMarketCapException("Wrong API key");
     }
     this.apikey = apikey;
     baseurl     = $"https://{(apischema == ApiSchema.Pro ? "pro" : "sandbox")}-api.coinmarketcap.com/v1/";
 }
Пример #6
0
        public void Register(ApiSchema schema)
        {
            // Queries
            schema.Query.AddQuery <HumanObject, IdInput>(GetHuman);
            schema.Query.AddQuery <DroidObject, IdInput>(GetDroid);
            schema.Query.AddQuery <Character, IdInput>(GetHero);
            schema.Query.AddQuery <ListGraphType <Character>, SearchHeroesInput>(SearchHeroes);

            //Mutations
            schema.Mutation.AddQuery <HumanObject, CreateHumanInput>(CreateHuman);
        }
Пример #7
0
        public Provider(ApiSchema schema, string address, int port, string phone, ITelegramPersist persist)
        {
            _address   = address;
            _port      = port;
            _phone     = phone;
            _persist   = persist;
            _formatter = new Formatter();
            Combinator.Setup(schema, _formatter);

            _settings = LoadSettings();

            _connection = new TcpConnection(_address, _port, _formatter);
        }
Пример #8
0
        protected void Application_Start()
        {
            var container = new GraphQLContainer();

            container.Options.AllowOverridingRegistrations = false;
            container.Options.DefaultScopedLifestyle       = new AsyncScopedLifestyle();
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Register <IContainer>(() => container);
            var data = new Data();

            container.Register <Data>(() => data);
            var authorizationMap = new AuthorizationMap()
            {
                AllowMissingAuthorizations = true
            };

            container.Register <AuthorizationMap>(() => authorizationMap);
            container.Register <ILegoOperation, LegoOperation>();

            //Graph Schema
            container.RegisterSingleton <ApiSchema>(() =>
            {
                var apiSchema = new ApiSchema(container);

                apiSchema.MapOperation <LegoOperation>();

                apiSchema.Lock();
                return(apiSchema);
            });
            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
            GlobalConfiguration.Configuration.EnsureInitialized();

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings()
            {
                TypeNameHandling      = TypeNameHandling.None,
                Formatting            = Formatting.Indented,
                ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
        }
Пример #9
0
    public bool GenerateCode()
    {
        // Create compilationUnit
        var compilationUnit = SyntaxFactory.CompilationUnit();

        NamespaceDeclarationSyntax @namespace;

        if (ApiSchema.IsSchemaEnumOrPropertyEnum())
        {
            @namespace = GenerateCodeForEnum(ref compilationUnit);
        }
        else
        {
            @namespace = GenerateCodeForOtherThanEnum(ref compilationUnit);
        }

        // Add namespace to compilationUnit
        compilationUnit = compilationUnit !.AddMembers(@namespace);

        // Set code property
        Code = compilationUnit;
        return(true);
    }
Пример #10
0
 public void Register(ApiSchema schema)
 {
     schema.Query.AddQuery <RobotOutput, IdInput>(GetRobot);
 }
        public void Register(ApiSchema schema)
        {
            var methods = typeof(TInterface).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);

            foreach (var methodInfo in methods)
            {
                if (methodInfo.Name == nameof(IOperation.Register))
                {
                    continue;
                }

                var isQuery    = methodInfo.CustomAttributes.Any(a => a.AttributeType == typeof(QueryAttribute));
                var isMutation = methodInfo.CustomAttributes.Any(a => a.AttributeType == typeof(MutationAttribute));
                if (!isQuery && !isMutation)
                {
                    isQuery = true;
                }

                var apiOperation = isQuery ? schema.Query : schema.Mutation;
                var parameters   = methodInfo.GetParameters();
                if (parameters.Length != 1)
                {
                    throw new GraphException($"An operation method must have one input parameter. Operation: {typeof(TInterface).Name}.{methodInfo.Name}");
                }
                var fieldName        = methodInfo.Name.ToCamelCase();
                var fieldDescription = "";
                var queryArguments   = GraphArguments.FromModel(parameters[0].ParameterType).GetQueryArguments();
                // Add function as operation
                var returnType = TypeLoader.GetBaseType(methodInfo.ReturnType, out bool isList);
                schema.MapOutput(returnType, autoMapChildren: true, overwriteMap: false);
                var graphType = TypeLoader.GetGraphType(methodInfo.ReturnType);
                apiOperation.Field(graphType, fieldName, fieldDescription, queryArguments, context =>
                {
                    var inputModel = ApiOperation.GetInputFromContext(context, parameters[0].ParameterType);
                    ValidationError.ValidateObject(inputModel);
                    var operationValues = new OperationValues()
                    {
                        Context            = context,
                        FieldName          = fieldName,
                        Fields             = new InputField[0],
                        FunctionAttributes = methodInfo.GetCustomAttributes(true).OfType <Attribute>().ToArray(),
                        Input = inputModel,
                    };
                    operationValues = schema.Container.GetInstance <ApiSchema>().RunOperationFilters(OperationFilterType.Pre, operationValues);

                    var graphClient = GetGraphClient();
                    var query       = graphClient.AddSelectionQuery(fieldName, inputModel, context.FieldAst.SelectionSet.Selections.OfType <Field>());
                    var graphOutput = isQuery ? graphClient.RunQueries() : graphClient.RunMutations();
                    if (graphOutput.HasErrors)
                    {
                        graphOutput.ThrowErrors();
                    }
                    operationValues.Output = query.Data.ToObject(methodInfo.ReturnType);
                    if (PostOperations.ContainsKey(fieldName))
                    {
                        operationValues.Output = PostOperations[fieldName](context, fieldName, operationValues.Output);
                    }
                    operationValues = schema.Container.GetInstance <ApiSchema>().RunOperationFilters(OperationFilterType.Post, operationValues);
                    return(operationValues.Output);
                });
            }
        }
Пример #12
0
 public static void Setup(ApiSchema schema, IFormatter <byte[]> formatter)
 {
     _schema    = schema;
     _formatter = formatter;
 }
Пример #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Client"/> class.
 /// </summary>
 /// <param name="apiSchema">The apiSchema<see cref="ApiSchema"/></param>
 public Client(ApiSchema apiSchema)
 {
     this.apiSchema = apiSchema;
 }
Пример #14
0
        protected void Application_Start()
        {
            var container = new GraphQLContainer();

            container.Options.AllowOverridingRegistrations = false;
            container.Options.DefaultScopedLifestyle       = new AsyncScopedLifestyle();
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Register <IContainer>(() => container);
            var data = new Data();

            container.Register <Data>(() => data);
            var authorizationMap = new AuthorizationMap()
            {
                AllowMissingAuthorizations = true
            };

            container.Register <AuthorizationMap>(() => authorizationMap);

            //Graph Schema
            container.Register <ResolverInfoManager>(Lifestyle.Scoped);
            container.RegisterSingleton <ApiSchema>(() =>
            {
                var apiSchema = new ApiSchema(container);
                apiSchema.AddPropertyFilter <string>((context, propertyInfo, name, value) =>
                {
                    Debug.WriteLine($"PropertyFilter for {name}");
                    return(value);
                });
                apiSchema.AddPropertyFilter <Uri>((context, propertyInfo, name, value) =>
                {
                    Debug.WriteLine($"Replacing host for Uri {value}");
                    var builder = new UriBuilder(value)
                    {
                        Host = "www.replacement.com"
                    };
                    return(builder.Uri);
                });
                apiSchema.AddPropertyFilter((context, propertyInfo, name, value) =>
                {
                    Debug.WriteLine($"Generic property filter");
                    return(value);
                });

                // map a type with a type mapping
                //apiSchema.MapOutput<Lego, LegoMap>();
                apiSchema.MapAssemblies(Assembly.GetAssembly(typeof(HumanObject)));

                // map a type without GraphObject implementation
                //apiSchema.MapOutput<Robot, Output.RobotOutput>();
                apiSchema.MapOutput <RobotOutput>(autoMapChildren: true, overwriteMap: true);

                // map an operation without IOperation implementation
                var proxy = apiSchema.Proxy <ILegoOperation>(() => new GraphClient("http://localhost:51365/api", new HttpClient()));
                //proxy.AddPostOperation(nameof(ILegoOperation.Lego), (context, name, value) =>
                //{
                //    Debug.WriteLine($"PostOperation for {name}");
                //    return value;
                //});
                proxy.AddPostOperation(i => nameof(i.Lego), (context, name, value) =>
                {
                    Debug.WriteLine($"PostOperation for {name}");
                    return(value);
                });
                apiSchema.Lock();
                return(apiSchema);
            });
            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
            GlobalConfiguration.Configuration.EnsureInitialized();

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings()
            {
                TypeNameHandling      = TypeNameHandling.None,
                Formatting            = Formatting.Indented,
                ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
        }
Пример #15
0
    private NamespaceDeclarationSyntax GenerateCodeForOtherThanEnum(
        ref CompilationUnitSyntax?compilationUnit)
    {
        // Create a namespace
        var @namespace = IsSharedContract
            ? SyntaxProjectFactory.CreateNamespace(ApiProjectOptions, NameConstants.Contracts)
            : SyntaxProjectFactory.CreateNamespace(ApiProjectOptions, NameConstants.Contracts, FocusOnSegmentName);

        // Create class
        var classDeclaration = SyntaxClassDeclarationFactory.Create(ApiSchemaKey.EnsureFirstCharacterToUpper())
                               .AddGeneratedCodeAttribute(ApiProjectOptions.ToolName, ApiProjectOptions.ToolVersion.ToString())
                               .WithLeadingTrivia(SyntaxDocumentationFactory.Create(ApiSchema));

        var hasAnyPropertiesAsArrayWithFormatTypeBinary = ApiSchema.HasAnyPropertiesAsArrayWithFormatTypeBinary();

        // Create class-properties and add to class
        if (ApiSchema.Properties is not null)
        {
            if (ApiSchema.IsTypeArray() ||
                hasAnyPropertiesAsArrayWithFormatTypeBinary)
            {
                var(key, _) = ApiProjectOptions.Document.Components.Schemas.FirstOrDefault(x =>
                                                                                           x.Key.Equals(ApiSchema.Title, StringComparison.OrdinalIgnoreCase));
                if (string.IsNullOrEmpty(ApiSchema.Title))
                {
                    ApiSchema.Title = ApiSchemaKey;
                    key             = ApiSchemaKey;
                }

                if (ApiSchema.Items is not null &&
                    string.IsNullOrEmpty(ApiSchema.Items.Title))
                {
                    ApiSchema.Items.Title = ApiSchemaKey;
                }

                var title = key is not null
                    ? $"{ApiSchema.Title.EnsureFirstCharacterToUpperAndSingular()}List"
                    : ApiSchema.Title.EnsureFirstCharacterToUpper();

                var propertyDeclaration = hasAnyPropertiesAsArrayWithFormatTypeBinary
                    ? SyntaxPropertyDeclarationFactory.CreateListAuto("IFormFile", ApiSchema.ExtractPropertyNameWhenHasAnyPropertiesOfArrayWithFormatTypeBinary())
                                          .WithLeadingTrivia(
                    SyntaxDocumentationFactory.CreateSummary("A list of File(s)."))
                    : SyntaxPropertyDeclarationFactory.CreateListAuto(ApiSchema.Items !.Title, title)
                                          .WithLeadingTrivia(
                    SyntaxDocumentationFactory.CreateSummary($"A list of {ApiSchema.Items.Title}."));

                classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
            }
            else
            {
                foreach (var property in ApiSchema.Properties)
                {
                    var propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateAuto(
                        property,
                        ApiSchema.Required,
                        ApiProjectOptions.UseNullableReferenceTypes)
                                              .WithLeadingTrivia(SyntaxDocumentationFactory.Create(property.Value));
                    classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
                }
            }

            var methodDeclaration = SyntaxMethodDeclarationFactory.CreateToStringMethod(ApiSchema.Properties);
            if (methodDeclaration is not null)
            {
                methodDeclaration = methodDeclaration.WithLeadingTrivia(SyntaxDocumentationFactory.CreateForOverrideToString());
                classDeclaration  = classDeclaration.AddMembers(methodDeclaration);
            }
        }

        // Add using statement to compilationUnit
        compilationUnit = compilationUnit !.AddUsingStatements(ProjectApiFactory.CreateUsingListForContractModel(ApiSchema));

        // Add the class to the namespace.
        @namespace = @namespace.AddMembers(classDeclaration);
        return(@namespace);
    }
Пример #16
0
        public bool GenerateCode()
        {
            // Create compilationUnit
            var compilationUnit = SyntaxFactory.CompilationUnit();

            NamespaceDeclarationSyntax @namespace;

            if (ApiSchema.IsSchemaEnumOrPropertyEnum())
            {
                IsEnum = true;

                // Create a namespace
                @namespace = SyntaxProjectFactory.CreateNamespace(
                    ApiProjectOptions,
                    NameConstants.Contracts);

                var apiEnumSchema = ApiSchema.GetEnumSchema();

                // Create an enum
                var enumDeclaration = SyntaxEnumFactory.Create(apiEnumSchema.Item1.EnsureFirstCharacterToUpper(), apiEnumSchema.Item2);

                if (enumDeclaration.HasAttributeOfAttributeType(typeof(FlagsAttribute)))
                {
                    // Add using statement to compilationUnit
                    compilationUnit = compilationUnit.AddUsingStatements(new[] { "System" });
                }

                if (enumDeclaration.HasAttributeOfAttributeType(typeof(SuppressMessageAttribute)))
                {
                    // Add using statement to compilationUnit
                    compilationUnit = compilationUnit.AddUsingStatements(new[] { "System.Diagnostics.CodeAnalysis" });
                }

                // Add the enum to the namespace.
                @namespace = @namespace.AddMembers(enumDeclaration);
            }
            else
            {
                // Create a namespace
                @namespace = IsSharedContract
                    ? SyntaxProjectFactory.CreateNamespace(ApiProjectOptions, NameConstants.Contracts)
                    : SyntaxProjectFactory.CreateNamespace(ApiProjectOptions, NameConstants.Contracts, FocusOnSegmentName);

                // Create class
                var classDeclaration = SyntaxClassDeclarationFactory.Create(ApiSchemaKey.EnsureFirstCharacterToUpper())
                                       .AddGeneratedCodeAttribute(ApiProjectOptions.ToolName, ApiProjectOptions.ToolVersion.ToString())
                                       .WithLeadingTrivia(SyntaxDocumentationFactory.Create(ApiSchema));

                // Create class-properties and add to class
                if (ApiSchema.Properties != null)
                {
                    if (ApiSchema.Type == OpenApiDataTypeConstants.Array)
                    {
                        var(key, _) = ApiProjectOptions.Document.Components.Schemas.FirstOrDefault(x => x.Key.Equals(ApiSchema.Title, StringComparison.OrdinalIgnoreCase));
                        if (string.IsNullOrEmpty(ApiSchema.Title))
                        {
                            ApiSchema.Title = ApiSchemaKey;
                            key             = ApiSchemaKey;
                        }

                        if (string.IsNullOrEmpty(ApiSchema.Items.Title))
                        {
                            ApiSchema.Items.Title = ApiSchemaKey;
                        }

                        var title = key != null
                            ? $"{ApiSchema.Title.EnsureFirstCharacterToUpperAndSingular()}List"
                            : ApiSchema.Title.EnsureFirstCharacterToUpper();

                        var propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateListAuto(ApiSchema.Items.Title, title)
                                                  .WithLeadingTrivia(SyntaxDocumentationFactory.CreateSummary($"A list of {ApiSchema.Items.Title}."));
                        classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
                    }
                    else
                    {
                        foreach (var property in ApiSchema.Properties)
                        {
                            var propertyDeclaration = SyntaxPropertyDeclarationFactory.CreateAuto(
                                property,
                                ApiSchema.Required,
                                ApiProjectOptions.ApiOptions.Generator.UseNullableReferenceTypes)
                                                      .WithLeadingTrivia(SyntaxDocumentationFactory.Create(property.Value));
                            classDeclaration = classDeclaration.AddMembers(propertyDeclaration);
                        }
                    }

                    var methodDeclaration = SyntaxMethodDeclarationFactory.CreateToStringMethod(ApiSchema.Properties);
                    if (methodDeclaration != null)
                    {
                        methodDeclaration = methodDeclaration.WithLeadingTrivia(SyntaxDocumentationFactory.CreateForOverrideToString());
                        classDeclaration  = classDeclaration.AddMembers(methodDeclaration);
                    }
                }

                // Add using statement to compilationUnit
                compilationUnit = compilationUnit.AddUsingStatements(ProjectContractDataFactory.CreateUsingList(ApiSchema));

                // Add the class to the namespace.
                @namespace = @namespace.AddMembers(classDeclaration);
            }

            // Add namespace to compilationUnit
            compilationUnit = compilationUnit.AddMembers(@namespace);

            // Set code property
            Code = compilationUnit;
            return(true);
        }
Пример #17
0
 public void Register(ApiSchema schema)
 {
     schema.Query.AddQuery <Lego, IdInput>(Lego);
 }