예제 #1
0
        public async Task GetCharityByKeyRequest_Handle_Returns_Null()
        {
            CharityContext.OpenInMemoryConnection();
            try
            {
                //Arrange

                using (var context = CharityContext.GetInMemoryContext())
                {
                    var charity = new Charity
                    {
                        CharityKey    = Guid.NewGuid(),
                        Name          = "testNameCharity",
                        OwnerUserName = "******",
                        Email         = "*****@*****.**",
                        Category      = Core.Enums.Category.None,
                        KVKNumber     = "",
                        IBAN          = "0-IBAN",
                        CoverImage    = "",
                        Slogan        = "Test"
                    };

                    context.Add(charity);
                    context.SaveChanges();
                }
                var request = new GetCharityByKeyRequest();

                GetCharityByKeyResponse response;

                //Act
                using (var context = CharityContext.GetInMemoryContext())
                {
                    var handler = new GetCharityByKeyRequestHandler(context, AutoMapperHelper.BuildMapper(new MappingProfile()));
                    response = await handler.Handle(request);
                }

                //Assert
                Assert.IsFalse(response.IsSuccess);
            }
            finally
            {
                CharityContext.CloseInMemoryConnection();
            }
        }
        public async Task GetStoryByKeyRequestHandler_Handle_Returns_Story()
        {
            StoryContext.OpenInMemoryConnection();

            try
            {
                var charity = new Charity
                {
                    CharityKey = Guid.NewGuid()
                };

                var story = new Story
                {
                    StoryKey = Guid.NewGuid(),
                    Title    = "title",
                    Charity  = charity
                };

                using (var context = StoryContext.GetInMemoryContext())
                {
                    context.Stories.Add(story);
                    context.SaveChanges();
                }

                GetStoryByKeyResponse response;
                using (var context = StoryContext.GetInMemoryContext())
                {
                    var handler = new GetStoryByKeyRequestHandler(context, AutoMapperHelper.BuildMapper(new MappingProfile()));
                    response = await handler.Handle(new GetStoryByKeyRequest
                    {
                        StoryKey = story.StoryKey
                    });
                }

                Assert.IsTrue(response.IsSuccess);
                Assert.AreEqual(story.StoryKey, response.Story.StoryKey);
                Assert.AreEqual(story.Title, response.Story.Title);
                Assert.IsNull(response.Story.AuthorUserKey);
            }
            finally
            {
                StoryContext.CloseInMemoryConnection();
            }
        }
예제 #3
0
        public async Task <OutputResponse> Add(PatientFacilityMovementDTO movement)
        {
            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var mappedMovement = new AutoMapperHelper <PatientFacilityMovementDTO, PatientFacilityMovements>().MapToObject(movement);
                mappedMovement.DateCreated = DateTime.UtcNow;

                await _context.PatientFacilityMovements.AddAsync(mappedMovement);

                await _context.SaveChangesAsync();

                scope.Complete();
            }
            return(new OutputResponse
            {
                IsErrorOccured = false,
                Message = MessageHelper.AddNewSuccess
            });
        }
예제 #4
0
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="array"></param>
        public void Update(ResourceDto entity, int[] array)
        {
            var info       = AutoMapperHelper.Signle <ResourceDto, Resource>(entity);
            var resourceId = info.ResourceId;

            using (_unitOfWork)
            {
                var repository          = _unitOfWork.Repository <Resource>();
                var operationRepository = _unitOfWork.Repository <Operation>();

                Expression <Func <Resource, bool> > where = w => w.ResourceId == resourceId || w.Code == entity.Code;
                var resource = repository.Get(where, "Operations");
                if (info.ResourceId <= 0)
                {
                    info.ResourceId = resource.ResourceId;
                }
                repository.CurrentValue(resource, info);

                var list = resource.Operations.Where(r => array != null &&
                                                     !array.Contains(r.OperationId)).ToList();
                list.ForEach(c => resource.Operations.Remove(c));
                if (array != null)
                {
                    //2.0  求差集
                    var operationIdArray = resource.Operations.Select(x => x.OperationId).ToArray();
                    var expectedList     = array.Except(operationIdArray);

                    foreach (var operation in expectedList.Select(expected =>
                                                                  new Operation
                    {
                        OperationId = expected
                    }))
                    {
                        operationRepository.Attach(operation);
                        resource.Operations.Add(operation);
                    }
                }

                repository.Update(resource);

                _unitOfWork.Commit();
            }
        }
