Ejemplo n.º 1
0
        public async Task <RestResponse <TReturnMessage> > PutAsync <TReturnMessage>(ServiceEnum serviceName, string path,
                                                                                     string correlationToken,
                                                                                     object dataObject = null)
            where TReturnMessage : class, new()
        {
            var uri = new Uri($"{_serviceLocator.GetServiceUri(serviceName)}/{path}");

            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer [token]");

            // Pack the correlationToken in the Http header
            _httpClient.DefaultRequestHeaders.Add("x-correlationToken", correlationToken);

            var updatedContent = dataObject != null?JsonConvert.SerializeObject(dataObject) : "{}";

            var response = await _httpClient.PutAsync(uri,
                                                      new StringContent(updatedContent, Encoding.UTF8, "application/json"));

            var result = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                // If unsuccessful, return null payload, error message, and http status code
                return(new RestResponse <TReturnMessage>(null,
                                                         result += $" with correlationId:{correlationToken}",
                                                         response.StatusCode));
            }

            // If successful, return payload and http status code - no message required
            return(new RestResponse <TReturnMessage>(JsonConvert.DeserializeObject <TReturnMessage>(result),
                                                     string.Empty,
                                                     response.StatusCode));
        }
Ejemplo n.º 2
0
        public IQueryable <ServiceProvidedDto> ServicesFiltered(FilterTypeEnum filterType, string filter)
        {
            switch (filterType)
            {
            case FilterTypeEnum.CLIENT:
                return(_supplierRepository.GetAll().Where(x => x.ServiceProvidedClient.Name.Contains(filter)).ProjectTo <ServiceProvidedDto>());

                break;

            case FilterTypeEnum.STATE:
                var resultState = Enum.GetValues(typeof(StatesEnum))
                                  .Cast <StatesEnum>()
                                  .FirstOrDefault(v => v.ToString().Contains(filter));

                return(_supplierRepository.GetAll().Where(x => x.ServiceProvidedClient.State == resultState).ProjectTo <ServiceProvidedDto>());

                break;

            case FilterTypeEnum.CITY:
                return(_supplierRepository.GetAll().Where(x => x.ServiceProvidedClient.City.Contains(filter)).ProjectTo <ServiceProvidedDto>());

                break;

            case FilterTypeEnum.NEIGHBORHOOD:
                return(_supplierRepository.GetAll().Where(x => x.ServiceProvidedClient.Neighborhood.Contains(filter)).ProjectTo <ServiceProvidedDto>());

                break;

            case FilterTypeEnum.SERVICE:
                ServiceEnum result = Enum.GetValues(typeof(ServiceEnum))
                                     .Cast <ServiceEnum>()
                                     .FirstOrDefault(v => v.ToString().Contains(filter));

                return(_supplierRepository.GetAll().Where(x => x.Service == result).ProjectTo <ServiceProvidedDto>());

                break;

            case FilterTypeEnum.MIN_VALUE:
                var resultTryParseMin = decimal.TryParse(filter, out decimal @decimalMin);
                if (resultTryParseMin)
                {
                    return(_supplierRepository.GetAll().Where(x => x.Value > @decimalMin)
                           .ProjectTo <ServiceProvidedDto>());
                }
                break;

            case FilterTypeEnum.MAX_VALUE:
                var resultTryParseMax = decimal.TryParse(filter, out decimal @decimalMax);
                if (resultTryParseMax)
                {
                    return(_supplierRepository.GetAll().Where(x => x.Value < @decimalMax)
                           .ProjectTo <ServiceProvidedDto>());
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(filterType), filterType, null);
            }
            return(_supplierRepository.GetAll().ProjectTo <ServiceProvidedDto>());
        }
Ejemplo n.º 3
0
 public Service GetService(ServiceEnum serviceName)
 {
     lock (syncRoot)
     {
         return(serviceSet.FirstOrDefault(s => s.ServiceName == serviceName));
     }
 }
