public void SetUp()
 {
     _configuration = Substitute.For<IApiConfiguration>();
     _webFactory = new TestWebRequestFactory();
     _service = new CustomerPaymentRecordWithDiscountsAndFeesService(_configuration, _webFactory);
     _configuration.ApiBaseUrl.Returns(ApiRequestHandler.ApiRequestUri.AbsoluteUri);
 }
 public ApiStreamRequestHandler(IApiConfiguration configuration, ICompanyFileCredentials credentials, OAuthTokens oauth = null)
 {
     _oauth = oauth;
     _configuration = configuration;
     _credentials = credentials;
     _helper = new ApiRequestHelper();
 }
 public void SetUp()
 {
     _configuration = Substitute.For<IApiConfiguration>();
     _webFactory = new TestWebRequestFactory();
     _service = new CalculateDiscountsFeesService(_configuration, _webFactory);
     _configuration.ApiBaseUrl.Returns(ApiRequestHandler.ApiRequestUri.AbsoluteUri);
 }
 public HandlerSettings(IConfigurationRotatationTimer rotater, IApiConfiguration configuration)
 {
     rotater.RotateConfiguration += OnRotateConfiguration;
     this.rotater = rotater;
     this.configuration = configuration;
     Current = configuration.ChaosSettings.FirstOrDefault();            
 }
 public void SetUp()
 {
     _configuration = Substitute.For<IApiConfiguration>();
     _webFactory = new TestWebRequestFactory();
     _service = new ContactService(_configuration, _webFactory, null);
     _configuration.ApiBaseUrl.Returns(ApiRequestHandler.ApiRequestUri.AbsoluteUri);
     _uid = Guid.NewGuid();
 }
        private static bool ShouldNotEnableChaosTimer(IApiConfiguration configuration)
        {
            if (!configuration.Enabled)
            {
                return true;
            }

            return Convert.ToInt32(configuration.ChaosInterval.TotalMilliseconds) == 0;
        }
 public void SetStandardHeaders(WebRequest request, IApiConfiguration configuration, ICompanyFileCredentials credentials, OAuthTokens oauth = null)
 {
     request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", oauth.Maybe(_ => _.AccessToken, string.Empty));
     request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
     request.Headers["x-myobapi-key"] = configuration.ClientId;
     request.Headers["x-myobapi-version"] = "v2";
     request.Headers["x-myobapi-cftoken"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", 
         credentials.Maybe(_ => _.Username).Maybe(_ => _, string.Empty), credentials.Maybe(_ => _.Password).Maybe(_ => _, string.Empty))));
 }
 public TraktUserService(IAuthenticator authenticator,
                         ICachedHttpHelper cachedHttpHelper,
                         IApiConfiguration configuration)
 {
     _authenticator    = authenticator;
     _cachedHttpHelper = cachedHttpHelper;
     _httpClient       = new HttpClient();
     _httpClient.DefaultRequestHeaders.Add("trakt-api-version", "2");
     _httpClient.DefaultRequestHeaders.Add("trakt-api-key", configuration.TmdbApiKey);
 }
        public ApiContext(RequestContext requestContext,IApiConfiguration apiConfiguration)
        {
            if (apiConfiguration==null)
                apiConfiguration = ServiceLocator.Current.GetInstance<IApiConfiguration>();

            if (requestContext == null) return;
            RequestContext = requestContext;

            //!!! Register in HttpContext. Needed for lifetime manager
            RequestContext.HttpContext.Items["_apiContext"] = this;

            Count = 0;
            //Try parse values
            string count = GetRequestValue("count");
            ulong countParsed;
            if (!string.IsNullOrEmpty(count) && ulong.TryParse(count,out countParsed))
            {
                //Count specified and valid
                SpecifiedCount = (long)Math.Max(0,Math.Min(apiConfiguration.ItemsPerPage, countParsed));
            }
            else
            {
                SpecifiedCount = Math.Max(0,apiConfiguration.ItemsPerPage);
            }
            Count = SpecifiedCount + 1;//NOTE: +1 added to see if it's last page


            string startIndex = GetRequestValue("startIndex");
            long startIndexParsed;
            if (startIndex != null && long.TryParse(startIndex,out startIndexParsed))
            {
                StartIndex =Math.Max(0,startIndexParsed);
                SpecifiedStartIndex = StartIndex;
            }

            string sortOrder = GetRequestValue("sortOrder");
            if ("descending".Equals(sortOrder))
            {
                SortDescending = true;
            }

            FilterToType = GetRequestValue("type");
            SortBy = GetRequestValue("sortBy");
            FilterBy = GetRequestValue("filterBy");
            FilterOp = GetRequestValue("filterOp");
            FilterValue = GetRequestValue("filterValue");
            FilterValues = GetRequestArray("filterValue");
            Fields = GetRequestArray("fields");

            string updatedSince = GetRequestValue("updatedSince");
            if (updatedSince != null)
            {
                UpdatedSince = Convert.ToDateTime(updatedSince);
            }
        }