예제 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var dbOptions = new DbContextOptionsBuilder <InterfaceCoreDB>()
                            .UseSqlServer(Configuration.GetConnectionString("InterfaceCoreDB")).Options;

            services.AddScoped(s => new InterfaceCoreDB(dbOptions));

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddDbContext <InterfaceMonitorDB>(options =>
                                                       options.UseSqlServer(Configuration.GetConnectionString("InterfaceMonitorDB")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddMvc(options =>
            {
                options.Filters.Add <GlobalExceptionFilter>();//设置全局异常处理
            })
            .AddRazorPagesOptions(options =>
            {
                //options.RootDirectory = "/Home";
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
            })
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            // Register no-op EmailSender used by account confirmation and password reset during development
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            services.AddSingleton <IEmailSender, EmailSender>();
            WxSDK.ServiceInject.ConfigureServices(services);//配置WxSDK的依赖服务
            OtherSDK.ServiceInject.ConfigureServices(services);
            BLL.ServiceInject.ConfigureServices(services);
            //AutoMapper的帮助类初始化
            AutoMapperHelper.Initialize();
        }
        public async Task GetCharityActionsRequestHandlerTests_Handle_Returns_CharityActions()
        {
            CharityActionContext.OpenInMemoryConnection();
            try
            {
                using (var context = CharityActionContext.GetInMemoryContext())
                {
                    var charity = new Charity
                    {
                        CharityKey = Guid.NewGuid()
                    };

                    for (var i = 0; i < 25; i++)
                    {
                        context.CharityActions.Add(new CharityAction
                        {
                            CharityActionKey = Guid.NewGuid(),
                            Charity          = charity
                        });
                    }

                    context.SaveChanges();
                }

                GetCharityActionsResponse response;
                using (var context = CharityActionContext.GetInMemoryContext())
                {
                    var handler = new GetCharityActionsRequestHandler(context, AutoMapperHelper.BuildMapper(new MappingProfile()));
                    response = await handler.Handle(new GetCharityActionsRequest
                    {
                        PageNumber = 2,
                        PageSize   = 20
                    });
                }

                Assert.AreEqual(25, response.TotalNumberOfResults);
                Assert.AreEqual(5, response.Results.Count);
            }
            finally
            {
                CharityActionContext.CloseInMemoryConnection();
            }
        }
    public async Task UpdateSistemaCommand_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Mock <IEventHandler> mockServiceBus           = ServiceBusHelper.GetInstance();
        Mock <IHubContext <CpnucleoHub> > mockSignalR = SignalRHelper.GetInstance();

        Guid     sistemaId    = Guid.NewGuid();
        DateTime dataInclusao = DateTime.Now;

        Sistema sistema = MockEntityHelper.GetNewSistema(sistemaId);

        await unitOfWork.SistemaRepository.AddAsync(sistema);

        await unitOfWork.SaveChangesAsync();

        unitOfWork.SistemaRepository.Detatch(sistema);

        UpdateSistemaCommand request = new()
        {
            Sistema = MockViewModelHelper.GetNewSistema(sistemaId, dataInclusao)
        };

        GetSistemaQuery request2 = new()
        {
            Id = sistemaId
        };

        // Act
        SistemaHandler  handler  = new(unitOfWork, mapper, mockServiceBus.Object, mockSignalR.Object);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        SistemaViewModel response2 = await handler.Handle(request2, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
        Assert.True(response2 != null);
        Assert.True(response2.Id == sistemaId);
        Assert.True(response2.DataInclusao.Ticks == dataInclusao.Ticks);
    }
}
    public async Task UpdateRecursoCommand_Handle()
    {
        // Arrange
        IUnitOfWork          unitOfWork = DbContextHelper.GetContext();
        IMapper              mapper     = AutoMapperHelper.GetMappings();
        ICryptographyManager manager    = CryptographyHelper.GetInstance();

        Guid     recursoId    = Guid.NewGuid();
        DateTime dataInclusao = DateTime.Now;

        Recurso recurso = MockEntityHelper.GetNewRecurso(recursoId);

        await unitOfWork.RecursoRepository.AddAsync(recurso);

        await unitOfWork.SaveChangesAsync();

        unitOfWork.RecursoRepository.Detatch(recurso);

        UpdateRecursoCommand request = new()
        {
            Recurso = MockViewModelHelper.GetNewRecurso(recursoId, dataInclusao)
        };

        GetRecursoQuery request2 = new()
        {
            Id = recursoId
        };

        // Act
        RecursoHandler  handler  = new(unitOfWork, mapper, manager);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        RecursoViewModel response2 = await handler.Handle(request2, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
        Assert.True(response2 != null);
        Assert.True(response2.Id == recursoId);
        Assert.True(response2.DataInclusao.Ticks == dataInclusao.Ticks);
        Assert.True(response2.Senha == null);
        Assert.True(response2.Salt == null);
    }
}
    public async Task CreateRecursoCommand_Handle()
    {
        // Arrange
        IUnitOfWork          unitOfWork = DbContextHelper.GetContext();
        IMapper              mapper     = AutoMapperHelper.GetMappings();
        ICryptographyManager manager    = CryptographyHelper.GetInstance();

        CreateRecursoCommand request = new()
        {
            Recurso = MockViewModelHelper.GetNewRecurso()
        };

        // Act
        RecursoHandler  handler  = new(unitOfWork, mapper, manager);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
    }
