Interaction logic for ApiConfiguration
Exemplo n.º 1
0
 public void NewApiContextIsConfiguredCorrectly()
 {
     var configuration = new ApiConfiguration();
     configuration.EnsureCommitted();
     var context = new ApiContext(configuration);
     Assert.Same(configuration, context.Configuration);
 }
Exemplo n.º 2
0
 public override void Configure(
     ApiConfiguration configuration,
     Type type)
 {
     base.Configure(configuration, type);
     Assert.Same(typeof(TestApiWithParticipants), type);
     configuration.SetProperty(this.Value, true);
 }
 /// <inheritdoc/>
 public static void ApplyTo(
     ApiConfiguration configuration,
     Type targetType)
 {
     Ensure.NotNull(configuration, "configuration");
     Ensure.NotNull(targetType, "targetType");
     configuration.AddHookHandler<IQueryExpressionFilter>(new ConventionBasedEntitySetFilter(targetType));
 }
 /// <inheritdoc/>
 public static void ApplyTo(
     ApiConfiguration configuration,
     Type targetType)
 {
     Ensure.NotNull(configuration, "configuration");
     Ensure.NotNull(targetType, "targetType");
     configuration.AddHookHandler<IChangeSetEntryAuthorizer>(new ConventionBasedChangeSetAuthorizer(targetType));
 }
Exemplo n.º 5
0
 public void InvocationContextGetsHookPointsCorrectly()
 {
     var hook = new HookA();
     var configuration = new ApiConfiguration().AddHookHandler<IHookA>(hook);
     configuration.EnsureCommitted();
     var apiContext = new ApiContext(configuration);
     var context = new InvocationContext(apiContext);
     Assert.Same(hook, context.GetHookHandler<IHookA>());
 }
Exemplo n.º 6
0
        public static void Initialize()
        {
            var routes = RouteTable.Routes;

            var config = new ApiConfiguration(Bootstrapper.CompositionRoot)
            {
                EnableTestClient = true
            };

            var odataFormatter = new ODataMediaTypeFormatter();
            odataFormatter.SupportedMediaTypes.Clear();
            odataFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/atom+xml"));

            config.Formatters.Clear();
            config.Formatters.Insert(0, odataFormatter);
            routes.SetDefaultHttpConfiguration(config);

            routes.MapServiceRoute<ProjectsApi>("api/projects");
        }
Exemplo n.º 7
0
 public Util(IOptions <ApiConfiguration> apiConfiguration)
 {
     _apiConfiguration = apiConfiguration.Value;
 }
Exemplo n.º 8
0
        private static Task<IEdmModel>[] PrepareThreads(int count, ApiConfiguration configuration, ManualResetEventSlim wait)
        {
            var tasks = new Task<IEdmModel>[count];
            var result = Parallel.For(0, count, (inx, state) =>
            {
                var source = new TaskCompletionSource<IEdmModel>();
                new Thread(() =>
                {
                    // To make threads better aligned.
                    wait.Wait();

                    var context = new ApiContext(configuration);
                    try
                    {
                        var model = context.GetModelAsync().Result;
                        source.SetResult(model);
                    }
                    catch (Exception e)
                    {
                        source.SetException(e);
                    }
                }).Start();
                tasks[inx] = source.Task;
            });

            Assert.True(result.IsCompleted);
            return tasks;
        }
Exemplo n.º 9
0
 public WorldOfWarcraftApi(ApiConfiguration configuration)
 {
     reader = new ApiReader(configuration);
 }
        public static IServiceCollection AddTeamPanelApi(this IServiceCollection services, ApiConfiguration apiConfiguration)
        {
            services.AddScoped <IActivitiesClient>(
                factory => {
                IActivitiesClient activitiesClient = new ActivitiesClient(apiConfiguration);

                return(activitiesClient);
            }
                );
            return(services);
        }
Exemplo n.º 11
0
 public DiabloApi(ApiConfiguration configuration)
 {
     reader = new ApiReader(configuration);
 }
Exemplo n.º 12
0
 public OAuthProvider(ApiConfiguration configuration) : base(configuration)
 {
     OAuthAuthorizationServerProvider = new GrantProvider(Configuration);
     RefreshTokenProvider             = new RefreshTokenProvider(Configuration);
 }
