Пример #1
0
        public void can_append_trailing_slash()
        {
            var url = new Url("https://www.site.com/a/b/c");

            Assert.AreEqual("https://www.site.com/a/b/c", url.ToString());
            url.AppendPathSegment("/");
            Assert.AreEqual("https://www.site.com/a/b/c/", url.ToString());
            url.AppendPathSegment("///");
            Assert.AreEqual("https://www.site.com/a/b/c///", url.ToString());
        }
Пример #2
0
        public async Task <ItemsResponse> LookupByGetAsync(params string[] codes)
        {
            var items = await _apiBaseUrl
                        .AppendPathSegment("lookup")
                        .SetQueryParam("upc", string.Join(",", codes))
                        .WithClient(_client)
                        .GetJsonAsync <ItemsResponse>();

            return(items.AssignRateLimit(_rateLimitResponse));
        }
Пример #3
0
        public void SetApiUrl(IEnumerable <string> baseUrls)
        {
            var timeout = FlurlHttp.GlobalSettings.Timeout;

            FlurlHttp.GlobalSettings.Timeout = TimeSpan.FromSeconds(1);

            foreach (var baseUrl in baseUrls)
            {
                var apiUrl = new Url(baseUrl);

                if (apiUrl.IsValid())
                {
                    try
                    {
                        apiUrl.AppendPathSegment("ws/check-version")
                        .GetAsync()
                        .Wait();
                        ApiUrl = new Url(baseUrl);
                        break;
                    }
                    catch (FlurlHttpException e)
                    {
                        if (e.Call.Completed)
                        {
                            ApiUrl = new Url(baseUrl);
                            break;
                        }
                    }
                    catch (Exception) { }
                }
            }

            FlurlHttp.GlobalSettings.Timeout = timeout;
        }
Пример #4
0
 public IEnumerable <MonthReportDto> GetMonthReport(DateTime dateStart, DateTime dateEnd)
 {
     return(Url.AppendPathSegment("report/GetMonthReport")
            .SetQueryParam("dateStart", dateStart)
            .SetQueryParam("dateEnd", dateEnd)
            .GetJsonAsync <IEnumerable <MonthReportDto> >().Result);
 }
Пример #5
0
        public AzureLogHandler(ILogFactory logFactory, ReaderSettings settings, IReloadingManager <DbSettings> dbsettings) :
            base(TimeSpan.FromMinutes(1), logFactory, nameof(AzureLogHandler))
        {
            _logFactory = logFactory;
            _exclude    = settings.ExcludeTables?.ToList() ?? new List <string>(1);
            _exclude.Add("LogReaderLog");
            _log        = logFactory.CreateLog(this);
            _settings   = settings;
            _dbsettings = dbsettings;

            var url = new Url(settings.LogAggregatorHost);

            url.AppendPathSegment("api/log-collector/log");
            _aggregatorUrl = url.ToString();

            var cri = Environment.GetEnvironmentVariable("COUNT_READ_ITERATIONS");
            var bs  = Environment.GetEnvironmentVariable("BATCH_SIZE");

            if (!string.IsNullOrEmpty(cri))
            {
                _countReadIterations = int.Parse(cri);
            }

            if (!string.IsNullOrEmpty(bs))
            {
                _batchSize = int.Parse(bs);
            }

            Console.WriteLine($"COUNT_READ_ITERATIONS: {_countReadIterations}");
            Console.WriteLine($"BATCH_SIZE: {_batchSize}");
        }
Пример #6
0
 public IEnumerable <CheckDto> GetByPeriod(DateTime DateStart, DateTime DateEnd)
 {
     return(Url.AppendPathSegment("Check/GetByPeriod")
            .SetQueryParam("DateStart", DateStart)
            .SetQueryParam("DateEnd", DateEnd)
            .GetJsonAsync <IEnumerable <CheckDto> >().Result);
 }
