Exemple #1
0
        /// <summary>
        /// Validate old token
        /// </summary>
        /// <param name="jwtToken">JWT token</param>
        /// <returns></returns>
        public async Task <LoginResponseDto> Login(string identifier, string password)
        {
            try
            {
                var requestModel = new LoginDto
                {
                    Identifier = identifier,
                    Password   = password,
                };

                var response = await _http.PostAsync("authentication/login", CreateContent(requestModel));

                _logger.LogInfo("SUCCESS LOGIN");

                if (response.IsSuccessStatusCode)
                {
                    return(await GetInstanceFromBody <LoginResponseDto>(response));
                }

                if (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
                {
                    _logger.LogInfo("Server not available!!!");
                    throw new HttpRequestException("Server not available!!!");
                }

                return(null);
            }
            catch (Exception e)
            {
                _logger.LogError(e);
                throw new HttpRequestException("Server not available!!!");
            }
        }
        /// <summary>
        /// Async call to request the update version info from the web.
        /// This call raises UpdateFound event notification, if an update is
        /// found.
        /// </summary>
        public void CheckForProductUpdate()
        {
            if (false != versionCheckInProgress)
            {
                return;
            }

            logger.LogInfo("RequestUpdateVersionInfo", "RequestUpdateVersionInfo");

            string exePath            = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string appVersionFileName = Path.Combine(Path.GetDirectoryName(exePath), Configurations.AppVersionFileName);

            if (!File.Exists(appVersionFileName))
            {
                logger.LogError("RequestUpdateVersionInfo",
                                string.Format("'{0}' not found!", Configurations.AppVersionFileName));
                return;
            }

            string[] appVersionInfo = File.ReadAllLines(appVersionFileName);
            if (appVersionInfo.Length != 3)
            {
                logger.LogError("RequestUpdateVersionInfo",
                                string.Format("Invalid '{0}' format!", Configurations.AppVersionFileName));
                return;
            }

            versionCheckInProgress = true;
            WebClient client = new WebClient();

            client.OpenReadCompleted += new OpenReadCompletedEventHandler(OnUpdateVersionRequested);
            client.OpenReadAsync(new System.Uri(appVersionInfo[1]));
        }
Exemple #3
0
        public IActionResult Error()
        {
            var error = HttpContext.Features.Get <IExceptionHandlerFeature>();
            var httpRequestFeature = HttpContext.Features.Get <IHttpRequestFeature>();

            var exception = error.Error;

            _loggerWrapper.LogError(exception.Message, this.GetType().Name, nameof(Error) + "()", null);
            _loggerWrapper.LogError(exception.InnerException.Message, this.GetType().Name, nameof(Error) + "()", null);

            var path                = httpRequestFeature.RawTarget;
            var httpMethod          = Request.Method;
            var userFriendlyMessage = exception.Message;
            var stackTrace          = exception.StackTrace;
            var innerException      = exception.InnerException?.ToString() != null
                ? exception.InnerException.ToString()
                : "None";

            if (innerException.Contains("Unauthorized") || userFriendlyMessage.Contains("Unauthorized"))
            {
                return(RedirectToAction("Login", "Authentication"));
            }

            var requestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;

            return(View(new ErrorViewModel
            {
                RequestId = requestId,
                Path = path,
                HttpMethod = httpMethod,
                UserFriendlyMessage = userFriendlyMessage,
                StackTrace = stackTrace,
                InnerException = innerException
            }));
        }
        private T CheckExceptions <T>(Func <T> func)
        {
            try
            {
                return(func());
            }
            catch (SocketException socketException)
            {
                _loggerWrapper.LogError(nameof(SocketException) + socketException.Message, GetType().Name, nameof(CheckExceptions), null);

                throw new HttpRequestException("Could not connect to datasource, socket exception", socketException);
            }
            catch (HttpRequestException httpRequestException)
            {
                _loggerWrapper.LogError(nameof(HttpRequestException) + httpRequestException.Message, GetType().Name, nameof(CheckExceptions), null);

                throw new HttpRequestException("Could not connect to datasource, http request exception", httpRequestException);
            }
            catch (HttwrapException httpwrapException)
            {
                _loggerWrapper.LogError(nameof(HttwrapException) + httpwrapException.Message, GetType().Name, nameof(CheckExceptions), null);

                throw new HttpRequestException("Could not connect to datasource, httwrap exception", httpwrapException);
            }
        }
 public IActionResult GetTopRatings(int count)
 {
     try
     {
         return(Ok(_dataAggregation.GetTopRated(count)));
     }
     catch (Exception e)
     {
         _logger.LogError(e, e.Message);
         return(StatusCode(500));
     }
 }
 public IActionResult Train([FromQuery] int iterations, int approximationRank, double learningRate)
 {
     try
     {
         return(Ok(_trainer.Train(iterations, approximationRank, learningRate)));
     }
     catch (Exception e)
     {
         _logger.LogError(e, e.Message);
         return(StatusCode(500, e.Message));
     }
 }
 public IActionResult Create([FromBody] Recipe recipe)
 {
     try
     {
         var user = _userRepository.GetByAuthId(recipe.UserId);
         recipe.UserId = user.Id.ToString();
         _recipeRepository.CreateRecipe(recipe, true);
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.LogError(e, e.Message);
         return(StatusCode(500));
     }
 }
Exemple #8
0
        public async Task Check()
        {
            try
            {
                _logger.LogInfo($"Started fetching communication type: {_time.Now}");

                if (!await _internet.CheckForInternetConnectionAsync() || _session.SessionInformation.Offline)
                {
                    _logger.LogInfo($"Can connect to commuincation point: {_time.Now}");
                    return;
                }

                CommunicationType type = await _communication.GetCommunicationType();

                if (type != _communicationTypeService.GetCommunicationType())
                {
                    CommunicationType old = _communicationTypeService.GetCommunicationType();
                    _communicationTypeService.SetCommuncationType(type);
                    _notification.ShowStatusMessage(nameof(CommunicationTypeCheckBehaviour), $"Communication type changed from {old} to {type}");
                }

                _logger.LogInfo($"Finished fetching communication type: {_time.Now} | type is {type}");
            }
            catch (Exception e)
            {
                _logger.LogError(e);
            }
        }
Exemple #9
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
            [RequestBodyType(typeof(GetNumberOfAddressesPerPostcodeInBoundaryRequest), "Get Number Of Addresses Per Postcode In Boundary")] GetNumberOfAddressesPerPostcodeInBoundaryRequest req,
            CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("C# HTTP trigger function processed a request.");


                if (req.IsValid(out var validationResults))
                {
                    GetNumberOfAddressesPerPostcodeInBoundaryResponse response = await _mediator.Send(req, cancellationToken);

                    return(new OkObjectResult(ResponseWrapper <GetNumberOfAddressesPerPostcodeInBoundaryResponse, AddressServiceErrorCode> .CreateSuccessfulResponse(response)));
                }
                else
                {
                    return(new ObjectResult(ResponseWrapper <GetNumberOfAddressesPerPostcodeInBoundaryResponse, AddressServiceErrorCode> .CreateUnsuccessfulResponse(AddressServiceErrorCode.ValidationError, validationResults))
                    {
                        StatusCode = 422
                    });;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Unhandled error in {nameof(GetNumberOfAddressesPerPostcodeInBoundary)}", ex);
                return(new ObjectResult(ResponseWrapper <GetNumberOfAddressesPerPostcodeInBoundaryResponse, AddressServiceErrorCode> .CreateUnsuccessfulResponse(AddressServiceErrorCode.UnhandledError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
        public async Task <ConvertedCurrencyValue> ConvertCurrencyAsync(PriceConversionRequest priceConversionRequest)
        {
            if (priceConversionRequest == null)
            {
                throw new ArgumentNullException("Price Conversion request is null");
            }
            await _priceConversionRequestValidator.ValidateAndThrowAsync(priceConversionRequest);

            var exchangeRateApiUrlSection = _configuration.GetSection("ExchangeRateApiUrl");

            if (string.IsNullOrEmpty(exchangeRateApiUrlSection?.Value))
            {
                var error = "Exchange rates API not configured";
                _logger.LogError(error);
                throw new Exception(error);
            }
            var exchangeRateApiUrl = $"{exchangeRateApiUrlSection.Value}/{priceConversionRequest.SourceCurrency}.json";
            var cancellationToken  = new CancellationTokenSource().Token;
            var response           = await _clientWrapper.GetAsync <ExchangeRatesResponse>(exchangeRateApiUrl, cancellationToken).ConfigureAwait(false);

            if (!response.Success || response.Data?.Rates == null)
            {
                return(null);
            }
            var    rates = response.Data.Rates;
            double convertedPrice;

            switch (priceConversionRequest.TargetCurrency.ToUpper())
            {
            case "USD":
                convertedPrice = priceConversionRequest.Price * rates.USD;
                break;

            case "EUR":
                convertedPrice = priceConversionRequest.Price * rates.EUR;
                break;

            case "GBP":
                convertedPrice = priceConversionRequest.Price * rates.GBP;
                break;

            default: return(null);
            }

            if (DateTime.TryParse(response.Data.Date, out var lastUpdated))
            {
                var time = new TimeSpan(response.Data.TimeLastUpdated);
                lastUpdated = lastUpdated.Add(time);
            }
            return(new ConvertedCurrencyValue
            {
                NewPrice = convertedPrice,
                ConvertedFromCurrency = priceConversionRequest.SourceCurrency,
                ConvertedToCurrency = priceConversionRequest.TargetCurrency,
                LastUpdated = lastUpdated
            });
        }
Exemple #11
0
 public IActionResult Get(string userId)
 {
     try
     {
         return(Ok(_userRepository.GetByAuthId(userId)));
     }
     catch (Exception e)
     {
         _logger.LogError(e, e.Message);
         return(StatusCode(500));
     }
 }
Exemple #12
0
        private T CheckExceptions <T>(Func <T> func)
        {
            try
            {
                return(func());
            }
            catch (SocketException socketException)
            {
                _loggerWrapper.LogError(nameof(SocketException) + "Could Not Connect To Data Source", this.GetType().Name, nameof(CheckExceptions) + "()", null);
                _loggerWrapper.LogError(nameof(SocketException) + socketException.Message, this.GetType().Name, nameof(CheckExceptions) + "()", null);

                throw new HttpRequestException("Could Not Connect To Data Source", socketException);
            }
            catch (HttpRequestException httpRequestException)
            {
                _loggerWrapper.LogError(nameof(HttpRequestException) + "Could Not Connect To Data Source", this.GetType().Name, nameof(CheckExceptions) + "()", null);
                _loggerWrapper.LogError(nameof(HttpRequestException) + httpRequestException.Message, this.GetType().Name, nameof(CheckExceptions) + "()", null);

                throw new HttpRequestException("Could Not Connect To Data Source", httpRequestException);
            }
            catch (HttwrapException httpwrapException)
            {
                _loggerWrapper.LogError(nameof(HttwrapException) + "The Data Source Link Has Changed", this.GetType().Name, nameof(CheckExceptions) + "()", null);
                _loggerWrapper.LogError(nameof(HttwrapException) + httpwrapException.Message, this.GetType().Name, nameof(CheckExceptions) + "()", null);

                throw new HttpRequestException("The Data Source Link Has Changed", httpwrapException);
            }
        }
Exemple #13
0
        public async Task <List <UrlHistoryContainer> > BuildHistoryContainers(List <PendingJobConfig> containers, string giphyRandomEndpoint)
        {
            _Log.LogInformation($"Building {containers.Count} histories.");
            var urlCaches = await _Context.GetUrlCachesAsync();

            var orderedUrlCaches = urlCaches.OrderByDescending(s => s.Stamp).ToList();
            var histories        = new List <UrlHistoryContainer>();

            foreach (var container in containers)
            {
                var firstUnseenUrlCache = (from urlCache in orderedUrlCaches
                                           //find caches where there are no histories with their gif IDs
                                           where !container.Histories.Any(s => s.GifId == urlCache.Id)
                                           select urlCache).FirstOrDefault();
                if (firstUnseenUrlCache != null)
                {
                    histories.Add(new UrlHistoryContainer(container.ChannelId, firstUnseenUrlCache.Id, firstUnseenUrlCache.Url, true));
                }
                else if (!string.IsNullOrEmpty(container.RandomSearchString))
                {
                    //TODO add a retry loop or something so that we can get/check more than 1 random gif for the channel
                    try
                    {
                        var randomTagGif = await _GiphyWrapper.GetRandomGifAsync(giphyRandomEndpoint, container.RandomSearchString);

                        var hasBeenSeenBefore = container.Histories.Any(s => s.GifId == randomTagGif.Data.Id);
                        if (!hasBeenSeenBefore)
                        {
                            histories.Add(new UrlHistoryContainer(container.ChannelId, randomTagGif.Data.Id, randomTagGif.Data.Url, false));
                        }
                    }
                    catch (GiphyException ex)
                    {
                        _Log.LogError(ex, "Error getting random gif.");
                    }
                }
            }
            _Log.LogInformation($"Built {histories.Count} histories.");
            return(histories);
        }
Exemple #14
0
        public async Task <ResponseModel <Favorite> > DeleteFavoriteAsync(Guid clientId, Guid productId)
        {
            try
            {
                var targetFavorite = await _favoriteRepository.GetFavorite(clientId, productId);

                if (targetFavorite is null)
                {
                    return(new ResponseModel <Favorite>(true, new List <ErrorInfo>
                    {
                        new ErrorInfo(HttpStatusCode.NotFound, _messages.NoFavoriteFound,
                                      string.Format(_messages.NoFavoriteFoundDescription, clientId, productId))
                    }));
                }

                var deleted = await _favoriteRepository.Delete(targetFavorite);

                if (deleted == 0)
                {
                    return(new ResponseModel <Favorite>(true, new List <ErrorInfo>
                    {
                        new ErrorInfo(HttpStatusCode.Conflict, _messages.NoFavoriteChanged, _messages.NoFavoriteChangedDescription)
                    }));
                }

                return(new ResponseModel <Favorite>(targetFavorite));
            }
            catch (Exception ex)
            {
                var message = string.Format(_messages.InternalErrorDescription, ex.Message);
                _logger.LogError(ex, message);

                return(new ResponseModel <Favorite>(true, new List <ErrorInfo>
                {
                    new ErrorInfo(HttpStatusCode.InternalServerError, _messages.InternalError, message)
                }));
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            [RequestBodyType(typeof(GetShiftRequestsByFilterRequest), "Get Shift Requests By Filter request")] GetShiftRequestsByFilterRequest req,
            CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("GetShiftRequestsByFilter started");
                GetShiftRequestsByFilterResponse response = await _mediator.Send(req, cancellationToken);

                return(new OkObjectResult(ResponseWrapper <GetShiftRequestsByFilterResponse, RequestServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception exc)
            {
                _logger.LogError("Exception occured in GetShiftRequestsByFilter", exc);
                _logger.LogError(exc.ToString(), exc);
                _logger.LogErrorAndNotifyNewRelic("Exception occured in GetShiftRequestsByFilter", exc);
                return(new ObjectResult(ResponseWrapper <GetShiftRequestsByFilterResponse, RequestServiceErrorCode> .CreateUnsuccessfulResponse(RequestServiceErrorCode.InternalServerError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
Exemple #16
0
 public IActionResult Create([FromBody] Rating rating)
 {
     try
     {
         rating.UserId = _userRepository.GetByAuthId(rating.UserId).Id.ToString();
         _rateRepository.CreateRating(rating, true);
         return(Ok());
     }
     catch (Exception e)
     {
         _logger.LogError(e, e.Message);
         return(StatusCode(500));
     }
 }
 public async Task <IActionResult> RunAsync(int guildCount, long botId, List <StatPost> statPosts)
 {
     _Log.LogInformation("Posting stats.");
     foreach (var statPost in statPosts)
     {
         try
         {
             var requestUri = string.Format(statPost.UrlStringFormat, botId);
             var content    = $"{{\"{statPost.GuildCountPropertyName}\":{guildCount}}}";
             await _StatWrapper.PostStatAsync(requestUri, content, statPost.Token);
         }
         catch (StatPostException ex)
         {
             _Log.LogError(ex, $"Error posting stats.");
         }
     }
     _Log.LogInformation("Posted stats.");
     return(new NoContentResult());
 }
        public async Task Run([TimerTrigger("%TimedCacheRefresherCronExpression%")] TimerInfo timerInfo, CancellationToken cancellationToken, ILogger log)
        {
            _logger.LogInformation($"TimedCacheRefresher CRON trigger executed at : {DateTimeOffset.Now}");

            Stopwatch stopwatch = Stopwatch.StartNew();

            try
            {
                await _memDistCache.RefreshDataAsync(async (token) => await _volunteersForCacheGetter.GetAllVolunteersAsync(token), CacheKey.AllCachedVolunteerDtos.ToString(), cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error running TimedCacheRefresher", ex);
                throw;
            }

            stopwatch.Stop();

            _logger.LogInformation($"TimedCacheRefresher CRON trigger took: {stopwatch.Elapsed:%m' min '%s' sec'}");
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            [RequestBodyType(typeof(GetDistanceBetweenPostcodesRequest), "Get Distance Between Postcodes")] GetDistanceBetweenPostcodesRequest req,
            CancellationToken cancellationToken)
        {
            try
            {
                var input = JsonConvert.SerializeObject(req);
                _logger.LogInformation(input);
                GetDistanceBetweenPostcodesResponse response = await _mediator.Send(req, cancellationToken);

                return(new OkObjectResult(ResponseWrapper <GetDistanceBetweenPostcodesResponse, AddressServiceErrorCode> .CreateSuccessfulResponse(response)));
            }
            catch (Exception exc)
            {
                _logger.LogErrorAndNotifyNewRelic("Exception occured in GetDistanceBetweenPostcodes", exc);
                _logger.LogError(exc.ToString(), exc);
                return(new ObjectResult(ResponseWrapper <GetDistanceBetweenPostcodesResponse, AddressServiceErrorCode> .CreateUnsuccessfulResponse(AddressServiceErrorCode.UnhandledError, "Internal Error"))
                {
                    StatusCode = StatusCodes.Status500InternalServerError
                });
            }
        }
Exemple #20
0
        public async Task Synchronize()
        {
            try
            {
                _logger.LogInfo($"Sync behaviourr started: {_time.Now}");

                //Offline mode so exit
                if (_sessionService.SessionInformation.Offline)
                {
                    _notification.ShowStatusMessage(nameof(SyncBehaviour), $"Sessions sync skipped (OFFLINE MODE): {_time.Now}");

                    _logger.LogInfo($"Sync finished: {_time.Now}, OFFLINE MODE");
                    return;
                }

                //Check for internet connection
                if (!await _internet.CheckForInternetConnectionAsync())
                {
                    _notification.ShowStatusMessage(nameof(SyncBehaviour), $"Sessions sync skipped (No internet connection): {_time.Now}");

                    _logger.LogInfo($"Sync finished: {_time.Now}, NO INTERNET ACCESS");
                    return;
                }

                //Get all sessions from database
                var sessions = await _unitOfWork.Sessions.GetAllWithIncludesAsync();

                //no records in database so finish sync process
                if (sessions.Count == 0)
                {
                    _notification.ShowStatusMessage(nameof(SyncBehaviour), $"No sessions for sync (No sync needed): {_time.Now}");

                    _logger.LogInfo($"Sync finished: {_time.Now}, NO RECORDS FOR SYNC");
                    return;
                }

                //are we working only with current session ?
                if (sessions.Count == 1 && IsCurrentSession(sessions))
                {
                    var curSession = sessions.First();

                    if (!SessionNeedsUpdate(curSession))
                    {
                        _notification.ShowStatusMessage(nameof(SyncBehaviour), $"Current session only (No sync needed): {_time.Now}");

                        _logger.LogInfo($"Sync finished: {_time.Now}, NO RECORDS FOR SYNC");

                        return;
                    }
                }

                //map entites from database to dtos
                var dtosSessions = sessions.Adapt <List <UserSessionDto> >();

                //list for successfuly synced entites
                var successStatuses = new List <UserSessionDto>();

                //sync process
                foreach (var session in dtosSessions)
                {
                    //get sync client
                    var syncClient = _factory.GetClient();

                    //sync session
                    var result = await syncClient.Sync(session);

                    //if sync successful, add to list
                    if (result)
                    {
                        successStatuses.Add(session);
                    }
                }

                //no success on sync
                if (successStatuses.Count == 0)
                {
                    _logger.LogInfo($"Sync finished: {_time.Now}, NO SYNC");

                    _notification.ShowStatusMessage(nameof(SyncBehaviour), $"Sync for session failed (Server error): {_time.Now}");

                    return;
                }

                /// Get successfuly synced sessions -> sessions that needs to be deleted
                var sessionsForDelete = GetSessionsForDelete(sessions, successStatuses);

                //remove current session entity -> current sessions = different treatment
                //get current session
                var currentSession = GetCurrentSessionFromList(sessionsForDelete);

                //remove if from deletesessions
                RemoveCurrentSessionFromList(sessionsForDelete);

                //handle current session
                HandleCurrentSession(currentSession);

                //zero objects, exit
                if (sessionsForDelete.Count() > 0)
                {
                    //delete old sessions
                    _unitOfWork.Sessions.RemoveRange(sessionsForDelete);
                }

                //save changes
                await _unitOfWork.CommitAsync();

                _notification.ShowStatusMessage(nameof(SyncBehaviour), $"Sync finished: {_time.Now}");

                _logger.LogInfo($"Sync finished: {_time.Now}, SYNC");
            }
            catch (Exception e)
            {
                _logger.LogError(e);
            }
        }
Exemple #21
0
        public async Task<List<TEntity>> GetAll(string path, string token = null)
        {
            List<TEntity> result;

            _loggerWrapper.LogInformation("path: " + path, this.GetType().Name, nameof(GetAll) + "()", null);

            try
            {
                result = await HttpClientWrapper.GetAllAsync(path, token);
            }
            catch (Exception exception)
            {
                _loggerWrapper.LogError("Failed to retrieve items", this.GetType().Name, nameof(GetAll) + "()", null);
                _loggerWrapper.LogError(exception.Message, this.GetType().Name, nameof(GetAll) + "()", null);
                _loggerWrapper.LogError(exception.InnerException != null ? exception.InnerException.Message : null, this.GetType().Name, nameof(GetAll) + "()", null);

                throw new Exception("Failed to retrieve items", exception);
            }

            return result;
        }