Exemple #10
0
 protected GetBaseTest(
     Resource resource,
     Dictionary <string, JArray> resultsDictionary,
     IApiConfiguration configuration,
     IOAuthTokenHandler tokenHandler)
 {
     Resource          = resource;
     ResultsDictionary = resultsDictionary;
     Configuration     = configuration;
     TokenHandler      = tokenHandler;
 }
        public void Initialise(IApiConfiguration configuration, CompanyFile companyFile,
                               ICompanyFileCredentials credentials, IOAuthKeyService oAuthKeyService)
        {
            // Add any initialization after the InitializeComponent() call.
            MyConfiguration = configuration;
            MyCompanyFile = companyFile;
            MyCredentials = credentials;
            MyOAuthKeyService = oAuthKeyService;

            Text = string.Format("{0} - {1}", companyFile.Name, companyFile.Uri);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WebhookService"/> class.
 /// </summary>
 /// <param name="loggerFactory">The logger factory.</param>
 /// <param name="mediator">The mediator.</param>
 /// <param name="configuration">The API configuration.</param>
 /// <param name="httpClient">The HTTP client.</param>
 public WebhookService(
     ILoggerFactory loggerFactory,
     IMediator mediator,
     IApiConfiguration configuration,
     IJsonHttpClient httpClient)
 {
     logger             = loggerFactory?.CreateLogger <WebhookService>() ?? throw new ArgumentNullException(nameof(loggerFactory));
     this.mediator      = mediator ?? throw new ArgumentNullException(nameof(mediator));
     this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
     this.httpClient    = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
 }
Exemple #13
0
        public ClockSingleton(IApiConfiguration configuration)
        {
            if (!configuration.OverrideClock)
            {
                return;
            }
            var overrideDate = configuration.OverrideClockDate;

            _currentDateFunc = () =>
                               overrideDate.AddMilliseconds(DateTime.Now.Subtract(FirstCreatedDate).TotalMilliseconds);
        }
        public void Initialise(IApiConfiguration configuration, CompanyFile companyFile,
                               ICompanyFileCredentials credentials, IOAuthKeyService oAuthKeyService)
        {
            // Add any initialization after the InitializeComponent() call.
            MyConfiguration   = configuration;
            MyCompanyFile     = companyFile;
            MyCredentials     = credentials;
            MyOAuthKeyService = oAuthKeyService;

            Text = string.Format("{0} - {1}", companyFile.Name, companyFile.Uri);
        }
Exemple #15
0
        /// <summary>
        /// Expose namespace containing a specific type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static ITypeSetExposureConfiguration ExposeNamespaceContaining <T>(this IApiConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var namespaceT = typeof(T).Namespace;

            return(configuration.Expose(typeof(T).GetTypeInfo().Assembly.ExportedTypes.Where(t => t.Namespace.StartsWith(namespaceT))));
        }
 public TtApiServiceBase(
     IApiConfiguration apiConfiguration,
     IHttpContextAccessor httpContextAccessor,
     IHttpClientFactory httpClientFactory,
     ILogger <TtApiServiceBase> logger)
 {
     this.apiConfiguration    = apiConfiguration;
     this.httpContextAccessor = httpContextAccessor;
     this.httpClientFactory   = httpClientFactory;
     this.logger = logger;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CreateCommandHandler"/> class.
 /// </summary>
 /// <param name="module">The command handler module.</param>
 /// <param name="idGenerator">The generator for unique identifiers.</param>
 /// <param name="constants">The application constants.</param>
 /// <param name="apiConfiguration">The API configuration.</param>
 public CreateCommandHandler(
     ICommandHandlerModule module,
     IIdGenerator idGenerator,
     IApplicationConstants constants,
     IApiConfiguration apiConfiguration)
     : base(module)
 {
     this.idGenerator      = idGenerator ?? throw new ArgumentNullException(nameof(idGenerator));
     this.constants        = constants ?? throw new ArgumentNullException(nameof(constants));
     this.apiConfiguration = apiConfiguration ?? throw new ArgumentNullException(nameof(apiConfiguration));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ResetCommandHandler"/> class.
        /// </summary>
        /// <param name="module">The command handler module.</param>
        /// <param name="configuration">The API configuration.</param>
        /// <param name="serializer">The JSON serializer.</param>
        public ResetCommandHandler(
            ICommandHandlerModule module,
            IApiConfiguration configuration,
            IDefaultJsonSerializer serializer)
            : base(module)
        {
            this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this.serializer    = serializer ?? throw new ArgumentNullException(nameof(serializer));

            batchSize = configuration.Options.BatchSize > 0 ? configuration.Options.BatchSize : 1000;
        }
 public SignerController(
     ISimpleMemoryCache simpleMemoryCache,
     IApiConfiguration apiConfiguration,
     IAlfrescoHttpClient alfrescoHttpClient,
     ISignerService signerService
     )
 {
     _simpleMemoryCache  = simpleMemoryCache;
     _apiConfiguration   = apiConfiguration;
     _alfrescoHttpClient = alfrescoHttpClient;
     _signerService      = signerService;
 }
Exemple #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IdentityService"/> class.
 /// </summary>
 /// <param name="loggerFactory">The logger factory.</param>
 /// <param name="configuration">The API configuration.</param>
 /// <param name="idGenerator">The generator for unique identifiers.</param>
 /// <param name="principalProvider">The principal provider.</param>
 /// <param name="userManager">The user manager.</param>
 public IdentityService(
     ILoggerFactory loggerFactory,
     IApiConfiguration configuration,
     IIdGenerator idGenerator,
     ICustomPrincipalProvider principalProvider,
     UserManager <UserEntity> userManager)
 {
     logger                 = loggerFactory?.CreateLogger <IdentityService>() ?? throw new ArgumentNullException(nameof(loggerFactory));
     this.configuration     = configuration ?? throw new ArgumentNullException(nameof(configuration));
     this.principalProvider = principalProvider ?? throw new ArgumentNullException(nameof(principalProvider));
     this.userManager       = userManager ?? throw new ArgumentNullException(nameof(userManager));
 }
        public ChaosIntervalTimer(IApiConfiguration configuration)
        {
            InsideChaosWindow = configuration.Enabled;

            if (ShouldNotEnableChaosTimer(configuration))
            {
                return;
            }

            ChaosTimer = new Timer(configuration.ChaosInterval.TotalMilliseconds);
            ChaosTimer.Elapsed += OnTimerElapsed;
            ChaosTimer.Start();
        }
Exemple #22
0
        public void SetUp()
        {
            _configuration = Substitute.For <IApiConfiguration>();
            _webFactory    = new TestWebRequestFactory();
            _service       = new CompanyPreferencesService(_configuration, _webFactory);
            _configuration.ApiBaseUrl.Returns(ApiRequestHandler.ApiRequestUri.AbsoluteUri);

            _cf = new CompanyFile
            {
                Uri = new Uri("https://dc1.api.myob.com/accountright/7D5F5516-AF68-4C5B-844A-3F054E00DF10")
            };
            _getRangeUri = string.Format("{0}/{1}/", _cf.Uri.AbsoluteUri, _service.Route);
        }
 public TraktShowService(IAuthenticator authenticator,
                         ICachedHttpHelper cachedHttpHelper,
                         IImageService imageService,
                         IShowFilterer showFilterer,
                         IApiConfiguration configuration)
 {
     _authenticator    = authenticator;
     _cachedHttpHelper = cachedHttpHelper;
     _imageService     = imageService;
     _showFilterer     = showFilterer;
     _httpClient       = new HttpClient();
     _httpClient.DefaultRequestHeaders.Add("trakt-api-version", "2");
     _httpClient.DefaultRequestHeaders.Add("trakt-api-key", configuration.TraktClientId);
 }
Exemple #24
0
        public void Register(INavigationService navigationService, INotificationService notificationService,
                             IBrowsingService browsingService, IApiConfiguration apiConfiguration)
        {
            // Luvi services
            this.container.RegisterInstance(navigationService, new ContainerControlledLifetimeManager());
            this.container.RegisterInstance(notificationService, new ContainerControlledLifetimeManager());
            this.container.RegisterInstance(browsingService, new ContainerControlledLifetimeManager());

            // Repositories
            var repositories = RepositoryFactory.CreateRepositories(apiConfiguration);

            this.container.RegisterInstance(repositories.Item1, new ContainerControlledLifetimeManager());
            this.container.RegisterInstance(repositories.Item2, new ContainerControlledLifetimeManager());
        }
Exemple #25
0
        public ServerInitializationManager(
            IServerSettings serverSettings,
            ILogsManager logsManager,
            IServerInitializationManagerHelpers serverInitializationManagerHelpers,
            IApiConfiguration apiConfiguration)
        {
            _serverSettings = serverSettings;

            _logsManager = logsManager;

            _serverInitializationManagerHelpers = serverInitializationManagerHelpers;

            _apiConfiguration = apiConfiguration;
        }
        public OdsRestClient(IApiConfiguration configuration, OAuthTokenHandler tokenHandler, List <string> schemaNames)
        {
            ServicePointManager.Expect100Continue      = false;
            ServicePointManager.ReusePort              = true;
            ServicePointManager.DefaultConnectionLimit = configuration.ConnectionLimit;

            _configuration = configuration;
            _tokenHandler  = tokenHandler;
            _schemaNames   = schemaNames;

            _httpClient = new HttpClient
            {
                Timeout = new TimeSpan(0, 0, 5, 0), BaseAddress = new Uri(_configuration.Url.TrimEnd('/'))
            };
        }
Exemple #27
0
 private void LogintoCompanyFile()
 {
     try
     {
         IApiConfiguration config = ConfigurationCloud;
         var configFilePath       = ServiceInfo.GetFileURI(AccountingIntegration.Properties.Settings.Default.CompanyFileDetails);
         var credentials          = XeroHelper.DeSerializeFromFilePath <CompanyFileCredentialsCF>(configFilePath);
         Credentials = new CompanyFileCredentials(credentials.CredentialsDetails.UserName, credentials.CredentialsDetails.Password);
         GetCompanyFileDetails(Credentials);
     }
     catch (Exception ex)
     {
         ServiceLogger.LogException("Exception in LogintoCompanyFile", ex);
     }
 }
Exemple #28
0
 public void FetchFile(IApiConfiguration configurationCloud, IWebRequestFactory webRequestFactory, IOAuthKeyService keyService, string inFilename)
 {
     try
     {
         ServiceLogger.Log("In fetch File");
         FileName           = inFilename;
         ConfigurationCloud = configurationCloud;
         MyOAuthKeyService  = keyService;
         var cfsCloud = new CompanyFileService(configurationCloud, null, keyService);
         cfsCloud.GetRange(OnComplete, OnError);
     }
     catch (Exception ex)
     {
         ServiceLogger.LogException("Exception in FetchFile", ex);
     }
 }
Exemple #29
0
        public NmsApiClient(IApiConfiguration config)
        {
            // Select certificate to send
            certificate = new X509Certificate2(config.CertificatePath, config.CertificatePassword);

            // Configure handler
            HttpClientHandler handler = new HttpClientHandler();

            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.ServerCertificateCustomValidationCallback = CheckCertificate;
            handler.ClientCertificates.Add(certificate);

            // HTTP client
            client             = new HttpClient(handler);
            client.BaseAddress = new Uri(config.ServerEndpoint);
        }
        public RestClientIDS(IApiConfiguration configuration, IIDSConfiguration idsConfiguration, IRestConfiguration restConfiguration)
            : base(configuration)
        {
            _idsConfiguration  = idsConfiguration;
            _restConfiguration = restConfiguration;

            SerializationSettings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                DateTimeZoneHandling  = DateTimeZoneHandling.Utc,
                DateFormatHandling    = DateFormatHandling.IsoDateFormat
            };

            DeserializationSettings = SerializationSettings;
        }
        public ConfigurationRotationTimer(IApiConfiguration configuration)
        {
            if (Convert.ToInt32(configuration.ConfigurationRotationInterval.TotalMilliseconds) == 0)
            {
                return;
            }

            if (configuration.ChaosSettings.Count <= 1)
            {
                return;                
            }

            ChaosTimer = new Timer(configuration.ConfigurationRotationInterval.TotalMilliseconds);
            ChaosTimer.Elapsed += OnTimerElapsed;
            ChaosTimer.Start();
        }
Exemple #32
0
        public NmsApiClient(IApiConfiguration config)
        {
            // Select certificate to send
            certificate = new X509Certificate2(config.CertificatePath, config.CertificatePassword);

            // Configure handler
            WebRequestHandler handler = new WebRequestHandler();

            handler.AuthenticationLevel                 = AuthenticationLevel.MutualAuthRequired;
            handler.ClientCertificateOptions            = ClientCertificateOption.Manual;
            handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckCertificate);
            handler.ClientCertificates.Add(certificate);

            // HTTP client
            client             = new HttpClient(handler);
            client.BaseAddress = new Uri(config.ServerEndpoint);
        }