Пример #7
0
        public void SetApiUrl(IEnumerable <string> baseUrls)
        {
            var timeout = FlurlHttp.GlobalSettings.Timeout;

            FlurlHttp.GlobalSettings.Timeout = TimeSpan.FromSeconds(5);

            foreach (var baseUrl in baseUrls)
            {
                var apiUrl = new Url(baseUrl);

                if (apiUrl.IsValid())
                {
                    try
                    {
                        apiUrl.AppendPathSegment("ws/web-service-version")
                        .AllowAnyHttpStatus()
                        .GetAsync()
                        .Wait();
                        ApiUrl = new Url(baseUrl);
                        break;
                    }
                    catch (Exception) { }
                }
            }

            FlurlHttp.GlobalSettings.Timeout = timeout;
        }
Пример #8
0
        private Url GetUrl(string path)
        {
            var url = new Url(_baseAddr);

            url.AppendPathSegment(path);
            return(url);
        }
Пример #9
0
 public IEnumerable <RecordDto> GetByPeriod(DateTime dateStart, DateTime dateEnd)
 {
     return(Url.AppendPathSegment("record/GetByPeriod")
            .SetQueryParam("dateStart", dateStart)
            .SetQueryParam("dateEnd", dateEnd)
            .GetJsonAsync <IEnumerable <RecordDto> >().Result);
 }
Пример #10
0
        /// <summary>
        /// Builds an authenticated request.
        /// </summary>
        /// <param name="path">The endpoint's path suffix.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <PreparedRequest> PrepareRequest(string path, CancellationToken cancellationToken)
        {
            Url endpoint = await GetEndpoint(cancellationToken).ConfigureAwait(false);

            endpoint.AppendPathSegment(path);

            return(PrepareRequest(endpoint, cancellationToken));
        }
        /// <summary>
        /// Lists all subnets associated with the account.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>
        /// A collection of subnet resources associated with the account.
        /// </returns>
        public virtual async Task <PreparedRequest> ListSubnetsAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            Url endpoint = await Endpoint.GetEndpoint(cancellationToken).ConfigureAwait(false);

            return(endpoint
                   .AppendPathSegment("subnets")
                   .Authenticate(AuthenticationProvider)
                   .PrepareGet(cancellationToken));
        }
Пример #12
0
        public PriceCostDto UpdatePriceCost(MonthReportDto monthReport, int year, int month)
        {
            var resp = Url.AppendPathSegment("report/UpdatePriceCost")
                       .SetQueryParam("year", year)
                       .SetQueryParam("month", month)
                       .PostJsonAsync(monthReport)
                       .ReceiveJson <PriceCostDto>();

            return(resp.Result);
        }
        private IRequest AddUrlSegment(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            url.AppendPathSegment(value);
            return(this);
        }
        public static async Task <ICommandResult> RunActivity(
            [ActivityTrigger] IDurableActivityContext functionContext)
        {
            if (functionContext is null)
            {
                throw new ArgumentNullException(nameof(functionContext));
            }

            var(provider, message) = functionContext.GetInput <(ProviderDocument, ProviderCommandMessage)>();

            var providerUrl = new Url(provider.Url?.Trim());

            if (!providerUrl.Path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                providerUrl = providerUrl.AppendPathSegment("api/command");
            }

            try
            {
                ICommandResult commandResult;

                try
                {
                    commandResult = await providerUrl
                                    .AppendPathSegment(message.CommandId)
                                    .WithHeader("x-functions-key", provider.AuthCode)
                                    .GetJsonAsync <ICommandResult>()
                                    .ConfigureAwait(false);
                }
                catch (FlurlHttpException postException) when(postException.Call.HttpStatus == HttpStatusCode.Unauthorized)
                {
                    throw new RetryCanceledException($"Provider '{provider.Id}' failed: {postException.Message}", postException);
                }

                return(commandResult);
            }
            catch (Exception exc) when(!exc.IsSerializable(out var serializableExc))
            {
                throw serializableExc;
            }
        }
    }
        public ChatConnectionWebSocket(Url baseUrl)
        {
            _hubConnection = new HubConnectionBuilder()
                             .WithUrl(baseUrl.AppendPathSegment("/chathub"))
                             .Build();

            _hubConnection.On <ChatMessage>("ReceiveMessage", (message) =>
            {
                this.MessageReceived?.Invoke(this, new ChatMessageEventArgs(message));
            });
        }