예제 #10
0
    public async Task GetRecursoTarefaQuery_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Guid sistemaId = Guid.NewGuid();
        await unitOfWork.SistemaRepository.AddAsync(MockEntityHelper.GetNewSistema(sistemaId));

        Guid projetoId = Guid.NewGuid();
        await unitOfWork.ProjetoRepository.AddAsync(MockEntityHelper.GetNewProjeto(sistemaId, projetoId));

        Guid workflowId = Guid.NewGuid();
        await unitOfWork.WorkflowRepository.AddAsync(MockEntityHelper.GetNewWorkflow(workflowId));

        Guid recursoId = Guid.NewGuid();
        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso(recursoId));

        Guid tipoTarefaId = Guid.NewGuid();
        await unitOfWork.TipoTarefaRepository.AddAsync(MockEntityHelper.GetNewTipoTarefa(tipoTarefaId));

        Guid tarefaId = Guid.NewGuid();
        await unitOfWork.TarefaRepository.AddAsync(MockEntityHelper.GetNewTarefa(projetoId, workflowId, recursoId, tipoTarefaId, tarefaId));

        Guid recursoTarefaId = Guid.NewGuid();
        await unitOfWork.RecursoTarefaRepository.AddAsync(MockEntityHelper.GetNewRecursoTarefa(tarefaId, recursoId, recursoTarefaId));

        await unitOfWork.SaveChangesAsync();

        GetRecursoTarefaQuery request = new()
        {
            Id = recursoTarefaId
        };

        // Act
        RecursoTarefaHandler   handler  = new(unitOfWork, mapper);
        RecursoTarefaViewModel response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response != null);
        Assert.True(response.Id != Guid.Empty);
        Assert.True(response.DataInclusao.Ticks != 0);
    }
예제 #11
0
        /// <summary>
        /// 菜单信息
        /// </summary>
        /// <param name="iD"></param>
        /// <returns></returns>
        public Task <RouterDto> GetUserMenuList(long iD)
        {
            List <SysMenu> sysMenuList = _sysUserRepository.GetAll().Where(m => m.DeleteFlag == 0).ToList();
            RouterDto      result      = new RouterDto
            {
                Data = new RouterInfo
                {
                    Router = new List <MenuInfo>()
                }
            };
            List <SysMenuDto> menuDtoList = AutoMapperHelper.MapToList <SysMenu, SysMenuDto>(sysMenuList).ToList();
            //构造递归集合
            List <SysMenuDto> res = Recursion(menuDtoList);

            List <MenuInfo> menuInfoList = BuilderVueRouter(res);

            result.Data.Router = menuInfoList;
            return(Task.FromResult(result));
        }
