示例#1
0
        public async Task <HmmNote> UpdateAsync(HmmNote entity)
        {
            Guard.Against <ArgumentNullException>(entity == null, nameof(entity));

            try
            {
                // check if need apply default catalog
                // ReSharper disable once PossibleNullReferenceException
                var catalog = PropertyChecking(entity.Catalog);
                entity.Catalog = catalog ?? throw new Exception("Cannot find default note catalog.");

                entity.LastModifiedDate = DateTimeProvider.UtcNow;
                DataContext.Notes.Update(entity);
                await DataContext.SaveAsync();

                var savedRec = LookupRepo.GetEntity <HmmNote>(entity.Id);

                return(savedRec);
            }
            catch (Exception ex)
            {
                ProcessMessage.WrapException(ex);
                return(null);
            }
        }
示例#2
0
 public PaymentController()
 {
     _PaymentRepo = new PaymentRepo(ConnString);
     _WorkRepo    = new WorkRepo(ConnString);
     _JobRepo     = new JobRepo(ConnString);
     _LookupRepo  = new LookupRepo(ConnString);
 }
示例#3
0
        public void Cannot_Update_Invalid_Note()
        {
            // Arrange
            var note = new HmmNote
            {
                Author      = _user,
                Description = "testing note",
                Subject     = "testing note is here",
                Content     = "<root><time>2017-08-01</time></root>"
            };

            CurrentTime = new DateTime(2021, 4, 4, 8, 15, 0);
            _manager.Create(note);

            Assert.True(_manager.ProcessResult.Success);
            var savedRec = NoteRepository.GetEntities().FirstOrDefault();

            Assert.NotNull(savedRec);
            Assert.Equal("jfang", savedRec.Author.AccountName);

            // change the note render
            var newUser = LookupRepo.GetEntities <Author>().FirstOrDefault(u => u.AccountName != "jfang");

            Assert.NotNull(newUser);
            note.Author = newUser;
            _testValidator.GetInvalidResult = true;

            // Act
            savedRec = _manager.Update(note);

            // Assert
            Assert.False(_manager.ProcessResult.Success);
            Assert.Null(savedRec);
            Assert.False(note.IsDeleted);
        }
示例#4
0
        public IActionResult Index(LookupViewModel vm, string buttonValue)
        {
            switch (buttonValue)
            {
            case "Save":
                if (ModelState.IsValid)
                {
                    vm.EditLookup.GroupId = vm.SelectedGroupId;
                    LookupRepo.SaveLookup(vm.EditLookup);
                    vm.EditLookup = new TimeCard.Domain.Lookup();
                    ModelState.Clear();
                }
                break;

            case "Delete":
                LookupRepo.DeleteLookup(vm.EditLookup.Id);
                break;

            default:
                vm.EditLookup = new TimeCard.Domain.Lookup();
                ModelState.Clear();
                break;
            }
            prepIndex(vm);
            return(View(vm));
        }
示例#5
0
 private void SetupTestEnv()
 {
     InsertSeedRecords();
     _user      = LookupRepo.GetEntities <Author>().FirstOrDefault();
     _validator = new NoteValidator(NoteRepository);
     _manager   = new HmmNoteManager(NoteRepository, _validator, DateProvider);
 }
示例#6
0
 private IEnumerable <SelectListItem> GetLookup(string group)
 {
     return(LookupRepo.GetLookups(group, "- Select -").Where(x => x.Id == 0 || x.Active == true)
            .Select(x => new SelectListItem {
         Text = x.Descr, Value = x.Id.ToString()
     }));
 }
示例#7
0
        public NoteRender Update(NoteRender entity)
        {
            Guard.Against <ArgumentNullException>(entity == null, nameof(entity));

            // ReSharper disable once PossibleNullReferenceException
            if (entity.Id <= 0)
            {
                ProcessMessage.Success = false;
                ProcessMessage.AddErrorMessage($"Can not update NoteRender with id {entity.Id}", true);
                return(null);
            }

            try
            {
                // make sure the record exists in data source
                DataContext.Renders.Update(entity);
                DataContext.Save();
                return(LookupRepo.GetEntity <NoteRender>(entity.Id));
            }
            catch (Exception ex)
            {
                ProcessMessage.WrapException(ex);
                return(null);
            }
        }
