/// <summary>
        ///     Same as
        ///     <see
        ///         cref="InvisibleCollector(string,string,int,Microsoft.Extensions.Logging.ILogger{InvisibleCollectorLib.InvisibleCollector})" />
        ///     but the <paramref name="remoteUri" /> in Uri format.
        /// </summary>
        /// <param name="remoteUri">The Invisible Collector service address</param>
        public InvisibleCollector(string apiKey, Uri remoteUri, int maxConcurrentRequests = IcConstants.MaxConcurrentRequests, ILogger <InvisibleCollector> logger = null)
        {
            _uriBuilder = new HttpUriBuilder(remoteUri);
            _jsonFacade = new JsonConvertFacade();
            _apiFacade  = new ApiConnectionFacade(apiKey, _jsonFacade.JsonStreamToStringDictionary, maxConcurrentRequests);
            _logger     = logger ?? NullLogger <InvisibleCollector> .Instance;

            _logger.LogInformation("Started Instance");
        }
 protected Uri BuildAuthenticateUri(AuthenticationPermissions scope, ResponseType responseType)
 {
     var builder = new HttpUriBuilder(AuthenticationUrl);
     builder.AddQueryStringParameter("client_id", this.ClientId);
     builder.AddQueryStringParameter("response_type", responseType.ToString().ToLower());
     builder.AddQueryStringParameter("scope", scope.GetParameterValue());
     builder.AddQueryStringParameter("redirect_uri", RedirectUri);
     return builder.Build();
 }
Example #3
0
        /// <summary>
        /// Build an instance
        /// </summary>
        /// <remarks>
        /// You can specify a logger to this class such as the NLog with an adapter.
        /// </remarks>
        /// <param name="apiKey">The company API Key</param>
        /// <param name="remoteUri">The InvisibleCollector service address.</param>
        /// <param name="logger">The logger to be used by the lib</param>
        public InvisibleCollector(string apiKey, string remoteUri = ProdutionUri, ILogger <InvisibleCollector> logger = null)
        {
            _uriBuilder = new HttpUriBuilder(remoteUri);
            _jsonFacade = new JsonConvertFacade();
            _apiFacade  = new ApiConnectionFacade(apiKey, _jsonFacade.JsonStreamToStringDictionary);
            _logger     = logger ?? NullLogger <InvisibleCollector> .Instance;

            _logger.LogInformation("Started Instance");
        }
        /// <summary>
        ///     Get a debt
        /// </summary>
        /// <param name="debtId">The debt id, you can use <see cref="Debt.RoutableId" /></param>
        /// <returns>The up-to-date debt</returns>
        /// <exception cref="IcException">
        ///     On bad json (sent or received) and when the server rejects the request (conflict, bad
        ///     request, invalid parameters, etc)
        /// </exception>
        /// <exception cref="HttpRequestException">
        ///     On connection or protocol related errors (except for the protocol errors sent by the
        ///     Invisible Collector)
        /// </exception>
        /// <seealso cref="SetNewDebtAsync" />
        public async Task <Debt> GetDebtAsync(string debtId)
        {
            var id = HttpUriBuilder.UriEscape(debtId);

            _logger.LogDebug("Making request to get debt information for debt ID: {Id}", debtId);
            var ret = await MakeRequestAsync <Debt>("GET", new[] { DebtsEndpoint, id });

            _logger.LogDebug("Received for debt with id: {Id} information: {Model}", debtId, ret);
            return(ret);
        }