예제 #12
0
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dictionary"></param>
        public void Add(ContentDto entity, Dictionary <string, object> dictionary)
        {
            var content = AutoMapperHelper.Signle <ContentDto, Content>(entity);

            using (_unitOfWork)
            {
                var repository      = _unitOfWork.Repository <Content>();
                var modelRepository = _unitOfWork.Repository <Model>();

                Expression <Func <Model, bool> > where = w => w.ModelId == entity.ModelId;
                var model = modelRepository.Get(where, "ModelFields");

                BuildContentField(content, model, dictionary);

                repository.Add(content);

                _unitOfWork.Commit();
            }
        }
        public async Task GetUserByKeyRequestHandler_Handle_Returns_User()
        {
            UserContext.OpenInMemoryConnection();

            try
            {
                GetUserByKeyResponse response;
                var request = new GetUserByKeyRequest
                {
                    UserKey = Guid.NewGuid()
                };

                using (var context = UserContext.GetInMemoryContext())
                {
                    context.Users.Add(new User
                    {
                        UserKey   = request.UserKey,
                        FirstName = "john",
                        LastName  = "doe"
                    });

                    context.SaveChanges();
                }

                using (var context = UserContext.GetInMemoryContext())
                {
                    var handler = new GetUserByKeyRequestHandler(context, AutoMapperHelper.BuildMapper(new MappingProfile()));
                    response = await handler.Handle(request);
                }

                using (var context = UserContext.GetInMemoryContext())
                {
                    Assert.IsTrue(response.UserExists);
                    Assert.AreEqual(context.Users.Single().FirstName, response.User.FirstName);
                    Assert.AreEqual(context.Users.Single().LastName, response.User.LastName);
                }
            }
            finally
            {
                UserContext.CloseInMemoryConnection();
            }
        }
예제 #14
0
        public ActionResult SaveZhixing(string jsonArr, string ProjectId, string SupplierId, string GroupId)
        {
            List <Quotation_ZhiXingDto> lstDto = JsonConvert.DeserializeObject <List <Quotation_ZhiXingDto> >(jsonArr);

            foreach (Quotation_ZhiXingDto dtl_dto in lstDto)
            {
                Quotation_Zhixing_Dtl dtl = AutoMapperHelper.MapTo <Quotation_Zhixing_Dtl>(dtl_dto);;
                int QuotationId           = SaveQuotationMst(GroupId, ProjectId, dtl_dto.SupplierId, "Zhixing");
                if (Convert.ToInt32(dtl_dto.QuotationId) == 0 && Convert.ToInt32(dtl_dto.SeqNO) == 0)
                {
                    int seqNo  = 1;
                    var maxOne = db.Quotation_Zhixing_Dtl.Where(x => x.QuotationId == QuotationId)
                                 .OrderByDescending(x => x.SeqNO).Select(x => x.SeqNO).FirstOrDefault();
                    if (maxOne > 0)
                    {
                        seqNo = maxOne + 1;
                    }

                    dtl.QuotationId = QuotationId;
                    dtl.SeqNO       = seqNo;
                    dtl.InDateTime  = DateTime.Now;
                    dtl.InUserId    = UserInfo.UserId;
                    db.Quotation_Zhixing_Dtl.Add(dtl);

                    db.SaveChanges();
                }
                else
                {
                    Quotation_Zhixing_Dtl findOne = db.Quotation_Zhixing_Dtl.Find(dtl.QuotationId, dtl.SeqNO);
                    if (findOne != null)
                    {
                        findOne.AccountUnit = dtl.AccountUnit;
                        findOne.Count       = dtl.Count;
                        findOne.UnitPrice   = dtl.UnitPrice;
                        findOne.Remark      = dtl.Remark;
                    }
                    db.SaveChanges();
                }
            }

            return(Json(""));
        }