Exemplo n.º 13
0
 public HomeController(ILogger <HomeController> logger, IOptions <ApiConfiguration> apiConfiguration)
 {
     _logger           = logger;
     _apiConfiguration = apiConfiguration.Value;
     loginService      = new LoginService(_apiConfiguration.ApiUsersUrl);;
 }
Exemplo n.º 14
0
 public ChatClient(IApi api, ApiConfiguration configuration)
 {
     this.Api           = api;
     this.configuration = configuration;
     StartSenderWorker();
 }
 public WebStoreClient(ApiConfiguration payConfiguration) : base(payConfiguration)
 {
 }
Exemplo n.º 16
0
 public TokenService(ApiConfiguration apiConfiguration)
 {
     _apiConfiguration = apiConfiguration;
 }
Exemplo n.º 17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory)
        {
            app.UseStaticFiles();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            ConfigurationService configurationService = ConfigurationService.Instance;

            configurationService.LoadConfiguration(hostingEnvironment.ContentRootPath);

            ApiConfiguration apiConfiguration = configurationService.ApiConfiguration;

            if (apiConfiguration.ExtractConfigurationFromDatabase)
            {
                DatabaseAnalyzer databaseAnalyzer = new DatabaseAnalyzer();

                databaseAnalyzer.ExtractConfigurationFromDatabase();

                // reload the configuration to include the newly created route configuration
                configurationService.LoadConfiguration(hostingEnvironment.ContentRootPath);

                apiConfiguration = configurationService.ApiConfiguration;
            }

            app.UseMvc(routes =>
            {
                Tavis.OpenApi.Model.OpenApiDocument openApiDocument = new Tavis.OpenApi.Model.OpenApiDocument();
                openApiDocument.Info             = new Tavis.OpenApi.Model.Info();
                openApiDocument.Info.Title       = apiConfiguration.Title;
                openApiDocument.Info.Description = apiConfiguration.Description;

                foreach (RouteConfiguration route in apiConfiguration.Routes)
                {
                    // set the route configuration prefix or use the default
                    string routePrefix = route.Prefix;
                    if (String.IsNullOrEmpty(routePrefix))
                    {
                        routePrefix = apiConfiguration.DefaultRoute.Prefix;
                    }

                    string resourceUri = routePrefix + "/";
                    if (!String.IsNullOrEmpty(route.Resource))
                    {
                        resourceUri += route.Resource;
                    }
                    else
                    {
                        resourceUri += route.Table;
                    }

                    // set the route configuration controller or use the default
                    string routeController = route.Controller;
                    if (String.IsNullOrEmpty(routeController))
                    {
                        routeController = apiConfiguration.DefaultRoute.Controller;
                    }

                    // set the route configuration actions or use the default actions
                    List <ActionConfiguration> routeActionConfigurations;
                    if (route.Actions.Any())
                    {
                        routeActionConfigurations = route.Actions;
                    }
                    else
                    {
                        routeActionConfigurations = apiConfiguration.DefaultRoute.Actions;
                    }

                    foreach (ActionConfiguration action in routeActionConfigurations)
                    {
                        string name     = Guid.NewGuid().ToString();
                        string template = resourceUri;
                        if (!String.IsNullOrEmpty(action.Template))
                        {
                            template += action.Template;
                        }

                        object defaults    = new { controller = routeController, action = action.Name };
                        object constraints = null;
                        object dataTokens  = new { apiConfiguration = configurationService.ApiConfiguration, routeConfiguration = route, actionConfiguration = action };

                        routes.MapRoute(
                            name: name,
                            template: template,
                            defaults: defaults,
                            constraints: constraints,
                            dataTokens: dataTokens
                            );


                        // add the route action as an operation to the OpenAPI definition
                        Tavis.OpenApi.Model.Operation operation = new Tavis.OpenApi.Model.Operation();
                        operation.Tags = new List <Tavis.OpenApi.Model.Tag>();
                        operation.Tags.Add(new Tavis.OpenApi.Model.Tag()
                        {
                            Name = resourceUri
                        });
                        operation.OperationId = name;
                        operation.Responses   = new Dictionary <string, Tavis.OpenApi.Model.Response>();
                        operation.Responses.Add("200", new Tavis.OpenApi.Model.Response()
                        {
                            Description = "Success"
                        });

                        // define one Path for every template
                        // with multiple operations for every HTTP method under those templates
                        Tavis.OpenApi.Model.PathItem pathItem = null;
                        try
                        {
                            pathItem = openApiDocument.Paths.GetPath(template);
                        }
                        catch
                        {
                            // the path does not yet exist in the OpenAPIDocument
                            // so we create a new path
                            pathItem = new Tavis.OpenApi.Model.PathItem();
                            openApiDocument.Paths.AddPathItem(template, pathItem);
                        }

                        pathItem.AddOperation(action.HttpMethod.ToLower(), operation);
                    }
                }

                // write the OpenAPI definition to the file
                string swaggerJsonFilePath = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot", "swagger.json");

                using (FileStream fileStream = new FileStream(swaggerJsonFilePath, FileMode.Create))
                {
                    Func <Stream, IParseNodeWriter> jsonWriterFactory = s => new JsonParseNodeWriter(s);

                    OpenApiV2Writer writer = new OpenApiV2Writer(jsonWriterFactory);

                    writer.Write(fileStream, openApiDocument);

                    fileStream.Close();
                }
            });


            // enable Swagger UI
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger.json", "freaqs awesome new api");
            });
        }