Пример #16
0
        public static async Task <JsonDocument> UpdateWorkItemByIdAsync(Url organization, int workitemId, object patchOperation, string pat)
        {
            // PATCH https://dev.azure.com/fabrikam/_apis/wit/workitems/{id}?api-version=6.1-preview.3
            var queryResponse = await organization
                                .AppendPathSegment($"_apis/wit/workitems/{workitemId}")
                                .SetQueryParam("api-version", "6.0")
                                .WithHeader("Content-Type", "application/json-patch+json")
                                .WithBasicAuth(string.Empty, pat)
                                .PatchJsonAsync(patchOperation);

            return(JsonDocument.Parse(await queryResponse.ResponseMessage.Content.ReadAsStringAsync()));
        }
        public static async Task <ICommandResult> RunActivity(
            [ActivityTrigger] IDurableActivityContext functionContext,
            ILogger log)
        {
            if (functionContext is null)
            {
                throw new ArgumentNullException(nameof(functionContext));
            }

            var(provider, message) = functionContext.GetInput <(Provider, ProviderCommandMessage)>();

            var providerUrl = new Url(provider.Url?.Trim());

            if (!providerUrl.Path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                providerUrl = providerUrl.AppendPathSegment("api/command");
            }

            log.LogInformation($"Sending command {message.CommandId} ({message.CommandType}) to {providerUrl}. Payload:{JsonConvert.SerializeObject(message)}");

            try
            {
                var response = await providerUrl
                               .WithHeader("x-functions-key", provider.AuthCode)
                               .WithHeader("x-functions-callback", message.CallbackUrl)
                               .PostJsonAsync(message)
                               .ConfigureAwait(false);

                return(await response.Content
                       .ReadAsJsonAsync <ICommandResult>()
                       .ConfigureAwait(false));
            }
            catch (FlurlHttpException postException) when(postException.Call.HttpStatus == HttpStatusCode.Conflict)
            {
                // there is no need to retry sending the command - the provider reported a conflict, so the command was already sent
                throw new RetryCanceledException($"Provider '{provider.Id}' failed with status code {postException.Call.HttpStatus}", postException);
            }
            catch (FlurlHttpException postException) when(postException.Call.HttpStatus == HttpStatusCode.BadRequest)
            {
                // there is no need to retry sending the command - the provider reported a bad message payload
                throw new RetryCanceledException($"Provider '{provider.Id}' failed with status code {postException.Call.HttpStatus}", postException);
            }
            catch (FlurlHttpException postException) when(postException.Call.HttpStatus == HttpStatusCode.Unauthorized)
            {
                // there is no need to retry sending the command - seems like our auth code became invalid
                throw new RetryCanceledException($"Provider '{provider.Id}' failed with status code {postException.Call.HttpStatus}", postException);
            }
            catch (Exception exc) when(!exc.IsSerializable(out var serializableExc))
            {
                throw serializableExc;
            }
        }
    }
Пример #18
0
        public static Url AppendPathSegmentsRequire(this Url url, params object[] segments)
        {
            foreach (var segment in segments)
            {
                if (segment is string s && string.IsNullOrWhiteSpace(s))
                {
                    throw new ArgumentException("Part of the URL segment is null or whitespace. Check the parameters to the method you are calling and verify none of the arguments are null or whitespace.");
                }

                url.AppendPathSegment(segment);
            }

            return(url);
        }
Пример #19
0
        /// <summary>
        /// This is the basic query function, everything (except the login request) uses this function as a base.
        /// </summary>
        /// <param name="relativeUri">The relative URI to TIDAL's base API</param>
        /// <param name="request">Request object</param>
        /// <param name="countryCode">Country code</param>
        /// <returns>TIDAL Response</returns>
        private async Task <HttpResponseMessage> AsyncQueryAPI(string relativeUri, TidalBaseRequest request, string countryCode)
        {
            if (!this.IsConnected)
            {
                await this.Connect();
            }

            // Apply defaults - if country code is set & valid, apply it on top
            request.SetDefaults(string.IsNullOrWhiteSpace(countryCode) ? this.activeLogin.CountryCode : countryCode);

            // Convert request to JSON and submit request
            var url = new Url(TidalUrls.BaseAPI);

            return(await this.AsyncGet(url.AppendPathSegment(relativeUri.TrimStart('/')), request));
        }