예제 #15
0
        public ActionResult SaveBiancheng(string jsonArr, string ProjectId, string SupplierId, string GroupId)
        {
            //List<Quotation_Biancheng_Dtl> lst = JsonConvert.DeserializeObject<List<Quotation_Biancheng_Dtl>>(jsonArr);
            List <Quotation_BianChengDto> lstDto = JsonConvert.DeserializeObject <List <Quotation_BianChengDto> >(jsonArr);

            foreach (Quotation_BianChengDto dtl_dto in lstDto)
            {
                Quotation_Biancheng_Dtl dtl = AutoMapperHelper.MapTo <Quotation_Biancheng_Dtl>(dtl_dto);
                int QuotationId             = SaveQuotationMst(GroupId, ProjectId, dtl_dto.SupplierId, "Biancheng");
                if (dtl.QuotationId == 0 && dtl.SeqNO == 0)
                {
                    int seqNo  = 1;
                    var maxOne = db.Quotation_Biancheng_Dtl.Where(x => x.QuotationId == QuotationId)
                                 .OrderByDescending(x => x.SeqNO).Select(x => x.SeqNO).FirstOrDefault();
                    if (maxOne > 0)
                    {
                        seqNo = maxOne + 1;
                    }

                    dtl.QuotationId = QuotationId;
                    dtl.SeqNO       = seqNo;
                    dtl.InDateTime  = DateTime.Now;
                    dtl.InUserId    = UserInfo.UserId;
                    db.Quotation_Biancheng_Dtl.Add(dtl);

                    db.SaveChanges();
                }
                else
                {
                    Quotation_Biancheng_Dtl findOne = db.Quotation_Biancheng_Dtl.Find(dtl.QuotationId, dtl.SeqNO);
                    if (findOne != null)
                    {
                        findOne.hesuandanwei = dtl.hesuandanwei;
                        findOne.shuliang     = dtl.shuliang;
                        findOne.danjia       = dtl.danjia;
                    }
                    db.SaveChanges();
                }
            }

            return(Json(""));
        }
    public async Task RemoveProjetoCommand_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Guid sistemaId = Guid.NewGuid();

        await unitOfWork.SistemaRepository.AddAsync(MockEntityHelper.GetNewSistema(sistemaId));

        Guid projetoId = Guid.NewGuid();

        Projeto projeto = MockEntityHelper.GetNewProjeto(sistemaId, projetoId);

        await unitOfWork.ProjetoRepository.AddAsync(projeto);

        await unitOfWork.SaveChangesAsync();

        unitOfWork.ProjetoRepository.Detatch(projeto);

        RemoveProjetoCommand request = new()
        {
            Id = projetoId
        };

        GetProjetoQuery request2 = new()
        {
            Id = projetoId
        };

        // Act
        ProjetoHandler  handler  = new(unitOfWork, mapper);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        ProjetoViewModel response2 = await handler.Handle(request2, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
        Assert.True(response2 == null);
    }

    [Fact]
예제 #17
0
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public ContentDto Query(object key)
        {
            using (_unitOfWork)
            {
                var repository      = _unitOfWork.Repository <Content>();
                var content         = repository.Get(Convert.ToInt32(key));
                var modelRepository = _unitOfWork.Repository <Model>();

                Expression <Func <Model, bool> > where = w => w.ModelId == content.ModelId;
                var model = modelRepository.Get(where, "ModelFields");

                var contentDto = AutoMapperHelper.Signle <Content, ContentDto>(content);
                //获取字典集
                var dictionary = BuildDictionary(_unitOfWork, model, Convert.ToInt32(key));

                dynamic obj = new ContentValue(dictionary);
                contentDto.ContentValue = obj;
                return(contentDto);
            }
        }
예제 #18
0
        private IList <RallyArtifact> QueryArtifact(RallyRestApi restApi, IEnumerable <RallyIteration> iterations)
        {
            var request = new Request("Artifact");

            request.Fetch = new List <string>()
            {
                "Name", "FormattedID", "ScheduleState", "c_CrossroadsKanbanState", "Priority", "c_PriorityUS", "Iteration", "DragAndDropRank"
            };
            request.Query = GetDefectAndStoryQuery(iterations);
            request.AddParameter("types", "hierarchicalrequirement,defect");
            request.Order = "DragAndDropRank";

            request.ProjectScopeDown = true;
            request.ProjectScopeUp   = true;

            var results   = RallyApiHelper.LoadResults(restApi, request);
            var artifacts = AutoMapperHelper.MapToListObjects <RallyArtifact>(results);

            return(artifacts);
        }