示例#8
0
        public async Task <Subsystem> UpdateAsync(Subsystem entity)
        {
            Guard.Against <ArgumentNullException>(entity == null, nameof(entity));

            // ReSharper disable once PossibleNullReferenceException
            if (entity.Id <= 0)
            {
                ProcessMessage.Success = false;
                ProcessMessage.AddErrorMessage($"Can not update Subsystem with id {entity.Id}", true);
                return(null);
            }

            try
            {
                // make sure the record exists in data source
                DataContext.Subsystems.Update(entity);
                await DataContext.SaveAsync();

                return(LookupRepo.GetEntity <Subsystem>(entity.Id));
            }
            catch (Exception ex)
            {
                ProcessMessage.WrapException(ex);
                return(null);
            }
        }
示例#9
0
        protected TP PropertyChecking <TP>(TP property) where TP : HasDefaultEntity
        {
            var defaultNeeded = false;

            if (property == null)
            {
                defaultNeeded = true;
            }
            else if (property.Id <= 0)
            {
                defaultNeeded = true;
            }
            else if (LookupRepo.GetEntity <TP>(property.Id) == null)
            {
                defaultNeeded = true;
            }

            if (!defaultNeeded)
            {
                return(property);
            }

            var defaultProp = LookupRepo.GetEntities <TP>(p => p.IsDefault).FirstOrDefault();

            return(defaultProp);
        }
示例#10
0
        public ActionResult GenerateDocs(int contractorId, int cycle)
        {
            var templateFile = new FileInfo($"{WebRootPath}\\Content\\TimeCardTemplates.xlsx");

            try
            {
                string name = LookupRepo.GetLookups("Contractor").Where(x => x.Id == contractorId).FirstOrDefault()?.Descr;

                var fileList = new List <string>();
                GenerateTimeCards(contractorId, name, templateFile, cycle, fileList);
                GenerateTimeBooks(contractorId, name, templateFile, cycle, fileList);
                GenerateInvoices(contractorId, name, templateFile, cycle, fileList);
                GenerateSummary(contractorId, name, templateFile, cycle, fileList);
                if (!fileList.Any())
                {
                    return(Json(new { success = false, message = "Nothing to generate." }));
                }


                string zipFile = $"C:\\TEMP\\{name}.zip";
                TempData["Download"] = JsonConvert.SerializeObject(new Infrastructure.ZipDownload {
                    FileName = zipFile, FileList = fileList
                });
                return(Json(new { success = true }));
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, message = ex.Message }));
            }
        }
示例#11
0
        public void CannotChangeAuthorForExistsNote()
        {
            // Arrange
            var note = new HmmNote
            {
                Author      = _user,
                Description = "testing note",
                Subject     = "testing note is here",
                Content     = "<root><time>2017-08-01</time></root>",
                Catalog     = new NoteCatalog()
            };

            CurrentTime = new DateTime(2021, 4, 4, 8, 15, 0);
            _manager.Create(note);

            Assert.True(_manager.ProcessResult.Success);
            var savedRec = NoteRepository.GetEntities().FirstOrDefault();

            Assert.NotNull(savedRec);
            Assert.Equal("jfang", savedRec.Author.AccountName);

            // change the note render
            var newUser = LookupRepo.GetEntities <Author>().FirstOrDefault(u => u.AccountName != "jfang");

            Assert.NotNull(newUser);
            note.Author = newUser;

            // Act
            var processResult = new ProcessingResult();
            var result        = _validator.IsValidEntity(note, processResult);

            // Assert
            Assert.False(result);
        }
示例#12
0
 public PaymentController(IConfiguration config, IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor) : base(config, webHostEnvironment, httpContextAccessor)
 {
     _PaymentRepo = new PaymentRepo(ConnString);
     _WorkRepo    = new WorkRepo(ConnString);
     _JobRepo     = new JobRepo(ConnString);
     _LookupRepo  = new LookupRepo(ConnString);
 }