Exemple #33
0
        /// <summary>
        /// Set common headers on the request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="configuration"></param>
        /// <param name="credentials"></param>
        /// <param name="oauth"></param>
        public void SetStandardHeaders(WebRequest request, IApiConfiguration configuration,
                                       ICompanyFileCredentials credentials, OAuthTokens oauth = null)
        {
            if (oauth != null)
            {
                request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}",
                                                                                 oauth.AccessToken.Maybe(_ => _, string.Empty));
            }
#if !PORTABLE
            if ((request as HttpWebRequest).Maybe(_ => _.ClientCertificates.Maybe(c => c.Count != 0)))
            {
                request.Headers.Remove(HttpRequestHeader.Authorization);
            }
#endif
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";

            IgnoreError(() =>
            {
#if PORTABLE
                request.Headers[HttpRequestHeader.UserAgent] = UserAgent;
#else
                try
                {
                    var webRequest = request as HttpWebRequest;
                    if (webRequest != null)
                    {
                        webRequest.UserAgent = UserAgent;
                    }
                }
                catch (Exception)
                {
                    request.Headers[HttpRequestHeader.UserAgent] = UserAgent;
                }
#endif
            });

            request.Headers["x-myobapi-key"]     = configuration.ClientId;
            request.Headers["x-myobapi-version"] = "v2";

            if ((credentials != null) && (!String.IsNullOrEmpty(credentials.Username))) // password can be empty
            {
                request.Headers["x-myobapi-cftoken"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}",
                                                                                                                   credentials.Username.Maybe(_ => _, string.Empty), credentials.Password.Maybe(_ => _, string.Empty))));
            }
        }