Example #5
0
        /// <summary>
        /// Get customer info
        /// </summary>
        /// <param name="customerId">The ID of the customer whose information is to be retrieved. It can be the 'gid' or 'externalId' of the customer (or just use <see cref="Customer.RoutableId"/>)</param>
        /// <returns>The up-to-date customer information</returns>
        /// <exception cref="IcException">On bad json (sent or received) and when the server rejects the request (conflict, bad request, invalid parameters, etc)</exception>
        /// <exception cref="WebException">On connection or protocol related errors (except for the protocol errors sent by the Invisible Collector)</exception>
        public async Task <Customer> GetCustomerInfoAsync(string customerId)
        {
            var id = HttpUriBuilder.NormalizeUriComponent(customerId);

            _logger.LogDebug("Making request to get customer information for customer ID: {Id}", customerId);
            var ret = await MakeBodylessRequestAsync <Customer>("GET", CustomersEndpoint, id);

            _logger.LogDebug("Received for customer with id: {Id} information: {Model}", customerId, ret);
            return(ret);
        }
        public void WithPath_MultipleFragments()
        {
            const string BaseUri   = "http://host.domain";
            const string Fragment1 = "company";
            const string Fragment2 = "123";
            var          builder   = new HttpUriBuilder(BaseUri);
            var          result    = builder.WithPath(Fragment1, Fragment2).BuildUri();

            Assert.AreEqual($"{BaseUri}/{Fragment1}/{Fragment2}", result.AbsoluteUri);
        }
Example #7
0
        /// <summary>
        /// Get a debt
        /// </summary>
        /// <param name="debtId">The debt id, you can use <see cref="Debt.RoutableId"/></param>
        /// <returns>The up-to-date debt</returns>
        /// <exception cref="IcException">On bad json (sent or received) and when the server rejects the request (conflict, bad request, invalid parameters, etc)</exception>
        /// <exception cref="WebException">On connection or protocol related errors (except for the protocol errors sent by the Invisible Collector)</exception>
        /// <seealso cref="SetNewDebtAsync"/>
        public async Task <Debt> GetDebtAsync(string debtId)
        {
            var id = HttpUriBuilder.NormalizeUriComponent(debtId);

            _logger.LogDebug("Making request to get debt information for debt ID: {Id}", debtId);
            var ret = await MakeBodylessRequestAsync <Debt>("GET", DebtsEndpoint, id);

            _logger.LogDebug("Received for debt with id: {Id} information: {Model}", debtId, ret);
            return(ret);
        }
        public void Constructor_CorrectUri()
        {
            var uri = new HttpUriBuilder("http://ahost.adomain:4000/").BuildUri();

            Assert.AreEqual("http://ahost.adomain:4000/", uri.ToString());

            var uri2 = new HttpUriBuilder("https://host").BuildUri();

            Assert.AreEqual("https://host/", uri2.ToString());
        }
Example #9
0
        /// <summary>
        /// Get customer attributes.
        /// </summary>
        /// <param name="customerId">The ID of the customer whose attributes are to be retrieved. It can be the 'gid' or 'externalId' of the customer (or just use <see cref="Customer.RoutableId"/>)</param>
        /// <returns>The up-to-date customer attributes.</returns>
        /// <exception cref="IcException">On bad json (sent or received) and when the server rejects the request (conflict, bad request, invalid parameters, etc)</exception>
        /// <exception cref="WebException">On connection or protocol related errors (except for the protocol errors sent by the Invisible Collector)</exception>
        /// <seealso cref="SetCustomerAttributesAsync"/>
        public async Task <IDictionary <string, string> > GetCustomerAttributesAsync(string customerId)
        {
            var id = HttpUriBuilder.NormalizeUriComponent(customerId);

            _logger.LogDebug("Making a request to get customer attributes for customer ID: {Id}", customerId);
            var ret = await MakeBodylessRequestAsync <Dictionary <string, string> >("GET", CustomersEndpoint, id,
                                                                                    CustomersAttributesPath);

            _logger.LogDebug("Received for customer with id: {Id} attributes: {Attributes}", customerId, ret.StringifyDictionary());
            return(ret);
        }