예제 #19
0
        public bool SaveRefundTicketLog(TraRefundTicketCallBackLogModel t)
        {
            IRefundTicketServerDAL dal = factory.CreateSampleDalObj();
            //TraHoldSeatCallBackLogEntity log = new TraHoldSeatCallBackLogEntity {LogOriginalContent = "233333"};
            //将DomainModel转为DbModel
            TraRefundTicketCallBackLogEntity log2 =
                AutoMapperHelper.DoMap <TraRefundTicketCallBackLogModel, TraRefundTicketCallBackLogEntity>(t);
            List <TraRefundTicketCallBackLogModel> list = new List <TraRefundTicketCallBackLogModel>();

            list.Add(t);
            List <TraRefundTicketCallBackLogEntity> logList =
                (List <TraRefundTicketCallBackLogEntity>)AutoMapperHelper.DoMapList <TraRefundTicketCallBackLogModel, TraRefundTicketCallBackLogEntity>(list);

            dal.Insert(log2);
            //dal.Query(1);
            //log.Orderid = "3333323";
            //dal.Update(log);
            //dal.Delete(log);
            return(true);
        }
        public async Task CreateUserRequestHandler_Handle_Returns_Success()
        {
            UserContext.OpenInMemoryConnection();

            try
            {
                var busMock = new Mock <IBus>();
                busMock.Setup(m => m.PublishAsync(It.IsAny <UserCreatedEvent>())).Returns(Task.FromResult(true));

                CreateUserResponse response;
                var request = new CreateUserRequest
                {
                    UserKey   = Guid.NewGuid(),
                    FirstName = "John",
                    LastName  = "Doe"
                };

                using (var context = UserContext.GetInMemoryContext())
                {
                    var handler = new CreateUserRequestHandler(context, AutoMapperHelper.BuildMapper(new MappingProfile()), busMock.Object);
                    response = await handler.Handle(request);
                }

                using (var context = UserContext.GetInMemoryContext())
                {
                    Assert.AreEqual(1, context.Users.Count());
                    Assert.AreEqual(request.UserKey, context.Users.Single().UserKey);
                    Assert.AreEqual(request.FirstName, context.Users.Single().FirstName);
                    Assert.AreEqual(request.LastName, context.Users.Single().LastName);
                    Assert.AreEqual(request.AddressLine1, context.Users.Single().AddressLine1);
                    Assert.IsNotNull(context.Users.Single().Created);
                    Assert.IsTrue(response.IsSuccess);
                }

                busMock.Verify(m => m.PublishAsync(It.Is <UserCreatedEvent>(e => e.UserKey == request.UserKey && e.FirstName == request.FirstName)), Times.Once);
            }
            finally
            {
                UserContext.CloseInMemoryConnection();
            }
        }
예제 #21
0
    public async Task CreateImpedimentoTarefaCommand_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Guid sistemaId = Guid.NewGuid();
        await unitOfWork.SistemaRepository.AddAsync(MockEntityHelper.GetNewSistema(sistemaId));

        Guid projetoId = Guid.NewGuid();
        await unitOfWork.ProjetoRepository.AddAsync(MockEntityHelper.GetNewProjeto(sistemaId, projetoId));

        Guid workflowId = Guid.NewGuid();
        await unitOfWork.WorkflowRepository.AddAsync(MockEntityHelper.GetNewWorkflow(workflowId));

        Guid recursoId = Guid.NewGuid();
        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso(recursoId));

        Guid tipoTarefaId = Guid.NewGuid();
        await unitOfWork.TipoTarefaRepository.AddAsync(MockEntityHelper.GetNewTipoTarefa(tipoTarefaId));

        Guid tarefaId = Guid.NewGuid();
        await unitOfWork.TarefaRepository.AddAsync(MockEntityHelper.GetNewTarefa(projetoId, workflowId, recursoId, tipoTarefaId, tarefaId));

        Guid impedimentoId = Guid.NewGuid();
        await unitOfWork.ImpedimentoRepository.AddAsync(MockEntityHelper.GetNewImpedimento(impedimentoId));

        await unitOfWork.SaveChangesAsync();

        CreateImpedimentoTarefaCommand request = new()
        {
            ImpedimentoTarefa = MockViewModelHelper.GetNewImpedimentoTarefa(tarefaId, impedimentoId)
        };

        // Act
        ImpedimentoTarefaHandler handler  = new(unitOfWork, mapper);
        OperationResult          response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
    }