Exemple #34
0
 public ApiLoaderApplication(
     FileImportPipeline fileImportPipeline,
     ResourcePipeline resourcePipeline,
     ISubmitResource submitResourcesProcessor,
     IResourceHashCache xmlResourceHashCache,
     IXmlReferenceCacheFactory xmlReferenceCacheFactory,
     IApiConfiguration apiConfiguration,
     IDependenciesRetriever dependenciesRetriever,
     IBulkLoadClientResult bulkLoadClientResult)
 {
     _fileImportPipeline       = fileImportPipeline;
     _resourcePipeline         = resourcePipeline;
     _submitResourcesProcessor = submitResourcesProcessor;
     _xmlResourceHashCache     = xmlResourceHashCache;
     _xmlReferenceCacheFactory = xmlReferenceCacheFactory;
     _apiConfiguration         = apiConfiguration;
     _dependenciesRetriever    = dependenciesRetriever;
     _bulkLoadClientResult     = bulkLoadClientResult;
 }
Exemple #35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CreateCommandHandler"/> class.
        /// </summary>
        /// <param name="module">The command handler module.</param>
        /// <param name="idGenerator">The generator for unique identifiers.</param>
        /// <param name="constants">The application constants.</param>
        /// <param name="apiConfiguration">The API configuration.</param>
        /// <param name="appConfiguration">The application configuration.</param>
        /// <param name="fileSystemStrategy">The file system strategy.</param>
        public CreateCommandHandler(
            ICommandHandlerModule module,
            IIdGenerator idGenerator,
            IApplicationConstants constants,
            IApiConfiguration apiConfiguration,
            IAppConfiguration appConfiguration,
            IFileSystemStrategy fileSystemStrategy)
            : base(module)
        {
            this.idGenerator      = idGenerator ?? throw new ArgumentNullException(nameof(idGenerator));
            this.constants        = constants ?? throw new ArgumentNullException(nameof(constants));
            this.apiConfiguration = apiConfiguration ?? throw new ArgumentNullException(nameof(apiConfiguration));
            this.appConfiguration = appConfiguration ?? throw new ArgumentNullException(nameof(appConfiguration));

            if (fileSystemStrategy == null)
            {
                throw new ArgumentNullException(nameof(fileSystemStrategy));
            }

            fileSystem = fileSystemStrategy.Create(appConfiguration.Options.WorkingDirectory);
        }
