public Service_xuangubao()
        {
            _clientFactory = AutofacContainer.Resolve <IHttpClientFactory>();

            _mapperService = AutofacContainer.Resolve <MapperService>();
            _redisService  = AutofacContainer.Resolve <IRedisService>();
        }
Example #2
0
        /// <summary>
        /// Execute the command entered by the user
        /// </summary>
        /// <param name="command"></param>
        /// <param name="arguments"></param>
        private static void ExecuteCommand(string command, params string[] arguments)
        {
            //Get the correct enum for the command entered
            Enum.TryParse <Enums.Commands>(command, out var result);

            switch (result)
            {
                #region Help
            //Help will display all possible commands
            case Enums.Commands.help:
            {
                //Get all enum commands
                Enum.GetNames(typeof(Enums.Commands))
                .ToList()
                .ForEach(Console.WriteLine);
                return;
            }

                #endregion

            //Start mapping process
            case Enums.Commands.map:
            {
                //Create a new mapper service
                var mapper = new MapperService(CurrentDir, arguments[0]);

                break;
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #3
0
        public async Task AddLocation(LocationModel locationModel)
        {
            var location = MapperService.Map <LocationModel, Location>(locationModel);

            GenericRepository.Add(location);
            await GenericRepository.SaveAsync();
        }
Example #4
0
        public IActionResult Cart()
        {
            decimal sum = 0;
            IEnumerable <FilmViewModel> films = GetFilmsFromCart("CartFilms");

            if (films == null)
            {
                return(View(null));
            }

            IEnumerable <FilmViewModel> filmsDistinct =
                films.GroupBy(film => film.Id)
                .Select(group => group.FirstOrDefault())
                .OrderBy(f => f.Name);
            var mapper = MapperService.CreateFilmDTOToFilmViewModelMapper();

            ViewBag.FilmsDistinctAmount = new Dictionary <string, int>();

            foreach (var film in films)
            {
                sum += film.Price;
            }
            foreach (var film in filmsDistinct)
            {
                ViewBag.FilmsDistinctAmount[film.Name] = films.Where(f => f.Id == film.Id).Count();
            }
            ViewBag.Sum = sum;

            return(View(filmsDistinct));
        }
Example #5
0
        public async Task <IActionResult> AddToCart(int id, [FromQuery] int count, [FromQuery] string returnUrl)
        {
            FilmDTO filmDTO = await _orderService.GetFilmAsync(id);

            var                  mapper = MapperService.CreateFilmDTOToFilmViewModelMapper();
            FilmViewModel        film   = mapper.Map <FilmDTO, FilmViewModel>(filmDTO);
            List <FilmViewModel> films  = new List <FilmViewModel>();

            if (returnUrl == null)
            {
                returnUrl = "~/Home/Index";
            }

            for (int i = 0; i < count; i++)
            {
                films.Add(film);
            }

            AddFilmsToCart("CartFilms", films);
            if (returnUrl.Contains("Cart"))
            {
                return(RedirectToAction("Cart"));
            }
            return(Redirect(returnUrl));
        }
Example #6
0
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            var itemContext = new ItemsContext();
            var itemService = new ItemService(new Repository <Item>(itemContext));

            if (controllerType == typeof(ItemController))
            {
                return(new ItemController(itemService));
            }

            if (controllerType == typeof(BasketController))
            {
                var mapperService         = new MapperService();
                var basketRepository      = new Repository <Basket>(itemContext);
                var invoiceRepository     = new Repository <Invoice>(itemContext);
                var invoiceItemRepository = new Repository <InvoiceItem>(itemContext);
                var basketItemRepository  = new Repository <BasketItem>(itemContext);

                var basketService = new BasketService(basketRepository, invoiceRepository, invoiceItemRepository, basketItemRepository);
                var userService   = new UserService(new Repository <User>(itemContext));
                return(new BasketController(itemService, mapperService, basketService, userService));
            }

            throw new ArgumentException("Unexpected type!", nameof(controllerType));
        }
Example #7
0
        public async Task <IActionResult> Edit(FilmViewModel filmViewModel)
        {
            var mapper = MapperService.CreateFilmViewModelToFilmDTOMapper();

            if (ModelState.IsValid)
            {
                var filmDTO = mapper.Map <FilmViewModel, FilmDTO>(filmViewModel);
                if (filmViewModel.Image != null)
                {
                    string path = "/Files/Posters/" + filmViewModel.Image.FileName;
                    using (FileStream fs = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
                    {
                        await filmViewModel.Image.CopyToAsync(fs);
                    }
                    filmDTO.ImagePath = path;
                }
                await _adminService.SaveFilmAsync(filmDTO);

                TempData["message"] = $"Changes in film {filmViewModel.Name} were saved successfully.";
                return(RedirectToAction("Admin"));
            }
            else
            {
                return(RedirectToAction("Edit"));
            }
        }
Example #8
0
        public void MapFromDataRow_IsValidWithCustomFieldName_ReturnsTheObjectFulfilled()
        {
            IMapper mapper    = new MapperService();
            var     dataTable = new DataTable();

            dataTable.Columns.AddRange(new[]
            {
                new DataColumn("String"), new DataColumn("Integer"), new DataColumn("DummyBoolean"),
                new DataColumn("DummyDouble"), new DataColumn("EnumA")
            });

            var source = dataTable.NewRow();

            source.ItemArray = new object[] { "StringValue", 4590, true, 1000.0, 1 };

            dataTable.Dispose();

            var result = mapper.Map <TestingModelB>(source);

            Assert.NotNull(result);
            Assert.IsType <TestingModelB>(result);
            Assert.Equal("StringValue", result.DummyString);
            Assert.Equal(4590, result.DummyInteger);
            Assert.True(result.DummyBoolean);
            Assert.Equal(1000.0, result.DummyDouble);
            Assert.Equal(TestingEnumA.First, result.DummyEnumA);
        }
        public async Task MappGmailAttachmentIntoEmailAttachment_Test()
        {
            var firstEmail = EmailGeneratorUtil.GenerateEmailFirst();

            var    gmailId  = firstEmail.GmailId;
            var    FileName = "TestFileName";
            double fileSize = 876.77;

            var emailServiceMock = new Mock <IEmailService>().Object;

            var options = TestUtilities.GetOptions(nameof(MappGmailAttachmentIntoEmailAttachment_Test));

            using (var actContext = new E_MailApplicationsManagerContext(options))
            {
                var sut = new MapperService(emailServiceMock);

                await sut.MappGmailAttachmentIntoEmailAttachment(gmailId, FileName, fileSize);

                await actContext.SaveChangesAsync();

                var attachment = actContext.LoanApplicants.Where(b => b.GmailId == firstEmail.GmailId).FirstOrDefaultAsync();

                Assert.IsNotNull(attachment);
            }
        }
        public async Task MappGmailBodyIntoEmailBody_Test()
        {
            var    firstEmail = EmailGeneratorUtil.GenerateEmailFirst();
            string body       = "TestBody";

            var emailServiceMock = new Mock <IEmailService>().Object;


            var options = TestUtilities.GetOptions(nameof(MappGmailBodyIntoEmailBody_Test));

            using (var actContext = new E_MailApplicationsManagerContext(options))
            {
                await actContext.Emails.AddAsync(firstEmail);

                await actContext.SaveChangesAsync();

                var sut = new MapperService(emailServiceMock);

                await sut.MappGmailBodyIntoEmailBody(firstEmail.GmailId, body, firstEmail.UserId);

                var emailBody = actContext.Emails
                                .Where(b => b.Body == body)
                                .FirstOrDefaultAsync();

                Assert.IsNotNull(emailBody);
            }
        }
Example #11
0
        public void MapFromDataRow_IsValidWithIgnore_ReturnsTheObjectFulfilled()
        {
            IMapper mapper    = new MapperService();
            var     dataTable = new DataTable();

            dataTable.Columns.AddRange(new[]
            {
                new DataColumn("DummyString"), new DataColumn("DummyInteger"), new DataColumn("DummyBoolean"),
                new DataColumn("DummyDouble"), new DataColumn("DummyEnumA")
            });

            var source = dataTable.NewRow();

            source.ItemArray = new object[] { "DummyStringValueV2", 900, true, 2000.0, 4 };

            dataTable.Dispose();

            var result = mapper.Map <TestingModelC>(source);

            Assert.NotNull(result);
            Assert.IsType <TestingModelC>(result);
            Assert.Null(result.DummyString);
            Assert.Equal(900, result.DummyInteger);
            Assert.True(result.DummyBoolean);
            Assert.Equal(0, result.DummyDouble);
            Assert.Equal(TestingEnumA.Fourth, result.DummyEnumA);
        }
        public void Patch_ReturnOkResult_UpdateRun()
        {
            var mapper = MapperService.DefaultMapper();

            Run run      = GetRuns()[0];
            var mockRepo = new Mock <IRunRepository>();

            mockRepo.Setup(repo => repo.GetRun(It.IsAny <int>()))
            .ReturnsAsync(run);
            mockRepo.Setup(repo => repo.UpdateRun(It.IsAny <Run>()))
            .ReturnsAsync(true);

            JsonPatchDocument <RunViewModel> patchRequest = new JsonPatchDocument <RunViewModel>();

            patchRequest.Replace(r => r.RunId, 1);
            patchRequest.Replace(r => r.runStatus, RunStatus.OnTheRun);

            var controller = new RunController(mockRepo.Object, mapper);
            var result     = controller.Patch(1, patchRequest);
            var okResult   = Assert.IsType <OkObjectResult>(result.Result);

            Assert.Equal(200, okResult.StatusCode);
            var item = Assert.IsAssignableFrom <RunViewModel>(okResult.Value);

            Assert.Equal(1, item.RunId);
            Assert.Equal(RunStatus.OnTheRun, item.runStatus);
        }
Example #13
0
        public async Task AddRecordSubject(RecordSubjectModel recordSubjectModel)
        {
            var recordSubject = MapperService.Map <RecordSubjectModel, RecordSubject>(recordSubjectModel);

            GenericRepository.Add(recordSubject);
            await GenericRepository.SaveAsync();
        }
Example #14
0
        public async Task <OrderModel> GetOrderByNumber(int number)
        {
            var order = await GenericRepository.GetFirstAsync <Order>(o => o.OrderNumber == number,
                                                                      "RecordSubject,Locations");

            return(MapperService.Map <Order, OrderModel>(order));
        }
Example #15
0
        private async Task LoadTasksFromDb()
        {
            var tasks = await new StorageService().GetTasks(Id);


            foreach (var asanaTask in tasks)
            {
                FillTaskCommands(asanaTask);
                await MapperService.FillSubtasksInfo(asanaTask);
            }

            Tasks.Clear();
            Tasks.AddRange(tasks);



            Project.TasksCount = ActiveTasks.Count;

            if (IsPinned)
            {
                PinService.CreateUpdateStartTileAsync(Project.name, Project.TasksCountText,
                                                      PinService.GetProjectDetailsUri(Id), false);
            }



            NotifyAll();
        }
Example #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var connectionString = Configuration.GetConnectionString("Default");

            services.AddEntityFrameworkNpgsql()
            .AddDbContext <AppDbContext>(options => options.UseNpgsql(connectionString));
            WebApi.DependencyInjectionConfig(services);
            MapperService.Init();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
            });
        }
