public IAppActionResult <ReadModelForExcel> Read(XLWorkbook workbook)
        {
            IAppActionResult <ReadModelForExcel> result = new AppActionResult <ReadModelForExcel> {
                Data = new ReadModelForExcel()
            };
            var worksheet = workbook.Worksheet(workSheetNumber);
            var range     = worksheet.RangeUsed();
            var rowCount  = range.RowsUsed().Count();
            var colCount  = range.ColumnsUsed().Count();

            if (rowCount <= 1)
            {
                result.ErrorMessages.Add(Localizer["RowCountOneOrLess"]);
            }
            var dataModelColCount = result.Data.GetType().GetProperties().Length;

            if (colCount < dataModelColCount)
            {
                result.ErrorMessages.Add(Localizer["ColCountSmallerThanDataModels"]);
            }
            if (result.ErrorMessages.Count != 0)
            {
                return(result);
            }
            return(ParseLoadedData(result, range, rowCount, colCount));
        }
Exemplo n.º 2
0
            public async Task ExecuteAsync()
            {
                var note = CreateNote();

                var result = await TryAddNoteToDatabase(note);

                if (!result.Success)
                {
                    Result = result;
                    return;
                }

                result = await TrySendNoteToServer(note);

                if (!result.Success)
                {
                    Result = result;
                    autoSendService.TrySendNotes(note);
                    await TryAddResultToDatabase(note, result);

                    return;
                }

                Result = await TryAddResultToDatabase(note, result);
            }
Exemplo n.º 3
0
        public IAppActionResult ValidateFile(IFormFile file)
        {
            var result = new AppActionResult();

            if (file == null || file.Length == 0)
            {
                result.ErrorMessages.Add(Localizer[NoData]);
            }
            result.SetStatus(HttpStatusCode.BadRequest, HttpStatusCode.OK);
            return(result);
        }
Exemplo n.º 4
0
        public virtual async Task <IAppActionResult> ValidateAdd(TAddDTO model)
        {
            IAppActionResult <TData> result = new AppActionResult <TData>();

            result.Data = await FindDataAsync(model);

            if (result.Data != null)
            {
                result.ErrorMessages.Add(Localizer[EntityAlreadyExist]);
            }
            return(result.SetStatus(HttpStatusCode.BadRequest, HttpStatusCode.OK));
        }
Exemplo n.º 5
0
        public virtual async Task <IAppActionResult <List <TGetDTO> > > GetPageAsync(int startItem, int countItem)
        {
            var resultDTO  = new AppActionResult <List <TGetDTO> >();
            var resultData = await Validator.ValidateGetData(startItem, countItem);

            resultDTO.SetResult(resultData);
            if (resultData.Data != null)
            {
                resultDTO.Data = Mapper.Map <List <TData>, List <TGetDTO> >(resultData.Data);
            }
            return(resultDTO);
        }
Exemplo n.º 6
0
        public virtual async Task <IAppActionResult <TGetDTO> > GetAsync(Guid id)
        {
            var resultDTO  = new AppActionResult <TGetDTO>();
            var resultData = await Validator.ValidateGetData(id);

            resultDTO.SetResult(resultData);
            if (resultData.Data != null)
            {
                resultDTO.Data = Mapper.Map <TData, TGetDTO>(resultData.Data);
            }
            return(resultDTO);
        }
Exemplo n.º 7
0
        public virtual async Task <IAppActionResult <List <TData> > > ValidateGetData(int startItem, int countItem)
        {
            IAppActionResult <List <TData> > result = new AppActionResult <List <TData> >();

            result.Data = await FindPageDataAsync(startItem, countItem);

            if (result.Data == null)
            {
                result.ErrorMessages.Add(Localizer[EntitiesNotFound]);
            }
            result.SetStatus(HttpStatusCode.NotFound, HttpStatusCode.OK);
            return(result);
        }
Exemplo n.º 8
0
        public virtual async Task <IAppActionResult <int> > ValidateCount()
        {
            IAppActionResult <int> result = new AppActionResult <int>();

            result.Data = await GetCountElementAsync();

            if (result.Data == 0)
            {
                result.ErrorMessages.Add(Localizer[EntitiesNotFound]);
            }
            result.SetStatus(HttpStatusCode.NotFound, HttpStatusCode.OK);
            return(result);
        }
Exemplo n.º 9
0
        public virtual async Task <IAppActionResult <TData> > ValidateGetData(Guid id)
        {
            IAppActionResult <TData> result = new AppActionResult <TData>();

            result.Data = await FindDataAsync(id);

            if (result.Data == null)
            {
                result.ErrorMessages.Add(Localizer[EntityNotFound]);
            }
            result.SetStatus(HttpStatusCode.NotFound, HttpStatusCode.OK);
            return(result);
        }