Exemple #36
0
        /// <summary>
        /// Inserts Logging at the beginning and end of the pipeline
        /// </summary>
        /// <param name="context"></param>
        /// <param name="loggingRepository"></param>
        /// <param name="apiConfiguration"></param>
        /// <returns></returns>
        public async Task Invoke(
            HttpContext context,
            ILoggingRepository loggingRepository,
            IApiConfiguration apiConfiguration)
        {
            SetupLogging(apiConfiguration);
            Serilog.Log.Information("Logging Enabled");

            if (apiConfiguration.GetRequestResponseArchiveEnabled())
            {
                _apiConfiguration  = apiConfiguration;
                _loggingRepository = loggingRepository;

                await LogRequestAsync(context);
                await LogResponseAsync(context);
            }
            else
            {
                await _next.Invoke(context);
            }
        }
        public void SetFixture(MyobArlApiPact data)
        {
            _mockProviderService        = data.MockProviderService;
            _mockProviderServiceBaseUri = data.MockProviderServiceBaseUri;
            _mockProviderService.ClearInteractions(); //NOTE: Clears any previously registered interactions before the test is run

            _configuration = Substitute.For <IApiConfiguration>();
            _service       = new TimesheetService(_configuration, keyService: new SimpleOAuthKeyService {
                OAuthResponse = new OAuthTokens {
                    ExpiresIn = 120
                }
            });

            _cfUid = Guid.NewGuid();
            _uid   = Guid.NewGuid();

            _cf = new CompanyFile
            {
                Uri = new Uri(string.Format("{0}/accountright/{1}", _mockProviderServiceBaseUri, _cfUid))
            };
        }