Exemplo n.º 18
0
        public IEnumerable <(string, string, string)> GetHeartbeats(IEnumerable <IEnumerable <BidEntry> > orders, ApiConfiguration config, IEnumerable <ConditionSetting> settings)
        {
            var heartbeats = new List <(string, string, string)>();

            // Conditions are in order of priority
            var conditions = Registry.GetHeartbeats();

            foreach (var conditionEntry in conditions)
            {
                if (this.IsEnabled(settings, conditionEntry.Name))
                {
                    IHeartbeat condition = (IHeartbeat)Activator.CreateInstance(conditionEntry, args: _serviceProvider);
                    if (conditionEntry.IsDefined(typeof(GlobalConditionAttribute), false))
                    {
                        heartbeats.Add(condition.Status(orders.SelectMany(o => o), config));
                    }
                    else
                    {
                        foreach (var order in orders)
                        {
                            heartbeats.Add(condition.Status(order, config));
                        }
                    }
                }
            }

            return(heartbeats);
        }
Exemplo n.º 19
0
        public IEnumerable <AlertDTO> Check(IEnumerable <IEnumerable <BidEntry> > orders, ApiConfiguration config, IEnumerable <ConditionSetting> settings)
        {
            var foundOrders    = new List <AlertDTO>();
            var foundOrdersIDs = new HashSet <string>();

            // Conditions are in order of priority
            var conditions = Registry.GetConditions().OrderBy(Registry.GetPriority).ToList();

            foreach (var conditionEntry in conditions)
            {
                if (this.IsEnabled(settings, conditionEntry.Name))
                {
                    var        data      = new List <AlertDTO>();
                    ICondition condition = (ICondition)Activator.CreateInstance(conditionEntry, args: _serviceProvider);
                    if (conditionEntry.IsDefined(typeof(GlobalConditionAttribute), false))
                    {
                        data = condition.Compute(orders.SelectMany(o => o), config).ToList();
                    }
                    else
                    {
                        foreach (var order in orders)
                        {
                            data.AddRange(condition.Compute(order, config));
                        }
                    }

                    foreach (var alert in data)
                    {
                        // Avoid duplicate alerts
                        var sig = $"{alert.BidEntry.NiceHashId}{alert.BidEntry.NiceHashDataCenter}";
                        if (!foundOrdersIDs.Contains(sig))
                        {
                            foundOrdersIDs.Add(sig);
                            foundOrders.Add(alert);
                        }
                    }
                }
            }

            return(foundOrders);
        }
Exemplo n.º 20
0
 public Startup(IConfiguration configuration)
 {
     apiConfiguration = configuration
                        .GetSection(ApiConfiguration.SectionName)
                        .Get <ApiConfiguration>();
 }
Exemplo n.º 21
0
 protected ApiConfiguration(ApiConfiguration configuration)
 {
     Host   = configuration.Host;
     Port   = configuration.Port;
     Scheme = configuration.Scheme;
 }
 public List <Tournament> Get()
 {
     return(ApiConfiguration.Load().Tournaments);
 }
 public TesouroDiretoRepository(ILoggerFactory loggerFactory, ApiConfiguration apiConfiguration) : base(loggerFactory.CreateLogger <BaseHttpClient>(), apiConfiguration.TesouroDiretoPath, useCompression: false, timeOut: 30)
 {
 }