示例#13
0
        public NoteCatalog Update(NoteCatalog entity)
        {
            Guard.Against <ArgumentNullException>(entity == null, nameof(entity));

            // ReSharper disable once PossibleNullReferenceException
            if (entity.Id <= 0)
            {
                ProcessMessage.Success = false;
                ProcessMessage.AddErrorMessage($"Can not update NoteCatalog with id {entity.Id}", true);
                return(null);
            }

            try
            {
                // check if need apply default render
                var          render  = PropertyChecking(entity.Render);
                const string message = "Cannot find default note render.";
                ProcessMessage.Success = false;
                ProcessMessage.AddErrorMessage(message, true);
                entity.Render = render ?? throw new DataSourceException(message);

                DataContext.Catalogs.Update(entity);
                DataContext.Save();
                return(LookupRepo.GetEntity <NoteCatalog>(entity.Id));
            }
            catch (Exception ex)
            {
                ProcessMessage.WrapException(ex);
                return(null);
            }
        }
示例#14
0
        /// <summary>
        /// The asynchronous version of <see cref="GetNotes"/>
        /// </summary>
        /// <param name="entity">The entity which used to get type and figure out the catalog</param>
        /// <param name="resourceCollectionParameters">The page information of the resource collection</param>
        /// <returns>The notes which belongs to entity type</returns>
        protected async Task <PageList <HmmNote> > GetNotesAsync(T entity, Expression <Func <HmmNote, bool> > query = null, ResourceCollectionParameters resourceCollectionParameters = null)
        {
            var catId = await entity.GetCatalogIdAsync(LookupRepo);

            var author = await LookupRepo.GetEntityAsync <Author>(DefaultAuthor.Id);

            var hasValidAuthor = DefaultAuthor != null && author != null;

            switch (hasValidAuthor)
            {
            case false:
                ProcessResult.AddErrorMessage("Cannot find default author", true);
                return(null);

            default:

                PageList <HmmNote> notes;
                if (query != null)
                {
                    var finalExp = query.And(n => n.Author.Id == DefaultAuthor.Id && n.Catalog.Id == catId);
                    notes = await NoteManager.GetNotesAsync(finalExp, false, resourceCollectionParameters);
                }
                else
                {
                    notes = await NoteManager.GetNotesAsync(n => n.Author.Id == DefaultAuthor.Id && n.Catalog.Id == catId, false, resourceCollectionParameters);
                }

                return(notes);
            }
        }
示例#15
0
        /// <summary>
        /// Get notes for specific entity
        /// </summary>
        /// <param name="id">The id of entity to get type and figure out the catalog</param>
        /// <param name="entity">The entity by id which used to get type and figure out the catalog</param>
        /// <returns>The notes which belongs to entity type</returns>
        protected async Task <HmmNote> GetNoteAsync(int id, T entity)
        {
            var catId = await entity.GetCatalogIdAsync(LookupRepo);

            var hasValidAuthor = DefaultAuthor != null && LookupRepo.GetEntity <Author>(DefaultAuthor.Id) != null;

            switch (hasValidAuthor)
            {
            case false:
                ProcessResult.AddErrorMessage("Cannot find default author", true);
                return(null);

            default:

                var note = await NoteManager.GetNoteByIdAsync(id);

                if (note == null)
                {
                    return(null);
                }

                if (note.Author.Id == DefaultAuthor.Id && note.Catalog.Id == catId)
                {
                    return(note);
                }

                return(null);
            }
        }