Пример #20
0
        public static async Task <JsonDocument> AddWorkItemCommentAsync(Url organization, string projectId, int workitemId, string comment, string mention, string pat)
        {
            // POST https://dev.azure.com/{organization}/{project}/_apis/wit/workItems/{workItemId}/comments?api-version=6.1-preview.3

            var commentPayload = new
            {
                text = $"<div><a href =\"#\"data-vss-mention=\"version:2.0,63fab158-69d5-4bc4-8a5a-1033f1cf3ee5\">@{mention}</a>&nbsp;{comment}</div>"
            };

            var queryResponse = await organization
                                .AppendPathSegment(projectId)
                                .AppendPathSegment($"_apis/wit/workitems/{workitemId}/comments")
                                .SetQueryParam("api-version", "6.1-preview.3")
                                .WithBasicAuth(string.Empty, pat)
                                .PostJsonAsync(commentPayload);

            return(JsonDocument.Parse(await queryResponse.ResponseMessage.Content.ReadAsStringAsync()));
        }
Пример #21
0
        public async Task <Company> GetCompanyAsync(long registrationNumber)
        {
            var url = new Url(BrregUnitsUrl());

            url.AppendPathSegment(registrationNumber);

            if (registrationNumber <= 0)
            {
                throw new ArgumentException("Invalid value: 'organizationNumber'", nameof(registrationNumber));
            }

            if (!url.IsValid())
            {
                throw new ArgumentException($"Bad url: '{url}'", nameof(url));
            }

            return(await url.GetJsonAsync <Company>());
        }
Пример #22
0
        /// <summary>
        /// Perform multiple requests (GET) to the Server with a single HTTP call asynchronously.
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="ids"></param>
        /// <param name="resources"></param>
        /// <param name="paths"></param>
        /// <returns></returns>
        protected async Task <JToken> GetBatchRequestAsync(string endpoint, IEnumerable <Guid> ids, IEnumerable <string> resources, params string[] paths)
        {
            // Create URL with base resource
            Url url = new Url(endpoint);

            // Concatenate batch segment to use batch request and prepare the list of requests
            url.AppendPathSegments("batch");
            var objectsRequests = new List <ObjectRequest>();

            // Concatenate batch segment to use batch request and prepare the list of requests
            foreach (var id in ids)
            {
                foreach (var r in resources)
                {
                    Url relativeUrl = new Url(id.ToString());
                    relativeUrl.AppendPathSegments(paths); // e.g. "00000000-0000-0000-0000-000000000001/attributes"
                    relativeUrl.AppendPathSegment(r);      // e.g. "00000000-0000-0000-0000-000000000001/attributes/presentValue"
                    // Use the object id concatenated to the resource to uniquely identify each request
                    objectsRequests.Add(new ObjectRequest {
                        Id = id.ToString() + '_' + r, RelativeUrl = relativeUrl
                    });
                }
            }
            JToken responseToken = null;

            try
            {
                // Post the list of requests and return responses as JToken
                var response = await Client.Request(url)
                               .PostJsonAsync(new BatchRequest {
                    Method = "GET", Requests = objectsRequests
                })
                               .ConfigureAwait(false);

                responseToken = JToken.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
            }
            catch (FlurlHttpException e)
            {
                ThrowHttpException(e);
            }
            return(responseToken);
        }
Пример #23
0
        public async Task <ImageResponse> AddImage(Uri uri, string name = null)
        {
            var path = new Url("")
                       .AppendPathSegment("/images")
                       .SetQueryParam("url", uri.AbsoluteUri);
            HttpResponseMessage response;

            if (string.IsNullOrWhiteSpace(name))
            {
                response = await PostAsync(path.ToString(), null);
            }
            else
            {
                path.AppendPathSegment(name);
                response = await PutAsync(path.ToString(), null);
            }
            var json = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <ImageResponse>(json));
        }