Exemplo n.º 10
0
        public virtual async Task <IAppActionResult> DeleteAsync(Guid id)
        {
            var result     = new AppActionResult();
            var resultData = await Validator.ValidateDelete(id);

            result.SetResult(resultData);
            if (!result.IsSuccess)
            {
                return(result);
            }
            DeleteDataFromDbAsync(resultData.Data);
            await UnitOfWork.SaveChangesAsync();

            return(result);
        }
Exemplo n.º 11
0
        public virtual IAppActionResult <List <TGetDTO> > ValidatePaging(int startItem, int countItem)
        {
            var result = new AppActionResult <List <TGetDTO> >();

            if (startItem < 0)
            {
                result.ErrorMessages.Add(Localizer[StartItemNotExist]);
            }
            if (countItem < 1)
            {
                result.ErrorMessages.Add(Localizer[CountItemsLeastOne]);
            }
            result.SetStatus(HttpStatusCode.BadRequest, HttpStatusCode.OK);
            return(result);
        }
Exemplo n.º 12
0
        public virtual IAppActionResult <TGetDTO> ValidateUpdate(TUpdateDTO updateDTO, ModelStateDictionary modelState)
        {
            var result = new AppActionResult <TGetDTO>();

            if (updateDTO == null)
            {
                result.ErrorMessages.Add(Localizer[NoData]);
            }
            if (!modelState.IsValid)
            {
                result.ErrorMessages.Add(Localizer[DataIsNotValid]);
            }
            result.SetStatus(HttpStatusCode.BadRequest, HttpStatusCode.OK);
            return(result);
        }
        public IAppActionResult <Image> ValidateFile(IFormFile file)
        {
            IAppActionResult <Image> result = new AppActionResult <Image>();

            try
            {
                using (result.Data = Image.FromStream(file.OpenReadStream()))
                {
                }
            }
            catch
            {
                result.ErrorMessages.Add(Localizer["FileNotPicture"]);
            }
            result.SetStatus(HttpStatusCode.BadRequest, HttpStatusCode.OK);
            return(result);
        }
 public IActionResult InvokeBulkUpdate(string name, [FromBody] BulkUpdateFormDto dto)
 {
     try
     {
         AppActionResult result = service.InvokeBulkUpdate(name, dto.Ids.Select(Guid.Parse), dto.Value);
         return(Ok(result));
     }
     catch (UnauthorizedAccessException)
     {
         return(Unauthorized());
     }
     catch (Exception ex)
     {
         Log.Error(ex, $"Failed to Invoke bulk update {name} for {EntityName}");
         return(StatusCode(500, ex.Message));
     }
 }
 public IActionResult InvokeAction(string name, [FromBody] IEnumerable <string> ids)
 {
     try
     {
         AppActionResult result = service.InvokeAction(name, ids.Select(Guid.Parse));
         return(Ok(result));
     }
     catch (UnauthorizedAccessException)
     {
         return(Unauthorized());
     }
     catch (Exception ex)
     {
         Log.Error(ex, $"Failed to Invoke action {name} for {EntityName}");
         return(StatusCode(500, ex.Message));
     }
 }
Exemplo n.º 16
0
        public virtual async Task <IAppActionResult <TGetDTO> > UpdateAsync(TUpdateDTO modelDTO)
        {
            var resultDTO  = new AppActionResult <TGetDTO>();
            var resultData = await Validator.ValidateUpdate(modelDTO);

            resultDTO.SetResult(resultData);
            if (!resultDTO.IsSuccess)
            {
                return(resultDTO);
            }
            Mapper.Map(modelDTO, resultData.Data);
            UpdateDataInDbAsync(resultData.Data);
            await UnitOfWork.SaveChangesAsync();

            resultDTO.Data = Mapper.Map <TData, TGetDTO>(resultData.Data);
            return(resultDTO);
        }
        public IAppActionResult <XLWorkbook> ValidateFile(IFormFile file)
        {
            IAppActionResult <XLWorkbook> result = new AppActionResult <XLWorkbook>();

            try
            {
                using (result.Data = new XLWorkbook(file.OpenReadStream()))
                {
                }
            }
            catch
            {
                result.ErrorMessages.Add(Localizer["FileNotXLWorkbook"]);
                result.Data = null;
            }
            result.SetStatus(HttpStatusCode.BadRequest, HttpStatusCode.OK);
            return(result);
        }
Exemplo n.º 18
0
        public virtual async Task <IAppActionResult <TGetDTO> > AddAsync(TAddDTO modelDTO)
        {
            var result = new AppActionResult <TGetDTO>();

            result.SetResult(await Validator.ValidateAdd(modelDTO));
            if (!result.IsSuccess)
            {
                return(result);
            }
            var data = Mapper.Map <TAddDTO, TData>(modelDTO);

            AddDataToDbAsync(data);
            await UnitOfWork.SaveChangesAsync();

            data = await FindDataAsync(data.Id);

            result.Data = Mapper.Map <TData, TGetDTO>(data);
            return(result);
        }