Exemplo n.º 24
0
 public void InitService(ApiConfiguration myConfiguration, OAuthKeyService myOAuthKeyService)
 {
     _myService         = new AccountService(myConfiguration, null, myOAuthKeyService);
     items              = new List <Account>();
     _myCustomerService = new CustomerService(myConfiguration, null, myOAuthKeyService);
 }
Exemplo n.º 25
0
 public PersonGateway(ApiConfiguration configuration, IHttpClientHelper httpClientHelper)
 {
     _configuration    = configuration;
     _httpClientHelper = httpClientHelper;
 }
Exemplo n.º 26
0
 public GoogleMaps(ApiConfiguration configuration)
 {
     this.configuration = configuration;
 }
Exemplo n.º 27
0
 public void OverrideConfiguration(ApiConfiguration newConfiguration)
 {
     reader.Configuration = newConfiguration;
 }
Exemplo n.º 28
0
 public SlimApiActionSelector(ApiConfiguration apiConfiguration)
 {
     _apiConfig = apiConfiguration;
 }
Exemplo n.º 29
0
 public CarsController(IMapper mapper, ApiConfiguration apiConfiguration, ILogger <CarsController> logger)
 {
     Mapper           = mapper;
     ApiConfiguration = apiConfiguration;
     Logger           = logger;
 }
Exemplo n.º 30
0
 public static Settings ParseConfigurationToLibrarySettings(ApiConfiguration apiConfiguration)
 {
     return(new Settings {
         ClientsUrl = apiConfiguration.ClientsUrl, PoliciesUrl = apiConfiguration.PoliciesUrl
     });
 }
Exemplo n.º 31
0
 public void ApiContextOnlyAcceptsCommittedConfiguration()
 {
     var configuration = new ApiConfiguration();
     Assert.Throws<ArgumentException>(() => new ApiContext(configuration));
 }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            // Relative or absolute path to the *.p12-file containing the test certificate used to sign tokens for Maskinporten
            var p12Filename = Environment.GetEnvironmentVariable("P12FILENAME");

            // Password required to use the certificate
            var p12Password = Environment.GetEnvironmentVariable("P12PWD");

            // The issuer as defined in Maskinporten
            var issuer = Environment.GetEnvironmentVariable("MASKINPORTEN_ISSUER");

            // ID-porten machine to machine configuration
            var maskinportenConfig = new MaskinportenClientConfiguration(
                audience: @"https://ver2.maskinporten.no/",           // ID-porten audience path
                tokenEndpoint: @"https://ver2.maskinporten.no/token", // ID-porten token path
                issuer: issuer,                                       // KS issuer name
                numberOfSecondsLeftBeforeExpire: 10,                  // The token will be refreshed 10 seconds before it expires
                certificate: new X509Certificate2(p12Filename, p12Password));

            // accountId as defined in the Fiks Forvaltning Interface
            var fiksIoAccountId = Environment.GetEnvironmentVariable("FIKS_IO_ACCOUNT_ID");
            // private key corresponding to the public key uploaded in the Fiks Forvaltning Interface
            var fiksIoPrivateKeyPath = Environment.GetEnvironmentVariable("FIKS_IO_PRIVATE_KEY_PATH");

            // Fiks IO account configuration
            var kontoConfig = new KontoConfiguration(
                kontoId: Guid.Parse(fiksIoAccountId) /* Fiks IO accountId as Guid */,
                privatNokkel: ReadFromFile(fiksIoPrivateKeyPath) /* Private key in PEM format, paired with the public key supplied to Fiks IO account */);

            // Values generated in Fiks Forvaltning when creating the "Integrasjon"
            var integrasjonId       = Environment.GetEnvironmentVariable("INTEGRASJON_ID");
            var integrasjonPassword = Environment.GetEnvironmentVariable("INTEGRASJON_PWD");

            // Id and password for integration associated to the Fiks IO account.
            var integrasjonConfig = new IntegrasjonConfiguration(
                Guid.Parse(integrasjonId) /* Integration id as Guid */,
                integrasjonPassword /* Integration password */);


            // Optional: Use custom api host (i.e. for connecting to test api)
            var apiConfig = new ApiConfiguration(
                scheme: "https",
                host: "api.fiks.test.ks.no",
                port: 443);

            // Optional: Use custom amqp host (i.e. for connection to test queue)
            var amqpConfig = new AmqpConfiguration(
                host: "io.fiks.test.ks.no",
                port: 5671);

            // Combine all configurations
            var configuration = new FiksIOConfiguration(kontoConfig, integrasjonConfig, maskinportenConfig, apiConfig,
                                                        amqpConfig);

            using (var client = new FiksIOClient(configuration))
            {
                var lookupTask = client.Lookup(new LookupRequest("999999999", "no.ks.fiks.melding", 2));
                lookupTask.Wait(TimeSpan.FromSeconds(30));

                var konto = lookupTask.Result;
            }
        }