Ejemplo n.º 4
0
 protected Service(ServiceEnum serviceName)
 {
     ServiceName = serviceName;
     Message     = string.Empty;
     Status      = ServiceStatus.Running.GetStringStatus();
     log         = LogManager.GetLogger(typeof(Service));
 }
Ejemplo n.º 5
0
        public async Task <TReturnMessage> PutAsync <TReturnMessage>(ServiceEnum serviceName, string path,
                                                                     object dataObject = null)
            where TReturnMessage : class, new()
        {
            var result = string.Empty;

            var uri = new Uri($"{_serviceLocator.GetServiceUri(serviceName)}/{path}");

            var content = dataObject != null?JsonConvert.SerializeObject(dataObject) : "{}";

            // Execute delegatge. In the event of a retry, this block will re-execute.
            var httpResponse = await HttpInvoker(async() =>
            {
                var response =
                    await _client.PutAsync(uri, new StringContent(content, Encoding.UTF8, "application/json"));
                response.EnsureSuccessStatusCode();

                if (!response.IsSuccessStatusCode)
                {
                    var ex = new HttpRequestException($"{response.StatusCode} -- {response.ReasonPhrase}");
                    // Stuff the Http StatusCode in the Data collection with key 'StatusCode'
                    ex.Data.Add("StatusCode", response.StatusCode);
                    throw ex;
                }

                result = await response.Content.ReadAsStringAsync();
                return(response);
            });

            return(JsonConvert.DeserializeObject <TReturnMessage>(result));
        }
Ejemplo n.º 6
0
        public async Task GetMonitorService(string serviceName)
        {
            ServiceEnum     serviceEnum = (ServiceEnum)Enum.Parse(typeof(ServiceEnum), serviceName.ToUpper());
            ILiveBotMonitor monitor     = _monitors.Where(m => m.ServiceType == serviceEnum).First();

            await ReplyAsync($"Loaded: {monitor.ServiceType}");
        }
Ejemplo n.º 7
0
        public void RequestStart(ServiceEnum service, string algo, bool isMinimizedToTray)
        {
            PriceEntryBase entry = null;

            foreach (PriceEntryBase priceEntry in _priceEntries)
            {
                if (priceEntry.AlgoName == algo)
                {
                    entry = priceEntry;
                    if (priceEntry.ServiceEntry.ServiceEnum == service)
                    {
                        break;
                    }
                }
            }

            if (entry == null)
            {
                RunBestAlgo(isMinimizedToTray);
            }
            else
            {
                StartMiner(entry, isMinimizedToTray);
            }
        }
Ejemplo n.º 8
0
        public async Task <TReturnMessage> GetAsync <TReturnMessage>(ServiceEnum serviceName, string path)
            where TReturnMessage : class, new()
        {
            // Configure call
            HttpResponseMessage response;
            var result = string.Empty;
            var uri    = new Uri($"{_serviceLocator.GetServiceUri(serviceName)}/{path}");

            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            // _client.DefaultRequestHeaders.Add("Authorization", "Bearer [token]");

            // Execute delegatge. In the event of a retry, this block will re-execute.
            var httpResponse = await HttpInvoker(async() =>
            {
                // Here is actual call to target service
                response = await _client.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    var ex = new HttpRequestException($"{response.StatusCode} -- {response.ReasonPhrase}");
                    // Stuff the Http StatusCode in the Data collection with key 'StatusCode'
                    ex.Data.Add("StatusCode", response.StatusCode);
                    throw ex;
                }

                result = await response.Content.ReadAsStringAsync();

                return(response);
            });

            return(JsonConvert.DeserializeObject <TReturnMessage>(result));
        }
Ejemplo n.º 9
0
 public TwitchAuth(ServiceEnum serviceType, string clientId, RefreshResponse refreshResponse)
 {
     ServiceType  = serviceType;
     Expired      = false;
     ClientId     = clientId;
     AccessToken  = refreshResponse.AccessToken;
     RefreshToken = refreshResponse.RefreshToken;
 }