Exemple #38
0
        /// <summary>
        /// Gets the remote IP address.
        /// </summary>
        /// <param name="context">The HTTP context.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>The remote IP address.</returns>
        public static string GetRemoteIpAddress(this HttpContext context, IApiConfiguration configuration)
        {
            Ensure.ArgumentNotNull(context, nameof(context));
            Ensure.ArgumentNotNull(configuration, nameof(configuration));

            string remoteIp = null;

            if (!string.IsNullOrWhiteSpace(configuration.Options.ConnectingIpHeaderName))
            {
                if (context?.Request?.Headers?.TryGetValue(configuration.Options.ConnectingIpHeaderName, out StringValues connectingIpHeader) ?? false)
                {
                    remoteIp = connectingIpHeader.FirstOrDefault();
                }
            }

            if (string.IsNullOrWhiteSpace(remoteIp))
            {
                remoteIp = context?.Connection?.RemoteIpAddress?.ToString();
            }

            return(remoteIp);
        }
        public static void UseSwaggerAll(this IApplicationBuilder app, IApiConfiguration apiConfiguration)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                var swaggers = apiConfiguration?.SwaggerOptions?
                               .Where(x => x != null)
                               .Where(x => x.Versions != null && x.Versions.Any())
                               .Select(x => x) ?? new List <SwaggerOptions>();

                swaggers.ForEach(swagger => swagger.Versions.ForEach(version =>
                {
                    if (version.Enabled)
                    {
                        c.SwaggerEndpoint($"/swagger/{swagger.Route}-{version.Version}/swagger.json", $"{swagger.Route}-{version.Version}");
                    }
                }));

                c.DisplayRequestDuration();
                c.RoutePrefix = string.Empty;
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TokenService"/> class.
        /// </summary>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="configuration">The API configuration.</param>
        /// <param name="constants">The application constants.</param>
        /// <param name="mediator">The mediator.</param>
        /// <param name="serializer">The serializer.</param>
        /// <param name="userManager">The user manager.</param>
        public TokenService(
            ILoggerFactory loggerFactory,
            IApiConfiguration configuration,
            IApplicationConstants constants,
            IMediator mediator,
            IDefaultJsonSerializer serializer,
            UserManager <UserEntity> userManager)
        {
            logger             = loggerFactory?.CreateLogger <TokenService>() ?? throw new ArgumentNullException(nameof(loggerFactory));
            this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this.constants     = constants ?? throw new ArgumentNullException(nameof(constants));
            this.mediator      = mediator ?? throw new ArgumentNullException(nameof(mediator));
            this.userManager   = userManager ?? throw new ArgumentNullException(nameof(userManager));
            this.serializer    = serializer ?? throw new ArgumentNullException(nameof(serializer));
            var serializerWrapper = new JwtJsonSerializerWrapper(serializer);
            var urlEncoder        = new JwtBase64UrlEncoder();

            encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializerWrapper, urlEncoder);
            var validator = new JwtValidator(serializerWrapper, new UtcDateTimeProvider());

            decoder = new JwtDecoder(serializerWrapper, validator, urlEncoder);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ThrottleMiddleware"/> class.
        /// </summary>
        /// <param name="next">The next.</param>
        /// <param name="options">The options.</param>
        /// <param name="counterStore">The counter store.</param>
        /// <param name="policyStore">The policy store.</param>
        /// <param name="config">The rate limit configuration.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="configuration">The API configuration.</param>
        /// <param name="serializer">The JSON serializer.</param>
        /// <exception cref="ArgumentNullException">configuration</exception>
        public ThrottleMiddleware(
            RequestDelegate next,
            IOptions <IpRateLimitOptions> options,
            IRateLimitCounterStore counterStore,
            IIpPolicyStore policyStore,
            IRateLimitConfiguration config,
            ILogger <IpRateLimitMiddleware> logger,
            IApiConfiguration configuration,
            IDefaultJsonSerializer serializer)
            : base(next, options, counterStore, policyStore, config, logger)
        {
            Ensure.ArgumentNotNull(options, nameof(options));

            if (options.Value == null)
            {
                throw new UnexpectedNullException("The options value is null.");
            }

            this.options       = options.Value;
            this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this.serializer    = serializer ?? throw new ArgumentNullException(nameof(serializer));
        }
        /// <summary>
        /// Function to return the OAuth code
        /// </summary>
        /// <param name="config">Contains the API configuration such as ClientId and Redirect URL</param>
        /// <returns>OAuth code</returns>
        /// <remarks></remarks>
        public static string GetAuthorizationCode(IApiConfiguration config)
        {
            //Format the URL so  User can login to OAuth server
            string url = string.Format("{0}?client_id={1}&redirect_uri={2}&scope={3}&response_type=code", CsOAuthServer,
                                       config.ClientId, HttpUtility.UrlEncode(config.RedirectUrl), CsOAuthScope);

            // Create a new form with a web browser to display OAuth login page
            var frm = new Form();
            var webB = new WebBrowser();
            frm.Controls.Add(webB);
            webB.Dock = DockStyle.Fill;

            // Add a handler for the web browser to capture content change
            webB.DocumentTitleChanged += WebBDocumentTitleChanged;

            // navigat to url and display form
            webB.Navigate(url);
            frm.Size = new Size(800, 600);
            frm.ShowDialog();

            //Retrieve the code from the returned HTML
            return ExtractSubstring(webB.DocumentText, "code=", "<");
        }
