Exemple #1
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var context = new Context($"Cache-{Guid.NewGuid()}", new Dictionary <string, object>
            {
                { "authClient", authClient }
            });


            return(await Policies.TokenRefreshPolicy.ExecuteAsync(async (ctx, ct) =>
            {
                if (request.Headers.Contains("Authorization"))
                {
                    request.Headers.Remove("Authorization");
                }

                var token = await authClient.GetToken();
                request.Headers.Add("Authorization", $"Bearer {token}");

                return await base.SendAsync(request, ct);
            }, context, cancellationToken));
        }
        /// <summary>
        /// Реализует выполнение работы по имитации действий пользователей.
        /// </summary>
        /// <param name="userName">Имя пользователя.</param>
        /// <param name="baseAdress">Адрес сервиса.</param>
        /// <param name="startDate">Дата добавления координат, из команды.</param>
        private void Work(int userName, string baseAdress, DateTime startDate)
        {
            try
            {
                UserDto user;

                // Используем протобуф для четных пользователей.
                var useProtobuf = (userName % 2) == 0;

                using (var client = new HttpClient())
                {
                    if (useProtobuf)
                    {
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
                    }

                    var createQquery = string.Format(_queryFormat, userName);
                    client.BaseAddress = new Uri(new Uri(baseAdress), createQquery);

                    var response = client.GetAsync(client.BaseAddress).Result;

                    if (!response.IsSuccessStatusCode)
                    {
                        return;
                    }

                    var data = response.Content.ReadAsAsync(_returnType, new MediaTypeFormatter[] { FormatterFactory.CreateJsonFormatter(), FormatterFactory.CreateProtoBufFormatter() }).Result;

                    user = (UserDto)data;

                    Console.WriteLine(user);
                    Logger.Trace(user.ToString());
                }

                var token = AuthClient.GetToken(baseAdress, user.Name, user.Password).Result;

                // Случайные числа для координат.
                var random = new Random(user.Name);
                var lat    = random.NextDouble();
                var lng    = random.NextDouble();

                while (true)
                {
                    var parameters = new CoordinatesDto
                    {
                        Date       = startDate,
                        Latitude   = (decimal)((lat - random.NextDouble()) * 90),
                        Longtitude = (decimal)((lng - random.NextDouble()) * 180),
                        UserId     = user.Id
                    };

                    using (var client = new HttpClient())
                    {
                        if (useProtobuf)
                        {
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
                        }

                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                        client.BaseAddress = new Uri(new Uri(baseAdress), _coordsPutFormat);
                        var response = client.PutAsync(client.BaseAddress, parameters, useProtobuf ? (MediaTypeFormatter)FormatterFactory.CreateProtoBufFormatter() : FormatterFactory.CreateJsonFormatter()).Result;

                        if (!response.IsSuccessStatusCode)
                        {
                            return;
                        }

                        var data = response.Content.ReadAsAsync(_coordsReturnType, new MediaTypeFormatter[] { FormatterFactory.CreateJsonFormatter(), FormatterFactory.CreateProtoBufFormatter() }).Result;

                        if ((int)data == 1)
                        {
                            var message = string.Format("Добавлена запись координат, пользователь {0}.", userName);
#if DEBUG
                            Console.WriteLine(message);
#endif
                            Logger.Trace(message);
                        }
                    }

                    Thread.Sleep(1000);
                }
            }
            catch (ThreadAbortException) {}
            catch (AggregateException ex)
            {
                Console.WriteLine(ex.InnerException.Message);
                Logger.Error("Ошибка имитации.", ex.InnerException);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Logger.Error("Ошибка имитации.", ex);
            }
        }