예제 #1
0
 public IHttpActionResult GetLocations([FromUri] string country)
 {
     try
     {
         return(Ok(_countryService.GetCities(country)));
     }
     catch (Exception exp)
     {
         _logger.Error("WeatherController failed at GetLocations", exp);
         return(BadRequest());
     }
 }
예제 #2
0
        private async Task ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
        {
            try
            {
                CheckEventRequeueLimit(e);
                var content = System.Text.Encoding.UTF8.GetString(e.Body);
                TryGetMessageType(e, out var messageType);
                await HandleMessage(content, messageType);

                _channel.BasicAck(e.DeliveryTag, false);
            }
            catch (EventRequeueLimitReachedException ex)
            {
                _logger.Error(ex.Message, ex);
                _channel.BasicReject(e.DeliveryTag, false);
            }
            catch (Exception ex)
            {
                _logger.Error($"Unable to process event '{e.DeliveryTag}': {ex.Message}", ex);
                _channel.BasicReject(e.DeliveryTag, true);
            }
        }
예제 #3
0
 private bool ConnectToQueue()
 {
     try
     {
         var factory = new ConnectionFactory
         {
             HostName = _queueConnectionSettings.Value.HostName,
             Port     = _queueConnectionSettings.Value.Port,
             UserName = _queueConnectionSettings.Value.Username,
             Password = _queueConnectionSettings.Value.Password
         };
         _connection = factory.CreateConnection();
         return(true);
     }
     catch (Exception ex)
     {
         _logger.Error($"Unable to connect to Response Queue: {ex.Message}", ex);
         return(false);
     }
 }
예제 #4
0
        private Country GetWeather(IApiLogger <WeatherService> logger, string countryName, string cityName)
        {
            /* Work through available weather services until we find data.
             * Similar approach to factory pattern, however, intention in here to provide more flexibility to
             * add new clients later, through DI, without modifying the existing code
             * */
            foreach (var weatherService in _weatherServiceClients)
            {
                try
                {
                    var weather = weatherService.GetWeather(countryName, cityName);
                    if (weather != null)
                    {
                        return(weather);
                    }
                }
                catch (Exception exp)
                {
                    logger.Error("WeatherService failed at GetWeather", exp);
                }
            }

            return(null);
        }
예제 #5
0
        public T InvokeApi <T>(string url, ApiRequestData data, IApiLogger logger)
        {
            string value = "";

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;

                request.Timeout = data.requestTimeout;

                // headers
                if (data.acceptHeader != null)
                {
                    request.Accept = data.acceptHeader;
                }

                foreach (KeyValuePair <string, string> header in data.headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }

                request.Method = data.method.ToString();

                //處理POST資料
                if (data.method == ApiRequestData.Method.POST ||
                    data.method == ApiRequestData.Method.PUT)
                {
                    var paramBytes = Encoding.UTF8.GetBytes(data.postData);


                    request.ContentType   = data.contentTypeText;
                    request.ContentLength = paramBytes.Length;
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(paramBytes, 0, paramBytes.Length);
                    }
                }

                logger.Info($"{url} req: {data.postData}");

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    //HttpStatusCode=200才算呼叫成功
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            value = sr.ReadToEnd();
                        }
                    }
                    else
                    {
                        throw new Exception(((int)response.StatusCode).ToString() + ":" + response.StatusDescription);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error($"invokeApi {ex.ToString()}");
            }

            logger.Info($"{url} resp: {value}");

            return(JsonConvert.DeserializeObject <T>(value));
        }