Exemple #43
0
        public static void Register(HttpConfiguration config, IApiConfiguration configuration)
        {
            if (!configuration.Enabled)
            {
                return;
            }

            configuration.Validate();

            config.MessageHandlers.Insert(
                0,
                new ChaoticDelegatingHandler(
                    new Chance(),
                    new HandlerSettings(new ConfigurationRotationTimer(configuration), configuration), 
                    new ChaoticResponseFactory(new ResponseMediaType()),
                    new RandomDelay(),
                    new ChaosIntervalTimer(configuration)));

            if (!config.Routes.ContainsKey("chaos.config.update"))
            {
                config.Routes.MapHttpRoute("chaos.config.update", "chaos/configuration/v1/changed", new { controller = "ChaosConfigurationChangedHook", action = "Post" });
            }            
        }
        /// <summary>
        /// Set common headers on the request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="configuration"></param>
        /// <param name="credentials"></param>
        /// <param name="oauth"></param>
        public void SetStandardHeaders(WebRequest request, IApiConfiguration configuration, 
            ICompanyFileCredentials credentials, OAuthTokens oauth = null)
        {
            if (oauth != null)
            {
                request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}",
                    oauth.AccessToken.Maybe(_ => _, string.Empty));
            }
#if !PORTABLE
            if ((request as HttpWebRequest).Maybe(_ => _.ClientCertificates.Maybe(c => c.Count != 0)))
            {
                request.Headers.Remove(HttpRequestHeader.Authorization);
            }
