public ActionResult ViewPhoto(string uniqueUserName, string photoName) { string userId = User.Identity.GetUserId(); string currentUserName = string.Empty; if (!string.IsNullOrEmpty(userId)) { currentUserName = _userService.GetUniqueUserNameById(userId); } var request = new RequestEntity { UniqueUserName = uniqueUserName, PhotoName = photoName, CurrentUserName = currentUserName }; var response = _photoService.GetPhoto(request); PhotoViewModel photo = MapperHelper.GetValue <Photo, PhotoViewModel>(response); if (photo == null) { var errMsg = string.Format(Errors.PhotoNotFound, photoName, uniqueUserName); _logger.Error(errMsg); return(View("Error", errMsg)); } ViewBag.CurrentUniqueUserName = currentUserName; ViewBag.ResultMessage = TempData["ResultMessage"]; return(View(photo)); }
public IActionResult Edit(int id) { var model = _mapper.Map <AppUserListDto>(_userManager.Users.First(u => u.Id == id)); if (model != null) { return(View(model)); } else { _customLogger.Error("UserController | Update User Error : Null Object"); } return(RedirectToAction("Index")); }
/// <summary> /// Adding client form /// </summary> public void AddClient() { var client = EnterClientData(); try { _clientService.Create(client); _outputEnvironment.WriteLine(Resource.CreatedSuccess); } catch (Exception ex) { _logger.Error(ex.Message, ex); } }
/// <summary> /// Render a rdlc (SQL Server Reporting Services) /// </summary> /// <param name="reportPath">Absolute file path</param> /// <param name="exportReportType">Export file extension</param> /// <param name="parameters">Report parameters</param> /// <param name="dataSources">Report datasources</param> /// <returns>Array file contents</returns> public byte[] RenderRdlc(string reportPath, ExportReportType exportReportType, Dictionary <string, string> parameters = null, Dictionary <string, object> dataSources = null) { try { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var report = new LocalReport(reportPath); if (dataSources != default) { foreach (var dataSource in dataSources) { report.AddDataSource(dataSource.Key, dataSource.Value); } } var result = report.Execute((RenderType)exportReportType, 1, parameters); return(result.MainStream); } catch (Exception e) { _logger?.Error(e, e.Message); throw; } }
private void ConsumeMessages(string eventSubscriber, ushort prefetchCount = 10) { var channel = _config.Channel(); DeclareQueue(channel, eventSubscriber); channel.BasicQos(0, prefetchCount, false); var consumer = new EventingBasicConsumer(channel); consumer.Received += async(_, ea) => { try { var body = ea.Body.ToArray(); var message = Encoding.UTF8.GetString(body); var @event = _deserializer.Deserialize(message); await _domainEventMediator.ExecuteOn(@event, eventSubscriber, CancellationToken.None); } catch (Exception ex) { _logger.Error(ex, ex.Message); HandleConsumptionError(ea, eventSubscriber); } channel.BasicAck(ea.DeliveryTag, false); }; channel.BasicConsume(eventSubscriber, false, consumer); }
/// <summary> /// Saving data to storage /// </summary> public void SaveDb() { _outputEnvironment.Write($"{Resource.EnterFileName}: "); var fileName = _outputEnvironment.Read(); try { _fileService.SaveToFile(fileName); _outputEnvironment.WriteLine(Resource.StorageSaved); _logger.Info(Resource.StorageSaved); } catch (Exception e) { _logger.Error(e.Message, e); } }
public void AddRemoveWishlist(BookDto book, bool remove) { if (remove) { try { var wish = _wishListService.GetAll() .FirstOrDefault(c => c.BookId == book.Id && c.ClientId == _authService.GetCurrentClientId()); _wishListService.Delete(wish.Id); } catch (Exception ex) { _logger.Error(ex.Message, ex); } } else { try { _wishListService.Create( new WishDto { ClientId = _authService.GetCurrentClientId().Value, BookId = book.Id }); } catch (Exception ex) { _logger.Error(ex.Message, ex); } } }
private Task ExecuteDomainSubscriber(string body, DomainEvent domainEvent, string subscriber, CancellationToken cancellationToken) { return(_retriever.ExecuteAsync <Task>(async ct => await ExecuteOn(body, domainEvent, subscriber, ct), e => { _logger?.Error(e, e.Message); return true; }, cancellationToken)); }
protected virtual ActionResult ErrorIfNotAnOwner(string uniqueUserName, string errorType, IUserService userService, string userId, ICustomLogger logger) { string uniqueUserNameFromDb = userService.GetUniqueUserNameById(userId); if (uniqueUserNameFromDb != uniqueUserName) { logger.Error(errorType); return(View("Error", errorType)); } return(null); }
public IActionResult Insert(TargetAddDto model) { if (!ModelState.IsValid) { return(View(model)); } model.UserId = GetCurrentUser().Result.Id; model.LastModified = DateTime.Now; var obj = _mapper.Map <Target>(model); try { _targetService.Add(obj); _customLogger.Information("TargetController | Added New Target : " + obj.Name); return(RedirectToAction("Index")); } catch (Exception e) { _customLogger.Error("TargetController | Insert Target Error " + e.Message.ToString()); } return(View(model)); }
/// <summary> /// Метод скачивания файлов с сайта и последующей выгрузкой на сторону Rdev-a /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void AbooksBtn_Click(object sender, EventArgs e) { try { // Количество скаченных со страницы аудиокниг int countDownloaded = 0; // Формируем объект категории "Новинки" var novelty = new Category { Name = "Новинки", Url = baseUrl }; logger.Debug("Получаем общее количество страниц в категории Новинки."); // Получаем общее количество страниц на сайте в категории "Новинки" int countPage = await service.GetPagesCount(novelty); // Запускаем цикл обхода страниц с книгам начиная с конца (самые новые книги находятся на 1 странице) for (int page = countPage; page >= 1; page--) { logger.Debug($"Получаем количество аудиокниг со страницы {page}."); // Получаем список аудиокниг со страницы var audiobooks = await service.GetAudiobooks(novelty, page); logger.Debug($"Количество аудиокниг на странице {page}: {audiobooks.Count}."); // Запускаем цикл на последовательное скачивание аудиокниг со страницы foreach (var audiobook in audiobooks) { logger.Log($"Загружаем аудиокнигу: {audiobook.Title}."); await grabber.Grab(audiobook); ++countDownloaded; logger.Success($"Аудиокнига {audiobook.Title} загружена, " + $"оставшееся количество аудиокниг на странице {audiobooks.Count - countDownloaded}." ); } countDownloaded = 0; } } catch (Exception ex) { logger.Error($"Скачивание остановлено по причине ошибки: {ex.Message}."); } }
public async Task <bool> CheckUsernameRegisteredAsync(string username) { try { var response = await _httpManager.GetAsync <bool>(ApiConstants.LogInURL, parameter : username); return(response); } catch (Exception e) { _logger.Error(e.Message); return(false); } }
protected virtual Task <ApiResponse <TResponse> > Post <TRequest, TResponse>(TRequest req, Func <TRequest, ApiResponse <TResponse> > handler) { _logger.Debug(this, $"Request ({typeof(TRequest).Name}): '{req.ToString()}'"); ApiResponse <TResponse> resp; try { resp = handler(req); } catch (Exception e) { _logger.Error(this, $"Post: {e}"); resp = new ServerError(e.ToString()).AsError <TResponse>(); } _logger.Debug(this, $"Response ({typeof(TResponse).Name}): '{resp.Success}, '{resp.Result}', {resp.Error?.Message}"); if (!resp.Success) { OnError(resp.Error); } return(Task.FromResult(resp)); }
public async Task Update(ICommand command) { var state = _state.State; var config = _state.Config; var runner = new CommandRunner(_offsetTime.Offset, command, state, config); foreach (var item in runner) { _logger.DebugFormat(this, "Start executing command: {0}", item.Command); if (!item.IsValid()) { _logger.ErrorFormat(this, "Command is invalid: {0}", item.Command); return; } item.Execute(); _logger.DebugFormat(this, "End executing command: {0}", item.Command); var container = _handlers.GetOrDefault(item.Command.GetType()); if (container != null) { var handlers = container.GetHandlers(); foreach (var handler in handlers) { await container.Invoke(handler, item.Command); OnStateUpdated(state); } } OnStateUpdated(state); } var response = await _api.Post(new IntentRequest(_state.User.Login, state.Version, command)); if (!response.Success) { _logger.Error(this, "State declined from server."); return; } var result = response.Result; state.Version = result.NewVersion; _logger.Debug(this, "State approved from server."); }
public static void ConfigureExceptionHandler(this IApplicationBuilder app, ICustomLogger logger) { app.UseExceptionHandler(appError => { appError.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { logger.Error($"Something went wrong: {contextFeature.Error}"); await context.Response.WriteAsync(new ErrorDetails() { StatusCode = context.Response.StatusCode, Message = "Internal Server Error. Error generated by NLog!" }.ToString()); } }); }); }
public async Task Invoke(DownstreamContext context) { await _next.Invoke(context); if (context.IsError) { //保存请求的信息 BaseLogModel logModel = new BaseLogModel() { Type = 1, Content = $"{context.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{context.HttpContext.Request.Path}, request method: {context.HttpContext.Request.Method}" }; _log.Error(logModel); SetErrorResponse(context.HttpContext, context.Errors); } else { //Logger.LogDebug("no pipeline errors, setting and returning completed response"); await _responder.SetResponseOnHttpContext(context.HttpContext, context.DownstreamResponse); } }
public void LogLogicalError(LogicalException exception, string msgFormat , params object[] formatVars) { _logger.Error(exception, msgFormat, formatVars); }
private ApiResponse HandleClientError <ApiResponse>(Exception e) { _logger.Error(e.Message); return(default(ApiResponse)); }
public void OnError(IApiError error) { _logger.Error(this, $"Failed: '{error.Message}' ({error.GetType().Name})"); Environment.Exit(-1); }
public BaseResultDto <List <SeasonTeamDto> > GetTeams(IEnumerable <SeasonDto> seasons) { var result = new BaseResultDto <List <SeasonTeamDto> >(); result.DataObject = new List <SeasonTeamDto>(); var dataPath = Utility.GetApplicationSetting <string>("PathToDataFiles"); foreach (var season in seasons) { var pythonRequest = new PythonRequestDto { Command = Utility.GetApplicationSetting <string>("TeamScript"), Params = new string[] { season.StartYear.ToString(), season.League.Name } }; var pythonResult = PythonUtility.ExecutePythonScript(pythonRequest); if (pythonResult.Status) { var cleanSheetsFile = Utility.GetFileData(dataPath + "team_Fpl.csv"); foreach (var line in Utility.GetFileData(dataPath + pythonResult.Output).Skip(1)) { var lineAsList = Utility.CsvRowToList(line); int position; int matches; int won; int drawn; int lost; int goals; int goalsAgainst; int points; double xG; double xGAgainst; double xPoints; var status = int.TryParse(lineAsList[0], out position); status &= int.TryParse(lineAsList[2], out matches); status &= int.TryParse(lineAsList[3], out won); status &= int.TryParse(lineAsList[4], out drawn); status &= int.TryParse(lineAsList[5], out lost); status &= int.TryParse(lineAsList[6], out goals); status &= int.TryParse(lineAsList[7], out goalsAgainst); status &= int.TryParse(lineAsList[8], out points); status &= double.TryParse(lineAsList[9].StripXValues().Replace(".", ","), out xG); status &= double.TryParse(lineAsList[10].StripXValues().Replace(".", ","), out xGAgainst); status &= double.TryParse(lineAsList[11].StripXValues().Replace(".", ","), out xPoints); if (status) { var seasonTeam = new SeasonTeamDto { Season = season, Team = new TeamDto { Name = ConvertDoubleTeam(lineAsList[1]) }, Drawn = drawn, GoalsAgainst = goalsAgainst, GoalsFor = goals, Lost = lost, GamesPlayed = matches, Points = points, Position = position, Won = won, XGAgainst = xGAgainst, XGFor = xG, XPoints = xPoints }; result.DataObject.Add(seasonTeam); } } var nextPosition = true; var nextTeam = false; var nextCS = false; SeasonTeamDto st = null; foreach (var line in cleanSheetsFile) { if (nextPosition) { nextPosition = false; nextTeam = true; nextCS = false; continue; } int cs; if (nextTeam) { st = result.DataObject.FirstOrDefault(r => r.Team.Name.Equals(line) && r.Season.Id == season.Id); if (st == null) { var tt = 1; } nextPosition = false; nextTeam = false; nextCS = true; continue; } var status = int.TryParse(line, out cs); if (!status || st == null) { throw new Exception(); } st.CleanSheets = cs; st = null; nextPosition = true; nextTeam = false; nextCS = false; } //foreach (var line in cleanSheetsFile) //{ // var csLineAsList = Utility.CsvRowToList(line); // int cs; // var st = result.DataObject.FirstOrDefault(r => r.Team.Name.Equals(csLineAsList[1]) // && r.Season.Id == season.Id); // var status = int.TryParse(csLineAsList[2], out cs); // if (!status || st == null) // { // throw new Exception(); // } // st.CleanSheets = cs; //} } else { var e = new Exception(pythonResult.ErrorMessage); _logger.Error(e, "Could not parse team data"); throw e; } } //result.Status = result.DataObject.Count/seasons.Count() == 20; result.Status = true; return(result); }
private void AddToAuditChangeDbSet(DbContext context) { var auditChangesDbSet = context.Set <AuditChange>(); var auditChanges = new List <AuditChange>(); foreach (var entity in context.ChangeTracker.Entries() .Where(p => p.State == EntityState.Added || p.State == EntityState.Modified || p.State == EntityState.Deleted) .Select(p => p.Entity)) { var propertyNames = new List <string>(); PropertyValues originalValues = null; PropertyValues currentValues = null; if (context.Entry(entity).State == EntityState.Modified) { originalValues = context.Entry(entity).OriginalValues; propertyNames = originalValues.Properties.Select(p => p.Name).ToList(); } if (context.Entry(entity).State != EntityState.Deleted) { currentValues = context.Entry(entity).CurrentValues; propertyNames = currentValues.Properties.Select(p => p.Name).ToList(); } //var keyProperties = context.GetKeysFor(typeof(T)).ToList(); //var values = keyProperties.Select(keyProp => keyProp.GetValue(entity, null)).ToList(); var id = propertyNames.Any(pn => pn == "Id") ? "Id" : propertyNames.Any(pn => pn == "EntityId") ? "EntityId" : null; var registryId = Guid.Empty.ToString(); if (id == null) { var exception = new Exception($"Property not found {string.Join(",", propertyNames)}"); _customLogger.Error(exception, exception.Message); } else { if (originalValues != null) { registryId = originalValues[id]?.ToString() ?? Guid.Empty.ToString(); } if (currentValues != null) { registryId = currentValues[id]?.ToString() ?? Guid.Empty.ToString(); } } var state = (State)context.Entry(entity).State; if (state == State.Deleted) { var auditChange = AuditChange.Create(_guid.NewGuid(), registryId, entity.GetType().Name, "Deleted", null, null, _dateTime.UtcNow, state); auditChanges.Add(auditChange); continue; } foreach (var propertyName in propertyNames) { object original = null; if (originalValues != null) { original = originalValues[propertyName]; } object current = null; if (currentValues != null) { current = currentValues[propertyName]; } if (original == default && current == default || Equals(original, current)) { continue; } var auditChange = AuditChange.Create(_guid.NewGuid(), registryId, entity.GetType().Name, propertyName, original?.ToString(), current?.ToString(), _dateTime.UtcNow, state); auditChanges.Add(auditChange); } } auditChangesDbSet.AddRange(auditChanges); }