예제 #22
0
    public async Task ListTarefaQuery_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Guid sistemaId = Guid.NewGuid();
        await unitOfWork.SistemaRepository.AddAsync(MockEntityHelper.GetNewSistema(sistemaId));

        Guid projetoId = Guid.NewGuid();
        await unitOfWork.ProjetoRepository.AddAsync(MockEntityHelper.GetNewProjeto(sistemaId, projetoId));

        Guid workflowId = Guid.NewGuid();
        await unitOfWork.WorkflowRepository.AddAsync(MockEntityHelper.GetNewWorkflow(workflowId));

        Guid recursoId = Guid.NewGuid();
        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso(recursoId));

        Guid tipoTarefaId = Guid.NewGuid();
        await unitOfWork.TipoTarefaRepository.AddAsync(MockEntityHelper.GetNewTipoTarefa(tipoTarefaId));

        Guid tarefaId = Guid.NewGuid();
        await unitOfWork.TarefaRepository.AddAsync(MockEntityHelper.GetNewTarefa(projetoId, workflowId, recursoId, tipoTarefaId, tarefaId));

        await unitOfWork.TarefaRepository.AddAsync(MockEntityHelper.GetNewTarefa(projetoId, workflowId, recursoId, tipoTarefaId));

        await unitOfWork.TarefaRepository.AddAsync(MockEntityHelper.GetNewTarefa(projetoId, workflowId, recursoId, tipoTarefaId));

        await unitOfWork.SaveChangesAsync();

        ListTarefaQuery request = new();

        // Act
        TarefaHandler handler = new(unitOfWork, mapper);
        IEnumerable <TarefaViewModel> response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response != null);
        Assert.True(response.Any());
        Assert.True(response.FirstOrDefault(x => x.Id == tarefaId) != null);
    }
예제 #23
0
        /// <summary>
        /// AutoMapper全局配置映射配置
        /// </summary>
        public static void Initialize()
        {
            #region User

            AutoMapperHelper.CreateMap <User, UserDto>();

            #endregion

            #region Role

            AutoMapperHelper.CreateMap <Role, RoleDto>();

            #endregion

            #region Blog

            AutoMapperHelper.CreateMap <Blog, BlogEditModel>();
            AutoMapperHelper.CreateMap <BlogEditModel, Blog>();//todo

            #endregion
        }
예제 #24
0
        /// <summary>
        /// 添加学生
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic AddStudent(StudentSingleModel model)
        {
            var transaction = DataRepository.Session.Begin();

            try
            {
                var student = AutoMapperHelper <StudentSingleModel, Student> .AutoConvert(model);

                var itemId = DataRepository.Insert <Student>(student, transaction);
                DataRepository.Session.Commit();

                return(itemId);
            }
            catch (Exception ex)
            {
                DataRepository.Session.Rollback();
                logger.Error(ex);

                return(string.Empty);
            }
        }
        /// <summary>
        /// Initializes the ABP system.
        /// </summary>
        public virtual void Initialize()
        {
            IocManager.IocContainer.Install(new SmartFrameCoreInstaller());

            var _typeFinder = IocManager.IocContainer.Resolve <ITypeFinder>();
            var types       = _typeFinder.Find(type =>
                                               type.IsDefined(typeof(AutoMapAttribute)) ||
                                               type.IsDefined(typeof(AutoMapFromAttribute)) ||
                                               type.IsDefined(typeof(AutoMapToAttribute))
                                               );

            foreach (var type in types)
            {
                AutoMapperHelper.CreateMap(type);
            }

            //todo IocManager.Resolve<AbpStartupConfiguration>().Initialize();

            //_moduleManager = IocManager.Resolve<IAbpModuleManager>();
            //_moduleManager.InitializeModules();
        }