Example #10
0
        /// <summary>
        /// Updates the customer's information.
        /// </summary>
        /// <param name="customer">The customer information to be updated. The <see cref="Customer.Gid"/> or <see cref="Customer.ExternalId"/> field must be set, since they contain the id of the customer. The <see cref="Customer.Country"/> field is mandatory.</param>
        /// <returns>The up-to-date updated customer information</returns>
        /// <exception cref="IcException">On bad json (sent or received) and when the server rejects the request (conflict, bad request, invalid parameters, etc)</exception>
        /// <exception cref="WebException">On connection or protocol related errors (except for the protocol errors sent by the Invisible Collector)</exception>
        /// <seealso cref="GetCustomerInfoAsync"/>
        /// <seealso cref="SetNewCustomerAsync"/>
        /// <seealso cref="Customer.RoutableId"/>
        public async Task <Customer> SetCustomerInfoAsync(Customer customer)
        {
            var id = HttpUriBuilder.NormalizeUriComponent(customer.RoutableId);

            customer.AssertHasMandatoryFields(Customer.CountryName);
            _logger.LogDebug("Making a request to update the customer's with ID: {Id} information: {Model}", customer.RoutableId, customer);
            var ret = await MakeRequestAsync <Customer, object>("PUT", customer.SendableDictionary, CustomersEndpoint, id);

            _logger.LogDebug("Updated for the customer with ID: {Id} information: {Model}", customer.RoutableId, ret);
            return(ret);
        }
Example #11
0
        /// <summary>
        /// Get a list of the customer's debts
        /// </summary>
        /// <param name="customerId">The ID of the customer whose debts are to be retrieved. It can be the 'gid' or 'externalId' of the customer (or just use <see cref="Customer.RoutableId"/>)</param>
        /// <returns>The up-to-date list of debts</returns>
        /// <exception cref="IcException">On bad json (sent or received) and when the server rejects the request (conflict, bad request, invalid parameters, etc)</exception>
        /// <exception cref="WebException">On connection or protocol related errors (except for the protocol errors sent by the Invisible Collector)</exception>
        /// <seealso cref="SetNewDebtAsync"/>
        public async Task <IList <Debt> > GetCustomerDebtsAsync(string customerId)
        {
            const string customerDebtsPath = "debts";

            _logger.LogDebug("Making a request to get customer debts for customer ID: {Id}", customerId);
            var id  = HttpUriBuilder.NormalizeUriComponent(customerId);
            var ret = await MakeBodylessRequestAsync <List <Debt> >("GET", CustomersEndpoint, id, customerDebtsPath);

            _logger.LogDebug("Received for customer with id: {Id} debts: {Models}", customerId, ret.StringifyList());
            return(ret);
        }