Example #17
0
        private (MapperService, StationBoardRequest) Arrange()
        {
            var tokenService    = A.Fake <IAccessTokenService>();
            var crsService      = A.Fake <ICrsService>();
            var dateTimeService = A.Fake <IDateTimeService>();
            var mapperService   = new MapperService(A.Fake <ILogger <MapperService> >(),
                                                    tokenService,
                                                    crsService,
                                                    dateTimeService);

            var restRequest = new StationBoardRequest
            {
                AccessToken = "test-in",
                Crs         = "CIN",
                FilterCrs   = "FIN",
                FilterType  = FilterType.from,
                NumRows     = 5,
                TimeOffset  = -30,
                TimeWindow  = 60,
            };

            A.CallTo(() => tokenService.MakeAccessToken(restRequest))
            .Returns(new AccessToken {
                TokenValue = "test-out"
            });
            A.CallTo(() => tokenService.MakeStaffAccessToken(restRequest))
            .Returns(new OpenLDBSVWS.AccessToken {
                TokenValue = "test-out-staff"
            });
            A.CallTo(() => crsService.MakeCrsCode("CIN")).Returns("COT");
            A.CallTo(() => crsService.MakeCrsCode("FIN")).Returns("FOT");
            A.CallTo(() => dateTimeService.LocalNow).Returns(TestDateTime);

            return(mapperService, restRequest);
        }