示例#16
0
        private void prepWork(Models.WorkViewModel vm, bool clearEdit = false)
        {
            var cycles = GetPayCycles();
            int cycle  = int.Parse(cycles.First().Value);

            vm.WorkTypes = LookupRepo.GetLookups("WorkType", "- Select -").Select(x => new SelectListItem {
                Text = x.Descr, Value = x.Id.ToString()
            });
            vm.PayCycles     = cycles;
            vm.IsCycleOpen   = false;
            vm.CanCloseCycle = true;
            if (vm.SelectedCycle == 0)
            {
                vm.SelectedCycle = cycle;
            }
            if (vm.SelectedCycle == cycle)
            {
                vm.IsCycleOpen   = true;
                vm.CanCloseCycle = false;
            }

            vm.Jobs = _JobRepo.GetJobsForWork(vm.SelectedContractorId, vm.SelectedCycle).Select(x => new SelectListItem {
                Text = x.Descr, Value = x.Id.ToString()
            });

            vm.WorkEntries = _WorkRepo.GetWork(vm.SelectedContractorId, vm.SelectedCycle, true);
            if (vm.SortByJob)
            {
                vm.WorkEntries = vm.WorkEntries.OrderBy(x => x.Job).ThenBy(x => x.WorkDay);
            }
            if (vm.EditWork == null)
            {
                vm.EditWork = new TimeCard.Domain.Work {
                    ContractorId = vm.SelectedContractorId, WorkDay = DateRef.GetWorkDay(DateTime.Today)
                };
            }
            if (clearEdit)
            {
                vm.EditWork = new TimeCard.Domain.Work {
                    ContractorId = vm.SelectedContractorId, WorkDay = vm.EditWork.WorkDay, JobId = vm.EditWork.JobId, WorkType = vm.EditWork.WorkType
                };
            }
            vm.EditDays    = GetEditDays(vm.SelectedCycle);
            vm.DailyTotals = new decimal[2][];
            for (int i = 0; i < 2; i++)
            {
                vm.DailyTotals[i] = new decimal[8];
                for (int j = 0; j < 7; j++)
                {
                    vm.DailyTotals[i][j]  = vm.WorkEntries.Where(x => x.WeekDay == j + i * 7).Sum(x => x.Hours);
                    vm.DailyTotals[i][7] += vm.DailyTotals[i][j];
                }
            }

            if (!vm.IsCycleOpen)
            {
                vm.IsCycleOpen = _WorkRepo.GetWorkOpen(vm.SelectedContractorId).Any(x => x == vm.SelectedCycle);
            }
        }
示例#17
0
        public ActionResult Index()
        {
            int contractorId = LookupRepo.GetLookupByVal("Contractor", CurrentUsername).Id;
            var jobs         = _JobRepo.GetJobStart(contractorId);

            return(View(new ViewModels.JobViewModel {
                ContractorId = contractorId, Jobs = jobs
            }));
        }
示例#18
0
        private IApplication GetApplication()
        {
            var user   = LookupRepo.GetEntities <Author>().FirstOrDefault();
            var system = new Subsystem
            {
                DefaultAuthor = user,
            };

            var fakeApplication = new Mock <IApplication>();

            fakeApplication.Setup(app => app.GetApplication(LookupRepo)).Returns(system);
            fakeApplication.Setup(app => app.GetCatalog(It.IsAny <NoteCatalogType>(), It.IsAny <IEntityLookup>())).Returns((NoteCatalogType type, IEntityLookup lookupRepo) =>
            {
                NoteCatalog catalog;
                switch (type)
                {
                case NoteCatalogType.Automobile:
                    catalog = LookupRepo.GetEntities <NoteCatalog>()
                              .FirstOrDefault(c => c.Name == AutomobileConstant.AutoMobileInfoCatalogName);
                    if (catalog != null)
                    {
                        var schemaStr  = File.ReadAllText("Automobile.xsd");
                        catalog.Schema = schemaStr;
                    }
                    break;

                case NoteCatalogType.GasDiscount:
                    catalog = LookupRepo.GetEntities <NoteCatalog>()
                              .FirstOrDefault(c => c.Name == AutomobileConstant.GasDiscountCatalogName);
                    if (catalog != null)
                    {
                        var schemaStr  = File.ReadAllText("Discount.xsd");
                        catalog.Schema = schemaStr;
                    }
                    break;

                case NoteCatalogType.GasLog:
                    catalog = LookupRepo.GetEntities <NoteCatalog>()
                              .FirstOrDefault(c => c.Name == AutomobileConstant.GasLogCatalogName);
                    if (catalog != null)
                    {
                        var schemaStr  = File.ReadAllText("GasLog.xsd");
                        catalog.Schema = schemaStr;
                    }
                    break;

                default:
                    catalog = null;
                    break;
                }

                return(catalog);
            });

            return(fakeApplication.Object);
        }