Пример #24
0
        /// <summary>
        /// Performs the login request, most importantly, retrieving the Session ID
        /// </summary>
        /// <returns></returns>
        private async Task <HttpResponseMessage> AsyncLogin()
        {
            IntPtr usrPtr   = Marshal.SecureStringToBSTR(this.username);
            string username = Marshal.PtrToStringBSTR(usrPtr);

            IntPtr psdPtr   = Marshal.SecureStringToBSTR(this.password);
            string password = Marshal.PtrToStringBSTR(psdPtr);

            Marshal.ZeroFreeBSTR(usrPtr);
            Marshal.ZeroFreeBSTR(psdPtr);

            var url = new Url(TidalUrls.BaseAPI);

            return(await url
                   .AppendPathSegment(TidalUrls.Login.ToString())
                   .WithHeader(TidalHeaders.ClientTypeToken, TidalNonces.TokenAndroid)
                   .PostUrlEncodedAsync(new Dictionary <string, string> {
                { TidalHeaders.Username, username },
                { TidalHeaders.Password, password },
                { TidalHeaders.ClientUniqueKey, TidalNonces.ClientKey }
            }));
        }
Пример #25
0
        public static async Task <ICommandResult> RunActivity(
            [ActivityTrigger] IDurableActivityContext activityContext)
        {
            if (activityContext is null)
            {
                throw new ArgumentNullException(nameof(activityContext));
            }

            var functionInput = activityContext.GetInput <Input>();

            try
            {
                var providerUrl = new Url(functionInput.Provider.Url?.Trim())
                                  .SetQueryParam("providerId", functionInput.Provider.Id);

                ICommandResult commandResult;

                try
                {
                    commandResult = await providerUrl
                                    .AppendPathSegment(functionInput.CommandMessage.CommandId)
                                    .WithHeader("x-functions-key", functionInput.Provider.AuthCode)
                                    .WithHeader("x-teamcloud-provider", functionInput.Provider.Id)
                                    .GetJsonAsync <ICommandResult>()
                                    .ConfigureAwait(false);
                }
                catch (FlurlHttpException postException) when(postException.Call.HttpStatus == HttpStatusCode.Unauthorized)
                {
                    throw new RetryCanceledException($"Provider '{functionInput.Provider.Id}' failed: {postException.Message}", postException);
                }

                return(commandResult);
            }
            catch (Exception exc) when(!exc.IsSerializable(out var serializableExc))
            {
                throw serializableExc;
            }
        }
Пример #26
0
        private string GetFormatterPropertyValue(PropertyInfo property, object propValue)
        {
            var baseUrl = new Url(_devOpsAddress).AppendPathSegment("/_workitems/edit/");

            if (property.PropertyType == typeof(double))
            {
                var format = "F2";
                if (property.Name.Contains("offset", StringComparison.OrdinalIgnoreCase))
                {
                    format = "P1";
                }
                return(((double)propValue).ToString(format));
            }
            else
            {
                if (property.Name.Equals("id", StringComparison.OrdinalIgnoreCase))
                {
                    var link = $"<a target=\"_blank\" href=\"{baseUrl.AppendPathSegment(propValue)}\">{propValue}</a>";
                    return(link);
                }
                return(propValue?.ToString());
            }
        }
Пример #27
0
 public static Url ById(this Url endpoint, string id)
 {
     return(endpoint.AppendPathSegment(id));
 }
Пример #28
0
 public static Url WithEndpoint(this Url url, Url endpoint)
 {
     return(url.AppendPathSegment(endpoint));
 }
Пример #29
0
 public void Delete(int Id)
 {
     Url.AppendPathSegment("pricecost")
     .SetQueryParam("Id", Id).DeleteAsync();
 }
Пример #30
0
 public PriceCostDto Update(PriceCostDto item)
 {
     return(Url.AppendPathSegment("pricecost")
            .PutJsonAsync(item).ReceiveJson <PriceCostDto>().Result);
 }