Example #18
0
        protected async Task <List <TModel> > GetAll <TEntity, TModel>(Expression <Func <TEntity, bool> > filter, string includeProperties = "")
            where TEntity : BaseEntity
        {
            var list = await GenericRepository.GetListAsync(filter, includeProperties);

            return(MapperService.Map <List <TEntity>, List <TModel> >(list));
        }
        public ActionResult <List <CustomerDTO> > Get()
        {
            CustomerService customerService = new CustomerService();
            MapperService   mapperService   = new MapperService();
            var             customerList    = customerService.GetAllCustomersFromCustomerDb();

            return(mapperService.CustomerListToDTO(customerList));
        }
Example #20
0
 public HomeController(IQuestionServices service,
                       MapperService mapper,
                       IAnswerServices answerService)
 {
     _questionService = service;
     _mapper          = mapper;
     _answerService   = answerService;
 }
Example #21
0
        public async Task AddNewOrder(OrderModel orderModel)
        {
            var order = MapperService.Map <OrderModel, Order>(orderModel);

            order.OrderDate = DateTime.UtcNow;
            GenericRepository.Add(order);
            await GenericRepository.SaveAsync();
        }
Example #22
0
        public IActionResult NewsFeed()
        {
            var mapper        = MapperService.NewsDTOTONewsViewModelMapper();
            var news          = _newsService.GetNews();
            var newsViewModel = mapper.Map <IEnumerable <NewsDTO>, IEnumerable <NewsViewModel> >(news);

            return(PartialView(newsViewModel));
        }
        public void Post([FromBody] CustomerDTO customerDto)
        {
            CustomerService customerService = new CustomerService();
            MapperService   mapperService   = new MapperService();
            var             customer        = mapperService.CustomerDtoToCustomer(customerDto);

            customerService.SaveCustomerInCustomerDb(customer);
        }