Example #12
0
        /// <summary>
        /// Updates the customer's attributes
        /// </summary>
        /// <remarks>
        /// <para>Any previously existing attributes won't be deleted, existing attributes will be updated and not-previously existing attributes will be created.</para>
        /// </remarks>
        /// <param name="customerId">The ID of the customer whose information is to be retrieved. It can be the 'gid' or 'externalId' of the customer (or just use <see cref="Customer.RoutableId"/>)</param>
        /// <param name="attributes">The attributes to be set</param>
        /// <returns>All of the customer's up-to-date updated attributes</returns>
        /// <exception cref="IcException">On bad json (sent or received) and when the server rejects the request (conflict, bad request, invalid parameters, etc)</exception>
        /// <exception cref="WebException">On connection or protocol related errors (except for the protocol errors sent by the Invisible Collector)</exception>
        /// <seealso cref="GetCustomerAttributesAsync"/>
        public async Task <IDictionary <string, string> > SetCustomerAttributesAsync(string customerId,
                                                                                     IDictionary <string, string> attributes)
        {
            var id = HttpUriBuilder.NormalizeUriComponent(customerId);

            _logger.LogDebug("Making a request to set or update the customer's with ID: {Id} attributes: {Attributes}", customerId, attributes.StringifyDictionary());
            var ret = await MakeRequestAsync <Dictionary <string, string>, string>("POST", attributes, CustomersEndpoint, id,
                                                                                   CustomersAttributesPath);

            _logger.LogDebug("Updated for the customer with ID: {Id} attributes: {Attributes}", customerId, ret.StringifyDictionary());
            return(ret);
        }
 protected HttpBuilderSettings()
 {
     UriBuilder                 = new HttpUriBuilder();
     Items                      = new Dictionary <string, object>();
     HandlerRegister            = new HttpHandlerRegister();
     NormalizedUriQuery         = new NormalizedUriQueryCollection();
     Method                     = HttpMethod.Get;
     CompletionOption           = HttpCompletionOption.ResponseContentRead;
     SuppressCancellationErrors = false;
     MediaType                  = "application/json";
     ContentEncoding            = Encoding.UTF8;
     ExceptionFactory           = ObjectHelpers.CreateHttpException;
 }
        public async Task<ICodeFlowAuthenticationInfo> TryAuthenticateWithRedirectUri(string redirectUri)
        {
            var start = RedirectUri + "?code=";
            if (!redirectUri.StartsWith(start))
                return null;
            var builder = new HttpUriBuilder(redirectUri);
            var code = builder.QueryStringParameters.FirstOrDefault(z => z.Key == "code");
            if (code.Value.IsNullOrWhiteSpace())
                return null;

            var body =
                $"client_id={this.ClientId}&redirect_uri={RedirectUri}&client_secret={this.ClientSecret}&code={code.Value}&grant_type=authorization_code";
            var result = await RedeemAccessTokenAsync(body);
            return result.Result;
        }
        public void WithQuery_correct()
        {
            const string BaseUri = "http://host.domain";
            var          queries = new Dictionary <string, string>
            {
                { "company", "123" },
                { "a", "" }
            };

            var builder = new HttpUriBuilder(BaseUri)
                          .WithQuery(queries);

            foreach (var pair in queries)
            {
                StringAssert.Contains(pair.Key, builder.BuildUri().Query);
                StringAssert.Contains("=" + pair.Value, builder.BuildUri().Query);
            }
        }
Example #16
0
        private Uri BuildGetAllUri(string phoneNumber, string accountReference, int pageNumber, int pageSize)
        {
            var requestUrl = _baseUrl + "v1.0/optouts";

            var builder = HttpUriBuilder.Create(requestUrl)
                          .WithParameter("startIndex", GetStartIndex(pageNumber, pageSize).ToString())
                          .WithParameter("count", pageSize.ToString());

            if (accountReference != null)
            {
                builder.WithParameter("accountreference", accountReference);
            }

            if (phoneNumber != null)
            {
                builder.WithParameter("from", phoneNumber);
            }

            return(builder.Build());
        }
        public ITokenFlowAuthenticationInfo TryAuthenticateWithRedirectUri(string redirectUri)
        {
            if (!this.IsRedirectUriVaild(redirectUri))
                return null;

            // 'access_token' 'authentication_token' 'token_type' 'expires_in' 'scope' 'user_id'
            var builder = new HttpUriBuilder(redirectUri);
            var result = new AuthenticationInfo();
            foreach (var kvp in builder.QueryStringParameters)
            {
                switch (kvp.Key)
                {
                    case "access_token":
                        result.AccessToken = kvp.Value;
                        break;
                    case "token_type":
                        result.TokenType = kvp.Value;
                        break;
                    case "expires_in":
                        int i;
                        if (int.TryParse(kvp.Value, out i))
                            result.ExpiresIn = i;
                        break;
                    case "scope":
                        result.Scope = kvp.Value;
                        break;
                    case "authentication_token":
                        result.AuthenticationToken = kvp.Value;
                        break;
                    case "user_id":
                        result.UserId = kvp.Value;
                        break;

                    default:
                        break;
                }
            }

            return result.AccessToken.IsNullOrWhiteSpace() ? null : result;
        }