#endif
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
            
            IgnoreError(() =>
                {
#if PORTABLE
                    request.Headers[HttpRequestHeader.UserAgent] = UserAgent;
#else
                    try
                    {
                        var webRequest = request as HttpWebRequest;
                        if (webRequest != null)
                            webRequest.UserAgent = UserAgent;
                    }
                    catch (Exception)
                    {
                        request.Headers[HttpRequestHeader.UserAgent] = UserAgent;
                    }
#endif
                });

            request.Headers["x-myobapi-key"] = configuration.ClientId;
            request.Headers["x-myobapi-version"] = "v2";

            if (credentials != null)
            {
                request.Headers["x-myobapi-cftoken"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}",
                    credentials.Username.Maybe(_ => _, string.Empty), credentials.Password.Maybe(_ => _, string.Empty))));
            }
        }
 public void SetUp()
 {
     _configuration = Substitute.For<IApiConfiguration>();
 }
        /// <summary>
        /// Event that is called when the form loads
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks></remarks>
        private void CompanyFilesLoad(object sender, EventArgs e)
        {
            try
            {
                ShowSpinner();

                //If developer key  enable (see above) and set useCVloud to true the following section manages OAuth token and accessing cloud service
                if (UseCloud)
                {
                    _configurationCloud = new ApiConfiguration(DeveloperKey, DeveloperSecret, "http://desktop");
                    _oAuthKeyService = new OAuthKeyService();

                    //Get tokens if not stored
                    if (_oAuthKeyService.OAuthResponse == null)
                    {
                        var oauthService = new OAuthService(_configurationCloud);
                        _oAuthKeyService.OAuthResponse =
                            oauthService.GetTokens(OAuthLogin.GetAuthorizationCode(_configurationCloud));
                    }

                    // Load all files from cloud and local simultaneously
                    var cfsCloud = new CompanyFileService(_configurationCloud, null, _oAuthKeyService);
                    cfsCloud.GetRange(OnComplete, OnError);
                }

                _configurationLocal = new ApiConfiguration(LocalApiUrl);
                var cfsLocal = new CompanyFileService(_configurationLocal);
                cfsLocal.GetRange(OnComplete, OnError);

                //' The following two lines can be called to run synchronously rather than async
                //_companyFiles = cfs.GetRange()
                //dgvCompanyFiles.DataSource = _companyFiles
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 /// <summary>
 /// Initialise a service that can use <see cref="Timesheet"/> resources
 /// </summary>
 /// <param name="configuration">The configuration required to communicate with the API service</param>
 /// <param name="webRequestFactory">A custom implementation of the <see cref="WebRequestFactory"/>, if one is not supplied a default <see cref="WebRequestFactory"/> will be used.</param>
 /// <param name="keyService">An implementation of a service that will store/persist the OAuth tokens required to communicate with the cloud based API at http://api.myob.com/accountright </param>
 public TimesheetService(IApiConfiguration configuration, IWebRequestFactory webRequestFactory = null, IOAuthKeyService keyService = null)
     : base(configuration, webRequestFactory, keyService)
 {
 }
 public TestServiceBase(IApiConfiguration configuration, IWebRequestFactory webRequestFactory, IOAuthKeyService keyService) 
     : base(configuration, webRequestFactory, keyService)
 {
 }
 /// <summary>
 /// Instantiate with OAuth configuration 
 /// </summary>
 /// <param name="configuration">The configuration required to communicate with the API service</param>
 /// <param name="factory">A custom IWebRequestFactory implementation, defaults to WebRequestFactory if not supplied.</param>
 public OAuthService(IApiConfiguration configuration, IWebRequestFactory factory = null)
 {
     _configuration = configuration;
     this._factory = factory ?? new WebRequestFactory(configuration);
 }
 public OAuthRequestHandler(IApiConfiguration configuration)
 {
     _configuration = configuration;
 }
 /// <summary>
 /// WebRequest factory constructor
 /// </summary>
 /// <param name="configuration">Configuration</param>
 public WebRequestFactory(IApiConfiguration configuration)
 {
     _configuration = configuration;
 }
 public void TestSetup()
 {
     _configuration = Substitute.For<IApiConfiguration>();
     _webRequestFactory = Substitute.For<IWebRequestFactory>();
     _keyService = Substitute.For<IOAuthKeyService>();
 }
 /// <summary>
 /// Initialise a service that can retrieve <see cref="VersionInfo"/> resources
 /// </summary>
 /// <param name="configuration">The configuration required to communicate with the API service</param>
 /// <param name="webRequestFactory">A custom implementation of the <see cref="WebRequestFactory"/>, if one is not supplied a default <see cref="WebRequestFactory"/> will be used.</param>
 /// <param name="keyService">An implementation of a service that will store/persist the OAuth tokens required to communicate with the cloud based API at http://api.myob.com/accountright </param>
 public VersionInfoService(IApiConfiguration configuration, IWebRequestFactory webRequestFactory, IOAuthKeyService keyService = null) 
     : base(configuration, webRequestFactory, keyService)
 {
 }
 public CompanyFileService(IApiConfiguration configuration, IWebRequestFactory webRequestFactory = null, IOAuthKeyService keyService = null)
     : base(configuration, webRequestFactory, keyService)
 {
 }
 private WebRequestFactory CreateWebRequestFactory(IApiConfiguration configuration = null)
 {
     return new WebRequestFactory(configuration ?? new ApiConfiguration(string.Empty));
 }
 public YBSquareService(IApiConfiguration configuration, IDownloader downloader)
 {
     _configuration = configuration;
     _downloader = downloader;
 }
 public void Given_I_Have_Converted_A_Request_To_An_Api_Configueration()
 {
     var updateConfigurationRequest = BuildRequest();
     apiConfiguration = UpdateRequestToConfigurationConverter.ToApiConfiguration(updateConfigurationRequest);
 }