Example #24
0
        public void Throw_ArgumentNullException_WithProperMessage_WhenProductDtoIsNull()
        {
            // Arrange
            var obj = new MapperService();

            // Act, Assert
            Assert.That(() => obj.Map((ProductDto)null),
                        Throws.ArgumentNullException.With.Message.Contains("product"));
        }
Example #25
0
        public async Task <IActionResult> ChangeQuantity(FilmViewModel film)
        {
            var mapper  = MapperService.CreateFilmViewModelToFilmDTOMapper();
            var filmDTO = mapper.Map <FilmViewModel, FilmDTO>(film);
            await _adminService.ChangeQuantityInStockAsync(filmDTO);

            TempData["message"] = $"{film.Name} quantity set to {film.QuantityInStock}.";
            return(RedirectToAction("Admin"));
        }
Example #26
0
        public void CreateDependenciesOfTests()
        {
            this.shoppingBasketDto = new ShoppingBasketDto();
            this.mapperService     = new MapperService();
            this.efDbContext       = new EfDbContext();
            this.efDbSetWrapper    = new EfDbSetWrapper <ShoppingBasket>(efDbContext);

            this.shoppingBasketService = new ShoppingBasketService(shoppingBasketDto, mapperService, efDbSetWrapper, efDbContext);
        }
Example #27
0
 public IEnumerable <AuthorVM> Get(string term)
 {
     using (var authorRepo = Factory.GetService <IAuthorRepo>())
     {
         var authorsEM = authorRepo.Get(term);
         var authorsVM = MapperService.Map <IEnumerable <AuthorVM> >(authorsEM);
         return(authorsVM);
     }
 }
Example #28
0
        public void Create(AuthorVM model)
        {
            var author = MapperService.Map <AuthorEM>(model);

            using (var authorRepo = Factory.GetService <IAuthorRepo>())
            {
                authorRepo.Create(author);
            }
        }
Example #29
0
        public MainViewModel(MapperService service)
        {
            this.service = service;
            PropertyGrid = new GroupViewModelProperties <PropertyGridTestDataProxy>(new PropertyGridTestDataProxy(), "Test Property Grid");

            //PropertyGrid.Value.RuleFor(x => x.SomeText).EmailAddress().WithMessage(" ...");

            ChangeTextCommand = new WpfActionCommand(OnChangeText);
        }
Example #30
0
        public string Publish(BookVM model)
        {
            var em   = MapperService.Map <BookEM>(model);
            var json = JsonConvert.SerializeObject(em);
            var arn  = ConfigurationManager.AppSettings["AWSSNSTopicARN"];
            var sns  = new SNS();

            return(sns.PublishEntity(arn, json, "Book", "Book"));
        }
Example #31
0
 public ExpenseService(IExpenseBusiness expenseBusiness, MapperService mapperService)
     : base(mapperService)
 {
     if(expenseBusiness == null)
     {
         throw new ArgumentNullException(nameof(expenseBusiness));
     }
     _expenseBusiness = expenseBusiness;
 }
Example #32
0
 public IncomeService(IIncomeBusiness incomeBusiness, MapperService mapperService)
     : base(mapperService)
 {
     if(incomeBusiness == null)
     {
         throw new ArgumentNullException(nameof(incomeBusiness));
     }
     _incomeBusiness = incomeBusiness;
 }
Example #33
0
 public void Init()
 {
     _service = new MapperService ();
     _fixture = new Fixture ();
 }
Example #34
0
 public void Cleanup()
 {
     _service = null;
     _fixture = null;
 }