Ejemplo n.º 1
0
        public async Task <Dictionary <string, string> > GetStationReferencesAndNamesForRiver(string riverName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(riverName))
                {
                    throw new ArgumentNullException("riverName");
                }

                var refNamePairs           = new Dictionary <string, string>();
                var riverStationsFromCache = (RiverStations)_memoryCache.Get(riverName);

                if (riverStationsFromCache != null)
                {
                    if (riverStationsFromCache.Stations != null && riverStationsFromCache.Stations.Any())
                    {
                        riverStationsFromCache.Stations.ForEach(s => refNamePairs.Add(s.StationReference, s.Label));
                    }
                }
                else
                {
                    var riverNameTokens = riverName.Split(' ');
                    var newRiverName    = (riverNameTokens.Length > 1) ? string.Join("+", riverNameTokens) : riverName;
                    var requestUrl      = string.Format(_config.GetApiRiverStationsUrl(), newRiverName);

                    var responseData = await _externalService.GetAsync(requestUrl);

                    var riverStations = JsonConvert.DeserializeObject <RiverStations>(responseData);

                    if (riverStations != null)
                    {
                        if (riverStations.Stations != null && riverStations.Stations.Any())
                        {
                            // Add data to cache memory
                            _memoryCache.AddOrGetExisting(riverName, riverStations);

                            riverStations.Stations.ForEach(s => refNamePairs.Add(s.StationReference, s.Label));
                        }
                    }
                }

                return(refNamePairs);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex, _config.GetDefaultLoggingPath());
                return(null);
            }
        }
        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="actionExecutedContext">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext?.Exception == null)
            {
                return;
            }


            var type = actionExecutedContext.Exception.GetType();

            Tuple <HttpStatusCode?, Func <Exception, HttpRequestMessage, HttpResponseMessage> > registration = null;

            if (this.Handlers.TryGetValue(type, out registration))
            {
                var statusCode = registration.Item1;
                var handler    = registration.Item2;

                var response = handler(
                    actionExecutedContext.Exception.GetBaseException(),
                    actionExecutedContext.Request
                    );

                // Use registered status code if available
                if (statusCode.HasValue)
                {
                    response.StatusCode = statusCode.Value;
                }

                actionExecutedContext.Response = response;
            }
            else
            {
                // If no exception handler registered for the exception type, fallback to default handler
                actionExecutedContext.Response = DefaultHandler(
                    actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
                    );
            }

            if (actionExecutedContext.Response == null)
            {
                return;
            }

            actionExecutedContext.Response.Headers?.Add("X-BypassError", "True");

            //ignore 404's and 401's
            if (actionExecutedContext.Response.StatusCode == HttpStatusCode.NotFound ||
                actionExecutedContext.Response.StatusCode == HttpStatusCode.Unauthorized)
            {
                return;
            }


            var uri = actionExecutedContext.Request.RequestUri;


            var message = $"Uri: {uri}";

            _logging.LogException(actionExecutedContext.Exception, message);
        }
Ejemplo n.º 3
0
        public async Task <string> GetAsync(string requestUrl)
        {
            try
            {
                var responseData = "";

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("FloodMonitoring")));

                    var response = await client.GetAsync(new Uri(requestUrl));

                    if (response.IsSuccessStatusCode)
                    {
                        responseData = await response.Content.ReadAsStringAsync();
                    }
                }

                return(responseData);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex, _config.GetDefaultLoggingPath());
                return(null);
            }
        }
Ejemplo n.º 4
0
        public void Release(ExecutionTask task)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }
            if (CurrentTask != null)
            {
                if (CurrentTask.Urn != task.Urn)
                {
                    throw new PluginException("taskUrn mismatch");
                }
                if (CurrentTask.State == ExecutionState.Running)
                {
                    throw new PluginException("Can not release running task.");
                }
                CurrentTask = null;
            }

            if (task.State == ExecutionState.Done &&
                task.Arguments.ContainsKey("TemporaryEssence") &&
                task.Arguments["TemporaryEssence"] == "From")
            {
                try
                {
                    DeleteFilesInEssence(task.From);
                }
                catch (Exception e)
                {
                    Logging.LogException(e, "Unable to clean up temp files.", task.Urn);
                }
            }

            task.EndTime = TimeProvider.GetUtcNow();
        }
Ejemplo n.º 5
0
        public string GetDefaultLoggingPath()
        {
            try
            {
                if (AppSettings != null && AppSettings.Any())
                {
                    return(AppSettings.Where(s => s.Key == "defaultLoggingPath").FirstOrDefault().Value);
                }

                return(null);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex, null);
                return(null);
            }
        }
Ejemplo n.º 6
0
        public static void LogException(this ILogging log, System.Exception exception)
        {
            if (exception == null || IDisposedExtensions.IsNullOrDisposed(log))
            {
                return;
            }

            log.LogException(exception);
        }