Exemplo n.º 33
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     ApiConfiguration.ConfigureServices(services, Environment, Configuration);
 }
Exemplo n.º 34
0
 public ApiClient(IAccessTokenProvider auth = null, ApiConfiguration config = null)
 {
     acccessTokenProvider = auth ?? new AnonymousAccessTokenProvider();
     configuration        = config ?? new ApiConfiguration();
     httpClient           = new HttpClient(auth, config);
 }
Exemplo n.º 35
0
 public WebhookEndPoint(ApiConfiguration config, ILogger logger) : base(logger, config)
 {
 }
Exemplo n.º 36
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app)
 {
     ApiConfiguration.Configure(app);
 }
Exemplo n.º 37
0
 public Startup(IConfiguration configuration)
 {
     _apiConfiguration = new ApiConfiguration(configuration);
     //Configuration = configuration;
 }
Exemplo n.º 38
0
        public override IEnumerable <AlertDTO> Compute(IEnumerable <BidEntry> orders, ApiConfiguration config, IEnumerable <PoolHashrate> poolData)
        {
            var threshold      = TotalHashThreshold ?? config.TotalHashThreshold;
            var foundOrders    = new List <AlertDTO>();
            var aliveOrders    = orders.Where(o => o.Alive).ToList();
            var totalOrderHash = aliveOrders.Sum(o => o.AcceptedSpeed);
            var averagePrice   = aliveOrders.Where(o => o.AcceptedSpeed > 0).Average(o => o.Price);

            var hasRate = Cache.TryGetValue <double>(Constants.HashRateKey, out var networkRateInMh);

            // To cut back on alert spam report if:
            // a.Power > 100 % and NOT profitable
            // or
            // b.Power > 150 % and likely FOR PROFIT
            var modifier = 1.5;

            if (IsOverpaying(averagePrice))
            {
                modifier = 1;
            }

            if (hasRate && totalOrderHash * threshold >= networkRateInMh * modifier)
            {
                _attackStart = GetNewAttackStart();

                string condition = $"Condition: " +
                                   $"Active Orders Hash ({totalOrderHash:F2} Mh/s) above or equal to " +
                                   $"{threshold * 100:F2}% (actual {totalOrderHash / networkRateInMh * 100:F2}%) of " +
                                   $"Total Network Hash ({networkRateInMh:F2}) Mh/s " +
                                   $"{this.CreateIsProfitableMessage(averagePrice, "Average Price of ")} " +
                                   $"{this.AnalyzePools(poolData, totalOrderHash)}" +
                                   $"{this.BlockInfo()}";
                string message = $"{MessagePrefix}Market Total Threshold ALERT - 'AT RISK'. {CreateShortIsProfitableMessage(averagePrice)} ";

                foundOrders.Add(new AlertDTO()
                {
                    BidEntry = new BidEntry()
                    {
                        RecordDate         = DateTime.UtcNow,
                        Algo               = orders.FirstOrDefault()?.Algo,
                        Price              = averagePrice,
                        Alive              = true,
                        NiceHashId         = "Aggregation",
                        NiceHashDataCenter = 0,
                        LimitSpeed         = aliveOrders.Sum(o => o.LimitSpeed),
                        AcceptedSpeed      = aliveOrders.Sum(o => o.AcceptedSpeed), // in Mh/s
                    },
                    Condition = condition,
                    Message   = message
                });
            }

            return(foundOrders);
        }