Exemplo n.º 19
0
        public async Task <AppActionResult> AddSending(long noteId, AppActionResult actionResult)
        {
            try
            {
                var sending = new Sending
                {
                    NoteId   = noteId,
                    SendDate = DateTime.Now,
                    Success  = actionResult.Success,
                    Error    = actionResult.Error
                };
                DbContext.Sendings.Add(sending);
                await DbContext.SaveChangesAsync();

                return(new AppActionResult(true));
            }
            catch (Exception ex)
            {
                return(new AppActionResult(false,
                                           $"{Resource.DbErrorAddSending}\r\t{ex.Message}"));
            }
        }
Exemplo n.º 20
0
        public async Task <IAppActionResult> SynchronizeData(IFormFile file)
        {
            IReader <XLWorkbook, ReadModelForExcel> reader = new ReaderFromExcel(Localizer);
            var result     = new AppActionResult();
            var resultData = validator.ValidateFile(file);

            result.SetResult(resultData);
            if (!result.IsSuccess)
            {
                return(result);
            }
            var readResult = reader.Read(resultData.Data);

            readResult.SetStatus(HttpStatusCode.BadRequest, HttpStatusCode.OK);
            result.SetResult(readResult);
            if (!result.IsSuccess)
            {
                return(result);
            }
            bool isSave = false;
            var  allPos = await UnitOfWork.Positions.GetAllAsync();

            var positionNames    = readResult.Data.Positions.Select(x => x.Name).ToList();
            var posWhichNotExist = allPos.Where(x => !positionNames.Contains(x.Name)).ToList();

            if (posWhichNotExist.Count != 0)
            {
                UnitOfWork.Positions.DeleteRange(posWhichNotExist);
                await UnitOfWork.SaveChangesAsync();
            }
            var allEmp = await UnitOfWork.Employees.GetAllAsync();

            var empWhichNotExist = allEmp.Where(x => !readResult.Data.Employees
                                                .Any(e => e.Surname == x.Surname && e.FirstName == x.FirstName && e.Patronymic == x.Patronymic)).ToList();

            if (empWhichNotExist.Count != 0)
            {
                UnitOfWork.Employees.DeleteRange(empWhichNotExist);
                isSave = true;
            }
            var empWhichExist = readResult.Data.Employees.Where(x => !allEmp
                                                                .Any(e => e.Surname == x.Surname && e.FirstName == x.FirstName && e.Patronymic == x.Patronymic)).ToList();
            var empWhichExistByPos = allEmp.Where(x => positionNames.Contains(x.Position.Name)).ToList();

            if (empWhichExistByPos.Count != 0)
            {
                empWhichExist.ForEach(x =>
                {
                    var emp = empWhichExistByPos.Find(y => y.Position.Name == x.Position.Name);
                    if (emp != null)
                    {
                        x.PositionId = emp.PositionId;
                        x.Position   = null;
                    }
                });
            }
            if (empWhichExist.Count != 0)
            {
                await UnitOfWork.Employees.AddRangeAsync(empWhichExist);

                isSave = true;
            }
            if (isSave)
            {
                await UnitOfWork.SaveChangesAsync();
            }
            return(result);
        }