Ejemplo n.º 7
0
        public static void LogException(this ILogging log, System.Exception exception)
        {
            if (object.ReferenceEquals(exception, null) || IDisposedExtensions.IsNullOrDisposed(log))
            {
                return;
            }

            log.LogException(exception);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Try to login with the auth server.
        /// </summary>
        /// <param name="email">Username</param>
        /// <param name="password">Password</param>
        public void TryLogin(string email, string password)
        {
            //If we haven't already started trying to login...
            if (_loginThread != null && _loginThread.ThreadState != ThreadState.Stopped)
            {
                return;
            }

            try
            {
                var stateInfo = new AuthStateInfo(this, new AuthParams(email, password));
                _loginThread = new Thread(TryLogin);
                _loginThread.Start(stateInfo);
            }
            catch (Exception e)
            {
                _logging.LogException("Authentication", e, "TryLogin", "Caught exception starting login process:");
            }
        }
Ejemplo n.º 9
0
 private void MakeCallback(Job job)
 {
     try
     {
         _callbackService.MakeCallback(job);
     }
     catch (Exception e)
     {
         _logging.LogException(e, $"Callback to  {job.CallbackUrl} failed", job.Urn);
     }
 }
Ejemplo n.º 10
0
        private async Task <int> AddFileDetailsAsync(string name, string description, long size)
        {
            try
            {
                var fileRecord = new UploadedFileDto
                {
                    Name        = name,
                    Description = description,
                    Size        = size
                };

                var fileId = await _baseRepo.AddFileDetailsAsync(fileRecord);

                return(fileId);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex, null);
                return(-1);
            }
        }
Ejemplo n.º 11
0
        private CommandLineViewModel ParseCommandLine(string commandLine)
        {
            try
            {
                var splitter = new Regex("(?:^| )(\"(?:[^\"]+|\"\")*\"|[^ ]*)", RegexOptions.Compiled);
                var argsList = new List <string>();

                foreach (Match match in splitter.Matches(commandLine))
                {
                    if (!string.IsNullOrWhiteSpace(match.Value))
                    {
                        argsList.Add(match.Value.Trim());
                    }
                }

                return(ParseArguments(argsList));
            }
            catch (Exception ex)
            {
                _logger.LogException(ex, _config.GetDefaultLoggingPath());
                return(null);
            }
        }
Ejemplo n.º 12
0
        protected void LogException(Exception e, string methodName, string message, params object[] args)
        {
            if (_logging != null)
            {
                _logging.LogException(ModuleName, e, methodName, message, args);
            }
            else
            {
                InnerSpaceAPI.InnerSpace.Echo(string.Format("Object {0} logging reference null.", ModuleName));

                var exceptionText = string.Format("Message: {0}\nStack Trace: {1}\nInner Exception: {2}",
                                                  e.Message, e.StackTrace, e.InnerException);
                InnerSpaceAPI.InnerSpace.Echo(exceptionText);
            }
        }
        public bool IsValidCurrencyCode(string currencyCode)
        {
            try
            {
                var camelCaseCode = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(currencyCode.ToLower());
                var validCode     = Enum.IsDefined(typeof(CurrencyCode), camelCaseCode);

                return(validCode);
            }
            catch (Exception ex)
            {
                _logger.LogException(ex, null);
                return(false);
            }
        }
Ejemplo n.º 14
0
        private void Pulse(object source, ElapsedEventArgs eea)
        {
            try
            {
                var potentialErrorSleep =
                    ErrorSleepConfiguration
                    .First(cfg => cfg.Key <= _pulseErrorCount).Value;
                if (_pluseLastError + potentialErrorSleep > _timeProvider.GetUtcNow())
                {
                    return; // noop because of error, longer and longer sleep.
                }
                try
                {
                    _executor.Pulse();
                    _pulseErrorCount = 0;
                }
                catch (Exception e)
                {
                    _pluseLastError = _timeProvider.GetUtcNow();
                    _logging.LogException(e, $"Executor failed to pulse. Successive error count : {++_pulseErrorCount}");
                    _healthCounterRepository.Increment(nameof(Executor.Executor), e.Message);
                }
#if DEBUG
                var status = _executor.GetStatus();
                foreach (var pluginStatus in status.PluginStatuses)
                {
                    Console.Write($"{pluginStatus.SourceUrn} : ");
                    if (pluginStatus.Busy && pluginStatus.CurrentTask == null)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("MISSING NODE");
                    }
                    else if (pluginStatus.Busy)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("BUSY");
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("FREE");
                    }
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                Console.WriteLine($"Last Executor pulse @ {_timeProvider.GetUtcNow().ToLocalTime()}");
#endif
            }
            catch
            {
                //ignore
            }
            finally
            {
                try
                {
                    _timer.Start();
                }
                catch (ObjectDisposedException)
                {
                    // ignore
                }
            }
        }
Ejemplo n.º 15
0
        private void ExecutePluginName(DictionaryNVR scopeData, SPSite site, ILogging log)
        {
            try
            {
                // TODO - config could be filtered based on plugin name and referrer
                // now it's up to the plugin itself to load what it needs

                PluginHost.Init(site);

                string pluginName = Request["PluginName"];

                IPlugin plugin = ExecutePagePluginHost.Get(site, pluginName);
                if (plugin == null)
                {
                    log.LogError(string.Format("ExecuteScriptPlugin named {0} was not found in loaded plugins, skipping execution", pluginName));
                    return;
                }

                try
                {
                    using (new SPMonitoredScope("Executing ExecuteScriptPlugin " + pluginName))
                    {
                        var res = plugin.Execute(null, scopeData);
                        log.LogInfo("Executed " + pluginName + " with result:\n", res ?? "NULL");
                    }
                }
                catch (Exception e)
                {
                    log.LogError(string.Format("ExecuteScriptPlugin named {0} has thrown {1}", pluginName, e),
                        e.InnerException, e.StackTrace, e.Source);
                }
            }
            catch (Exception exc)
            {
                log.LogException("Exception in Execute.aspx, Script " + Request["ScriptPath"], exc);
                Response.Write("Exception in script\n" + exc);
                Response.StatusCode = 500;
                Response.StatusDescription = "Exception in script";
                return;
            }
        }