示例#19
0
 void prepIndex(LookupViewModel vm)
 {
     vm.LookupGroups = LookupRepo.GetGroups().Select(x => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem {
         Value = x.GroupId.ToString(), Text = x.Descr
     });
     if (vm.SelectedGroupId != 0)
     {
         vm.Lookups = LookupRepo.GetLookups(vm.SelectedGroupId);
     }
 }
示例#20
0
        public ActionResult Index()
        {
            var vm = new ViewModels.WorkViewModel {
                Contractor = LookupRepo.GetLookupByVal("Contractor", CurrentUsername)
            };

            Session["Contractor"] = vm.Contractor;
            prepWork(vm);
            return(View(vm));
        }
示例#21
0
        public void Can_Update_Subsystem()
        {
            // Arrange
            Assert.NotNull(_author);
            var sys = new Subsystem
            {
                Name          = "Test Subsystem",
                DefaultAuthor = _author,
                Description   = "Default Subsystem",
                NoteCatalogs  = new List <NoteCatalog>
                {
                    new()
                    {
                        Name   = "Test Catalog1",
                        Schema = "Test Catalog1 Schema",
                        Render = new NoteRender
                        {
                            Name        = "Test Catalog1 Render",
                            Namespace   = "Hmm.Render",
                            Description = "This is description of test catalog1 render"
                        }
                    },
                    new ()
                    {
                        Name   = "Test Catalog2",
                        Schema = "Test Catalog2 Schema",
                        Render = new NoteRender
                        {
                            Name        = "Test Catalog2 Render",
                            Namespace   = "Hmm.Render",
                            Description = "This is description of test catalog2 render"
                        }
                    }
                }
            };
            var newSys   = SubsystemRepository.Add(sys);
            var savedSys = LookupRepo.GetEntities <Subsystem>().FirstOrDefault(s => s.Id == newSys.Id);

            Assert.NotNull(savedSys);

            // Act
            savedSys.Description = "changed default Subsystem";
            var firstCatalog = savedSys.NoteCatalogs.First();

            Assert.NotNull(firstCatalog);
            firstCatalog.Name        = "Updated Test Catalog1";
            firstCatalog.Render.Name = "Update Test Catalog1 Render Name";
            var updatedSys = SubsystemRepository.Update(savedSys);

            // Assert
            Assert.NotNull(updatedSys);
            Assert.Equal("changed default Subsystem", updatedSys.Description);
            Assert.True(SubsystemRepository.ProcessMessage.Success);
        }
        private void SetupTestEnv()
        {
            InsertSeedRecords();
            _user = LookupRepo.GetEntities <Author>().FirstOrDefault();
            var schemaStr = File.ReadAllText("NotebaseSchema.xsd");
            var catalog   = new NoteCatalog {
                Schema = schemaStr
            };

            _noteSerializer = new TestDefaultXmlNoteSerializer(new NullLogger <HmmNote>(), catalog);
        }
示例#23
0
        private void SetupDevEnv()
        {
            InsertSeedRecords();
            var catalog = LookupRepo.GetEntities <NoteCatalog>()
                          .FirstOrDefault(c => c.Name == AutomobileConstant.GasDiscountCatalogName);

            Assert.NotNull(catalog);
            var noteSerializer = new GasDiscountXmlNoteSerializer(Application, new NullLogger <GasDiscount>(), LookupRepo);
            var noteManager    = new HmmNoteManager(NoteRepository, new NoteValidator(NoteRepository), DateProvider);

            _manager  = new DiscountManager(noteSerializer, new GasDiscountValidator(LookupRepo), noteManager, LookupRepo);
            _authorId = ApplicationRegister.DefaultAuthor.Id;
        }