예제 #26
0
        public void MapToTest()
        {
            User _user = new User();

            _user.Id       = 1;
            _user.Name     = "chruenyouzi";
            _user.PassWord = "******";
            var _userDto = AutoMapperHelper.MapTo <User, UserDto>(_user);

            Assert.AreEqual(_userDto.Name, "chruenyouzi");
            Assert.AreEqual(_userDto.PassWord, "123");
            _userDto = AutoMapperHelper.MapTo <User, UserDto>(_user);
            Assert.AreEqual(_userDto.Name, "chruenyouzi");
            Assert.AreEqual(_userDto.PassWord, "123");
            _userDto = AutoMapperHelper.MapTo <User, UserDto, UserProfile>(_user);
            Assert.AreEqual(_userDto.Name, "chruenyouzi");
            Assert.AreEqual(_userDto.PassWord, "123");
            _userDto = AutoMapperHelper.MapTo <User, UserDto, UserProfile>(_user);
            Assert.AreEqual(_userDto.Name, "chruenyouzi");
            Assert.AreEqual(_userDto.PassWord, "123");
        }
예제 #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var groceryStoreConfiguration = new GroceryStoreConfiguration();

            Configuration.GetSection("GroceryStore").Bind(groceryStoreConfiguration);
            GroceryStoreConfiguration = groceryStoreConfiguration;

            services.AddSingleton <GroceryStoreConfiguration>(x => groceryStoreConfiguration);

            // automapper
            services.AddScoped <IMapper>(x => AutoMapperHelper.ConfigureAutomapper().CreateMapper());
            services.ConfigureGroceryStoreBLL();

            services.AddControllers(configure => configure.Filters.Add(typeof(ExceptionInterceptor)));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "GroceryStore.API", Version = "v1"
                });
            });
        }
    public async Task CreateSistemaCommand_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Mock <IEventHandler> mockServiceBus           = ServiceBusHelper.GetInstance();
        Mock <IHubContext <CpnucleoHub> > mockSignalR = SignalRHelper.GetInstance();

        CreateSistemaCommand request = new()
        {
            Sistema = MockViewModelHelper.GetNewSistema()
        };

        // Act
        SistemaHandler  handler  = new(unitOfWork, mapper, mockServiceBus.Object, mockSignalR.Object);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
    }
예제 #29
0
        [HttpPut] //("{id}")]
        public IHttpActionResult Update(int id, [FromBody] UserDto userDto)
        {
            // map dto to entity and set id

            //var user = Mapper.Map<User>(userDto);
            var user = AutoMapperHelper.Convert(userDto);

            user.Id = id;

            try
            {
                // save
                _userService.Update(user, userDto.Password);
                return(Ok());
            }
            catch (AppException ex)
            {
                // return error message if there was an exception
                return(BadRequest(ex.Message));
            }
        }
예제 #30
0
        public virtual async Task <ActionResult> Index(int page = 1, int pageSize = 10, string orderColumn = "Id", string orderType = "desc", string search = "")
        {
            var cts = TaskHelper.CreateChildCancellationTokenSource(ClientDisconnectedToken());

            try
            {
                var dataTask  = Service.SearchAsync(cts.Token, null, search, null, AutoMapperHelper.GetOrderBy <TDto>(orderColumn, orderType), page - 1, pageSize, true, false, null);
                var totalTask = Service.GetSearchCountAsync(cts.Token, null, search);

                await TaskHelper.WhenAllOrException(cts, dataTask, totalTask);

                var data  = dataTask.Result;
                var total = totalTask.Result;

                var response = new WebApiPagedResponseDto <TDto>
                {
                    Page        = page,
                    PageSize    = pageSize,
                    Records     = total,
                    Rows        = data.ToList(),
                    OrderColumn = orderColumn,
                    OrderType   = orderType,
                    Search      = search
                };

                ViewBag.Search      = search;
                ViewBag.Page        = page;
                ViewBag.PageSize    = pageSize;
                ViewBag.OrderColumn = orderColumn;
                ViewBag.OrderType   = orderType;

                ViewBag.PageTitle = Title;
                ViewBag.Admin     = Admin;
                return(View("List", response));
            }
            catch
            {
                return(HandleReadException());
            }
        }