Exemplo n.º 21
0
        public AppActionResult InvokeAction(string name, IEnumerable <Guid> ids)
        {
            string    entityName = typeof(TEntity).Name;
            Stopwatch sw         = new Stopwatch();

            sw.Start();

            var singleActions = _serviceProvider.GetService <IEnumerable <IAppAction <TEntity> > >();
            var singleAction  = singleActions.FirstOrDefault(x => x.GetType().Name.ToLowerFirstLetter() == name);

            var groupActions = _serviceProvider.GetService <IEnumerable <IGroupAppAction <TEntity> > >();
            var groupAction  = groupActions.FirstOrDefault(x => x.GetType().Name.ToLowerFirstLetter() == name);

            Log.Information("{entityName}.InvokeAction (Load role): {ElapsedMilliseconds}ms", entityName,
                            sw.ElapsedMilliseconds);
            sw.Restart();

            if (singleAction == null && groupAction == null)
            {
                return new AppActionResult
                       {
                           IsError = true,
                           Message = $"Action {name} not found"
                       }
            }
            ;

            var currentUser = _userIdProvider.GetCurrentUser();
            var role        = currentUser.RoleId.HasValue ? _dataService.GetById <Role>(currentUser.RoleId.Value) : null;
            var dbSet       = _dataService.GetDbSet <TEntity>();

            var entities = dbSet.Where(x => ids.Contains(x.Id));

            AppActionResult result;

            if (groupAction != null)
            {
                string actionName = groupAction.GetType().Name.ToLowerFirstLetter();

                bool isActionAllowed = role?.Actions == null || role.Actions.Contains(actionName);
                if (isActionAllowed && groupAction.IsAvailable(entities))
                {
                    result = groupAction.Run(currentUser, entities);
                }
                else
                {
                    result = new AppActionResult
                    {
                        IsError = false,
                        Message = "Done"
                    };
                }
            }
            else
            {
                List <string> messages        = new List <string>();
                string        actionName      = singleAction.GetType().Name.ToLowerFirstLetter();
                bool          isActionAllowed = role?.Actions == null || role.Actions.Contains(actionName);
                if (isActionAllowed)
                {
                    foreach (var entity in entities)
                    {
                        if (isActionAllowed && singleAction.IsAvailable(entity))
                        {
                            string message = singleAction.Run(currentUser, entity)?.Message;
                            if (!string.IsNullOrEmpty(message))
                            {
                                messages.Add(message);
                            }
                        }
                    }
                }

                result = new AppActionResult
                {
                    IsError = false,
                    Message = string.Join(". ", messages)
                };
            }

            Log.Information("{entityName}.InvokeAction (Apply action): {ElapsedMilliseconds}ms", entityName,
                            sw.ElapsedMilliseconds);
            sw.Restart();

            _triggersService.Execute();
            Log.Information("{entityName}.InvokeAction (Execure triggers): {ElapsedMilliseconds}ms", entityName,
                            sw.ElapsedMilliseconds);
            sw.Restart();

            _dataService.SaveChanges();
            Log.Information("{entityName}.InvokeAction (Save changes): {ElapsedMilliseconds}ms", entityName,
                            sw.ElapsedMilliseconds);

            return(result);
        }
Exemplo n.º 22
0
        public AppActionResult InvokeBulkUpdate(string fieldName, IEnumerable <Guid> ids, string value)
        {
            string entityName   = typeof(TEntity).Name;
            string propertyName = fieldName?.ToUpperFirstLetter();

            Stopwatch sw = new Stopwatch();

            sw.Start();

            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            var propertyType = typeof(TFormDto).GetProperty(propertyName);

            if (propertyType == null)
            {
                throw new ArgumentException("Unknown field", nameof(propertyName));
            }

            var dbSet = _dataService.GetDbSet <TEntity>();

            var entities      = dbSet.Where(x => ids.Contains(x.Id)).ToList();
            var validEntities = entities.Where(i => !_rules.ContainsKey(propertyName) || _rules[propertyName](i));

            var dtos = validEntities.Select(MapFromEntityToFormDto).ToArray();

            Log.Information("{entityName}.InvokeBulkUpdate (Load from DB): {ElapsedMilliseconds}ms", entityName,
                            sw.ElapsedMilliseconds);
            sw.Restart();

            object validValue = value;

            if (propertyType.PropertyType == typeof(int?))
            {
                validValue = ParseInt(value);
            }

            if (propertyType.PropertyType == typeof(decimal?))
            {
                validValue = ParseDecimal(value);
            }

            if (propertyType.PropertyType == typeof(bool?))
            {
                validValue = ParseBool(value);
            }

            if (propertyType.PropertyType == typeof(LookUpDto))
            {
                validValue = value == null ? null : new LookUpDto {
                    Value = value
                };
            }

            foreach (var dto in dtos)
            {
                propertyType.SetValue(dto, validValue);
            }

            var importResult = new List <ValidateResult>();

            foreach (var dto in dtos)
            {
                importResult.Add(SaveOrCreateInner(dto));
            }
            Log.Information("{entityName}.InvokeBulkUpdate (Import): {ElapsedMilliseconds}ms", entityName,
                            sw.ElapsedMilliseconds);

            string errors = string.Join(" ", importResult.Where(x => x.IsError).Select(x => x.Error));
            var    result = new AppActionResult
            {
                IsError = !string.IsNullOrWhiteSpace(errors),
                Message = errors
            };

            if (!result.IsError)
            {
                string lang       = _userIdProvider.GetCurrentUser()?.Language;
                string entityType = typeof(TEntity).Name.ToLower();
                string numbers    = string.Join(", ", dtos.Select(GetNumber));
                result.Message = $"field_bulk_updated_{entityType}".Translate(lang, numbers);
            }

            return(result);
        }
Exemplo n.º 23
0
 private async Task <AppActionResult> TryAddResultToDatabase(Note note, AppActionResult result)
 {
     return(await databaseService.AddSending(note.Id, result));
 }