示例#24
0
        private void SetupDevEnv()
        {
            InsertSeedRecords();

            // add testing note catalog
            var catalog = LookupRepo.GetEntities <NoteCatalog>()
                          .FirstOrDefault(c => c.Name == AutomobileConstant.AutoMobileInfoCatalogName);

            Assert.NotNull(catalog);
            var noteSerializer = new AutomobileXmlNoteSerializer(Application, new NullLogger <AutomobileInfo>(), LookupRepo);
            var noteManager    = new HmmNoteManager(NoteRepository, new NoteValidator(NoteRepository), DateProvider);

            _manager = new AutomobileManager(noteSerializer, new AutomobileValidator(LookupRepo), noteManager, LookupRepo);
        }
示例#25
0
        public void Can_Check_Author_Exists(string authorId, bool expected)
        {
            // Arrange
            var id = authorId;

            if (authorId == "FirstID")
            {
                id = LookupRepo.GetEntities <Author>().FirstOrDefault()?.Id.ToString();
            }

            // Act
            var result = _authorManager.AuthorExists(id);

            // Assert
            Assert.Equal(result, expected);
        }
示例#26
0
        public void Dispose()
        {
            if (_dbContext is DbContext context)
            {
                context.Reset();
            }

            var systems = LookupRepo.GetEntities <Subsystem>().ToList();

            foreach (var sys in systems)
            {
                SubsystemRepository.Delete(sys);
            }
            var notes = LookupRepo.GetEntities <HmmNote>().ToList();

            foreach (var note in notes)
            {
                NoteRepository.Delete(note);
            }

            var catalogs = LookupRepo.GetEntities <NoteCatalog>().ToList();

            foreach (var catalog in catalogs)
            {
                CatalogRepository.Delete(catalog);
            }

            var renders = LookupRepo.GetEntities <NoteRender>().ToList();

            foreach (var render in renders)
            {
                RenderRepository.Delete(render);
            }

            var authors = LookupRepo.GetEntities <Author>().ToList();

            foreach (var author in authors)
            {
                AuthorRepository.Delete(author);
            }

            if (_dbContext is DbContext newContext)
            {
                newContext.Reset();
            }
            GC.SuppressFinalize(this);
        }
示例#27
0
        public override bool IsValid(HmmNote entity, bool isNewEntity)
        {
            if (entity == null)
            {
                ValidationErrors.Add("Error: null note found.");
                return(false);
            }

            // make sure note author is exists
            if (isNewEntity)
            {
                if (!IsAuthorValid(entity.Author))
                {
                    return(false);
                }
            }

            if (!isNewEntity)
            {
                if (entity.Id <= 0)
                {
                    ValidationErrors.Add($"The note get invalid id {entity.Id}");
                    return(false);
                }

                var rec = LookupRepo.GetEntity <HmmNote>(entity.Id);
                if (rec == null)
                {
                    ValidationErrors.Add($"Cannot find note with id {entity.Id} from data source");
                    return(false);
                }

                // check if user want to update author for note which does not allowed by system
                var newAuthorId = entity.Author.Id;
                if (rec.Author.Id != newAuthorId)
                {
                    ValidationErrors.Add($"Cannot update note: {entity.Id}'s author. current author id: {rec.Id}, new author id: {newAuthorId}");
                    return(false);
                }
            }

            return(true);
        }
示例#28
0
        private bool IsAuthorValid(User author)
        {
            // make sure note author is exists
            if (author == null || author.Id <= 0)
            {
                ValidationErrors.Add("Error: invalid author attached to note.");
                return(false);
            }

            var savedAuthor = LookupRepo.GetEntity <User>(author.Id);

            if (savedAuthor == null)
            {
                ValidationErrors.Add("Error: cannot find author from data source.");
                return(false);
            }

            return(true);
        }
示例#29
0
        public async Task <PageList <NoteRender> > GetEntitiesAsync(Expression <Func <NoteRender, bool> > query = null, ResourceCollectionParameters resourceCollectionParameters = null)
        {
            var renders = await LookupRepo.GetEntitiesAsync(query, resourceCollectionParameters);

            return(renders);
        }
示例#30
0
 public PageList <NoteRender> GetEntities(Expression <Func <NoteRender, bool> > query = null, ResourceCollectionParameters resourceCollectionParameters = null)
 {
     return(LookupRepo.GetEntities(query, resourceCollectionParameters));
 }