Ejemplo n.º 10
0
 public ServiceHistory(ServiceEnum service, TimeSpan window, double percentile, decimal iqrMultiplier)
 {
     Service        = service;
     _statWindow    = window;
     _percentile    = percentile;
     _iqrMultiplier = iqrMultiplier;
     PriceList      = new Dictionary <PriceEntryBase, List <PriceStat> >();
 }
Ejemplo n.º 11
0
 public TwitchUser(string baseURL, ServiceEnum serviceType, StreamUser user) : base(baseURL, serviceType)
 {
     Id          = user.SourceID;
     Username    = user.Username;
     DisplayName = user.DisplayName;
     AvatarURL   = user.AvatarURL;
     ProfileURL  = user.ProfileURL;
 }
Ejemplo n.º 12
0
 public TwitchUser(string baseURL, ServiceEnum serviceType, User user) : base(baseURL, serviceType)
 {
     Id          = user.Id;
     Username    = user.Login;
     DisplayName = user.DisplayName;
     AvatarURL   = user.ProfileImageUrl;
     ProfileURL  = $"{BaseURL}/{Username}";
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Constructor with definition provider
 /// </summary>
 /// <param name="service">Service provider</param>
 /// <param name="checkInternetConnection">Checks for internet connection</param>
 public AddressService(ServiceEnum service, bool checkInternetConnection = false)
 {
     Service = service;
     this.CheckInternetConnection = checkInternetConnection;
     ServicesUri = new Dictionary <ServiceEnum, string>();
     ServicesUri.Add(ServiceEnum.Postmon, "http://api.postmon.com.br/v1/cep/{0}");
     ServicesUri.Add(ServiceEnum.ViaCEP, "http://viacep.com.br/ws/{0}/json");
     ServicesUri.Add(ServiceEnum.TargetLock, "https://api.targetlock.io/v1/post-code/{0}");
 }
Ejemplo n.º 14
0
 public FickleType(ServiceEnum serviceEnum, ServiceModel serviceModel, bool nullable = false, bool byRef = false, bool isPrimitive = false)
 {
     this.serviceModel = serviceModel;
     this.ServiceEnum  = serviceEnum;
     this.Nullable     = nullable;
     this.name         = serviceEnum.Name;
     this.byRef        = byRef;
     this.isPrimitive  = isPrimitive;
 }
Ejemplo n.º 15
0
 public void Add(ServiceEnum serviceName)
 {
     lock (syncRoot)
     {
         if (serviceSet.All(s => s.ServiceName != serviceName))
         {
             serviceSet.Add(Service.CreateNewService(serviceName));
         }
     }
 }
Ejemplo n.º 16
0
 public void DropAttempt(ServiceEnum serviceName)
 {
     lock (syncRoot)
     {
         var service = serviceSet.FirstOrDefault(s => s.ServiceName == serviceName);
         if (service != null)
         {
             service.Attempt = 0;
         }
     }
 }
Ejemplo n.º 17
0
        public async Task <bool> DeleteAsync(ServiceEnum serviceName, string path)
        {
            var uri = new Uri($"{_serviceLocator.GetServiceUri(serviceName)}/{path}");
            //_logger.LogInformation("[INFO] DELETE Uri:" + uri);

            var response = await _client.DeleteAsync(uri);

            response.EnsureSuccessStatusCode();

            return(response.IsSuccessStatusCode);
        }
Ejemplo n.º 18
0
 public void Remove(ServiceEnum serviceName)
 {
     lock (syncRoot)
     {
         var service = serviceSet.FirstOrDefault(s => s.ServiceName == serviceName);
         if (service != null)
         {
             serviceSet.Remove(service);
         }
     }
 }
Ejemplo n.º 19
0
 public TwitchStream(string baseURL, ServiceEnum serviceType, Stream stream, ILiveBotUser user, ILiveBotGame game) : base(baseURL, serviceType)
 {
     UserId       = user.Id;
     User         = user;
     Id           = stream.Id;
     Title        = stream.Title;
     StartTime    = stream.StartedAt;
     GameId       = game.Id;
     Game         = game;
     ThumbnailURL = stream.ThumbnailUrl;
     StreamURL    = $"{User.ProfileURL}";
 }
Ejemplo n.º 20
0
 public TwitchStream(string baseURL, ServiceEnum serviceType, Stream stream) : base(baseURL, serviceType)
 {
     UserId       = stream.UserId;
     User         = null;
     Id           = stream.Id;
     Title        = stream.Title;
     StartTime    = stream.StartedAt;
     GameId       = stream.GameId;
     Game         = null;
     ThumbnailURL = stream.ThumbnailUrl;
     StreamURL    = $"{baseURL}/{stream.UserName.Replace(" ", "")}";
 }
Ejemplo n.º 21
0
        public virtual Expression Build(ServiceEnum serviceEnum)
        {
            var expressions = serviceEnum.Values.Select(value => Expression.Assign(Expression.Variable(typeof(long), value.Name), Expression.Constant(value.Value))).Cast <Expression>().ToList();

            var attributes = new Dictionary <string, string>();

            if (serviceEnum.Flags != null)
            {
                attributes["flags"] = "true";
            }

            return(new TypeDefinitionExpression(this.GetTypeFromName(serviceEnum.Name), null, expressions.ToGroupedExpression(), true, new ReadOnlyDictionary <string, string>(attributes), null));
        }
Ejemplo n.º 22
0
 public bool ShouldRestart(ServiceEnum serviceName)
 {
     lock (syncRoot)
     {
         var service = serviceSet.FirstOrDefault(s => s.ServiceName == serviceName);
         if (service != null)
         {
             service.Attempt++;
             return(service.Attempt == RestartAttempt);
         }
         return(false);
     }
 }
Ejemplo n.º 23
0
        public void SetFactoryCommand(ServiceEnum service, string command)
        {
            var temp = Factories.Find(x => x.ServiceName.Equals(service));

            if (temp == null)
            {
                throw new ArgumentException("Service {0} did not match any classes", service.ToString());
            }

            temp.SetCommands(new List <object> {
                command
            });
        }
Ejemplo n.º 24
0
        public bool HasAtempt(ServiceEnum serviceName)
        {
            lock (syncRoot)
            {
                var service = serviceSet.FirstOrDefault(s => s.ServiceName == serviceName);
                if (service == null)
                {
                    return(false);
                }

                return(!(service.Attempt == AttemptsLimit || (service.Attempt + 1) % 1000 == 0));
            }
        }
Ejemplo n.º 25
0
        private static void HasAttempt(ServiceEnum serviceName)
        {
            log.DebugFormat("HasAttempt: service = {0}", serviceName);
            if (serviceRepository.ShouldRestart(serviceName))
            {
                log.DebugFormat("HasAttempt: ShouldRestart is true, service = {0}", serviceName);
                var healthCheckServiceManager = new HealthCheckServiceManager(ServiceRepository);
                healthCheckServiceManager.StopService(serviceName);
                Thread.Sleep(5);
                healthCheckServiceManager.StartService(serviceName);
                return;
            }
            if (!serviceRepository.HasAtempt(serviceName))
            {
                // Send sms and e-mail about service/site/zone
                var service = ServiceRepository.GetService(serviceName);
                log.ErrorFormat("There are some problem with serviceName = {0}, status = {1}, Message = {2}.",
                                serviceName, service.Status, service.Message);

                var healthCheckSettings = HealthCheckSettingsAccessor.GetHealthCheckSettings();

                if (healthCheckSettings.SendNotify)
                {
                    if (healthCheckSettings.SendEmail)
                    {
                        log.Debug("Send email notification.");
                        SendEmail(String.Format("Onlyoffice {0} problem.", serviceName),
                                  String.Format(HealthCheckResource.ServiceProblem, serviceName, service.Status, service.Message),
                                  healthCheckSettings);
                    }
                    else
                    {
                        log.Debug("Email isn't sent. Email notification disabled.");
                    }
                    if (healthCheckSettings.SendSms)
                    {
                        log.Debug("Send SMS notification.");
                        SendSms(String.Format(HealthCheckResource.ServiceProblem,
                                              serviceName, service.Status, service.Message), healthCheckSettings);
                    }
                    else
                    {
                        log.Debug("SMS isn't sent. SMS notification disabled.");
                    }
                }
                else
                {
                    log.Debug("Notification isn't sent. Notification disabled.");
                }
            }
        }
Ejemplo n.º 26
0
        public async Task <bool> DeleteAsync(ServiceEnum serviceName, string path, string correlationToken)
        {
            var uri = new Uri($"{_serviceLocator.GetServiceUri(serviceName)}/{path}");

            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer [token]");

            // Pack the correlationToken in the Http header
            _httpClient.DefaultRequestHeaders.Add("x-correlationToken", correlationToken);

            var response = await _httpClient.DeleteAsync(uri);

            return(response.IsSuccessStatusCode);
        }
Ejemplo n.º 27
0
        internal static ServiceEnum ServiceSwitch(List <ServiceEnum> services)
        {
            var specificService = new ServiceEnum();

            foreach (var service in services)
            {
                switch (service)
                {
                case ServiceEnum.Ideal:
                    specificService = ServiceEnum.Ideal;
                    break;
                }
            }
            return(specificService);
        }
Ejemplo n.º 28
0
 public TwitchGame(string baseURL, ServiceEnum serviceType, StreamGame game = null) : base(baseURL, serviceType)
 {
     if (game == null)
     {
         Id           = "0";
         Name         = "[Not Set]";
         ThumbnailURL = "";
     }
     else
     {
         Id           = game.SourceId;
         Name         = game.Name;
         ThumbnailURL = game.ThumbnailURL;
     }
 }
 public ServiceStatus GetStatus(ServiceEnum serviceName)
 {
     log.DebugFormat("GetStatus: serviceName = {0}", serviceName);
     try
     {
         using (var xplatServiceController = XplatServiceController.GetXplatServiceController(serviceName))
         {
             return(xplatServiceController.GetServiceStatus());
         }
     }
     catch (Exception ex)
     {
         log.ErrorFormat("Error on GetStatus. {0} {1} {2}", ex.ToString(), ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : string.Empty);
         return(ServiceStatus.NotFound);
     }
 }
Ejemplo n.º 30
0
        private void btnReloadConfig_Click(object sender, EventArgs e)
        {
            MiningModeEnum originalMode = _engine.MiningMode;
            ServiceEnum    service      = ServiceEnum.Manual;
            string         algo         = string.Empty;

            if (_engine.CurrentPriceEntry != null)
            {
                service = _engine.CurrentPriceEntry.ServiceEntry.ServiceEnum;
                algo    = _engine.CurrentPriceEntry.AlgoName;
            }

            _engine.Cleanup();
            _engine = new MiningEngine
            {
                WriteConsoleAction = WriteConsole,
                WriteRemoteAction  = WriteRemote
            };

            if (!_engine.LoadConfig())
            {
                MessageBox.Show("Something went wrong with reloading your configuration file. Check for errors.",
                                "Error loading conf", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            dgServices.DataSource = new SortableBindingList <IService>(_engine.Services);
            dgPrices.DataSource   = new SortableBindingList <PriceEntryBase>(_engine.PriceEntries);

            _engine.MiningMode = originalMode;

            _engine.LoadExchangeRates();
            RunCycle();
            UpdateButtons();
            UpdateGrid();

            HistoryChart historyChart = tabHistory.Controls["historyChart"] as HistoryChart;

            if (historyChart != null)
            {
                historyChart.UpdateChart();
            }

            if (originalMode == MiningModeEnum.Manual)
            {
                _engine.RequestStart(service, algo, IsMinimizedToTray);
            }
        }