Esempio n. 1
0
        public async Task <RunResult> LaunchAsync(Algorithm algorithm, Run run, RunSettings settings)
        {
            var filePath = _algorithmFileProvider.GetAlgorithmFilePath(algorithm.CodeName, algorithm.FilePath);

            if (!_fileSystemWrapper.ExistsFile(filePath))
            {
                throw new NotFoundException("Given algorithm execution file doesn't exists");
            }

            using (var uow = _unitOfWorkProvider.Create())
            {
                // Download and Transform file arguments
                await _algorithmFileProvider.DownloadFiles(settings.Arguments, run.UserId);

                var stringArguments = settings.Arguments.Select(arg => arg.ToString()).ToList();

                var runFolder = _temporaryFileProvider.CreateTemporaryFolder();

                var tokenSource = new CancellationTokenSource(_options.Value.HardTimeoutInSeconds * 1000);

                var task = _processService.RunAsync(new ProcessOptions(filePath, stringArguments, runFolder), tokenSource.Token);

                var lightTimeout = !settings.Timeout.HasValue || settings.Timeout < 0
                    ? _options.Value.LightTimeoutInSeconds
                    : settings.Timeout.Value;

                var result = await task.WithTimeout(TimeSpan.FromSeconds(lightTimeout));

                if (!result.Completed)
                {
                    // timeout/cancellation logic
                    task.ContinueWith(async action =>
                    {
                        await AfterRunFinished(run.Id, action, runFolder);
                    }, TaskContinuationOptions.None).SupressError();

                    return(new RunResult()
                    {
                        RunId = run.Id,
                        Result = run.Result,
                        CreatedAt = run.CreatedAt
                    });
                }

                var savedRun = await SaveSuccessRun(runFolder, run, result.Value);

                await uow.CommitAsync();

                return(new RunResult()
                {
                    FileId = savedRun.FileId,
                    StdOut = result.Value.StdOut,
                    StdErr = result.Value.StdError,
                    RunId = run.Id,
                    Result = savedRun.Result,
                    CreatedAt = result.Value.StartedAt,
                    FinishedAt = result.Value.FinishedAt
                });
            }
        }
Esempio n. 2
0
        public ActionResult ApplyDiscountOrGiftCardCode(DiscountOrGiftCardCodeDto model)
        {
            try
            {
                using (var uow = _uowProvider.Create())
                {
                    var store = CurrentPage.GetStore();
                    var order = _sessionManager.GetOrCreateCurrentOrder(store.Id)
                                .AsWritable(uow)
                                .Redeem(model.Code);

                    _orderService.SaveOrder(order);

                    uow.Complete();
                }
            }
            catch (ValidationException ex)
            {
                ModelState.AddModelError("", "Failed to redeem discount code");

                return(CurrentUmbracoPage());
            }

            return(RedirectToCurrentUmbracoPage());
        }
        public ActionResult AddToCart(AddToCartDto postModel)
        {
            try
            {
                using (var uow = _uowProvider.Create())
                {
                    var store = CurrentPage.GetStore();
                    var order = _sessionManager.GetOrCreateCurrentOrder(store.Id)
                                .AsWritable(uow)
                                .AddProduct(postModel.ProductReference, postModel.ProductVariantReference, 1);

                    _orderService.SaveOrder(order);

                    uow.Complete();
                }
            }
            catch (ValidationException ex)
            {
                ModelState.AddModelError("productReference", "Failed to add product to cart");

                return(CurrentUmbracoPage());
            }

            TempData["addedProductReference"] = postModel.ProductReference;

            return(RedirectToCurrentUmbracoPage());
        }
Esempio n. 4
0
        public async Task ExecuteAsync_ComplexWherePredicate_ReturnsCorrectQueryResult()
        {
            QueryResult <Freelancer> actualQueryResult;
            var categoryQuery       = Initializer.Container.Resolve <IQuery <Freelancer> >();
            var expectedQueryResult = new QueryResult <Freelancer>(new List <Freelancer> {
                new Freelancer(Sex.MALE, new DateTime(1968, 12, 5), "Bardejov", "*****@*****.**", "Karol Kovach", "som super")
            }, 1);

            var predicate = new CompositePredicate(new List <IPredicate>
            {
                new SimplePredicate(nameof(Freelancer.Sex), ValueComparingOperator.Equal, Sex.MALE),
                new CompositePredicate(new List <IPredicate>
                {
                    new SimplePredicate(nameof(Freelancer.Location), ValueComparingOperator.Equal, "Brno"),
                    new SimplePredicate(nameof(Freelancer.Location), ValueComparingOperator.Equal, "Liberec")
                }, LogicalOperator.OR)
            });

            using (unitOfWorkProvider.Create())
            {
                actualQueryResult = await categoryQuery.Where(predicate).ExecuteAsync();
            }

            Assert.AreEqual(actualQueryResult, expectedQueryResult);
        }
Esempio n. 5
0
 public async Task <QueryResultDto <TDto, TFilterDto> > GetAllItemsAsync()
 {
     using (UnitOfWorkProvider.Create())
     {
         return(await Service.ListAllAsync());
     }
 }
Esempio n. 6
0
        public async Task <IActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(ErrorView());
            }

            using (_unitOfWorkProvider.Create())
            {
                var user = await _userManager.FindByIdAsync(userId);

                if (user == null)
                {
                    return(ErrorView());
                }
                var result = await _userManager.ConfirmEmailAsync(user, code);

                if (result.Succeeded)
                {
                    return(View(InitializeLayoutModel("Confirm Email")));
                }
                else
                {
                    return(ErrorView());
                }
            }
        }
Esempio n. 7
0
        public ActionResult UpdateOrderInformation(UpdateOrderInformationDto model)
        {
            try
            {
                using (var uow = _uowProvider.Create())
                {
                    var store = CurrentPage.GetStore();
                    var order = _sessionManager.GetOrCreateCurrentOrder(store.Id)
                                .AsWritable(uow)
                                .SetProperties(new Dictionary <string, string>
                    {
                        { Constants.Properties.Customer.EmailPropertyAlias, model.Email },
                        { "marketingOptIn", model.MarketingOptIn ? "1" : "0" },

                        { Constants.Properties.Customer.FirstNamePropertyAlias, model.BillingFirstName },
                        { Constants.Properties.Customer.LastNamePropertyAlias, model.BillingLastName },
                        { "billingAddressLine1", model.BillingAddressLine1 },
                        { "billingAddressLine2", model.BillingAddressLine2 },
                        { "billingCity", model.BillingCity },
                        { "billingZipCode", model.BillingZipCode },
                        { "billingTelephone", model.BillingTelephone },

                        { "shippingSameAsBilling", model.ShippingSameAsBilling ? "1" : "0" },
                        { "shippingFirstName", model.ShippingSameAsBilling ? model.BillingFirstName : model.ShippingFirstName },
                        { "shippingLastName", model.ShippingSameAsBilling ? model.BillingLastName : model.ShippingLastName },
                        { "shippingAddressLine1", model.ShippingSameAsBilling ? model.BillingAddressLine1 : model.ShippingAddressLine1 },
                        { "shippingAddressLine2", model.ShippingSameAsBilling ? model.BillingAddressLine2 : model.ShippingAddressLine2 },
                        { "shippingCity", model.ShippingSameAsBilling ? model.BillingCity : model.ShippingCity },
                        { "shippingZipCode", model.ShippingSameAsBilling ? model.BillingZipCode : model.ShippingZipCode },
                        { "shippingTelephone", model.ShippingSameAsBilling ? model.BillingTelephone : model.ShippingTelephone },

                        { "comments", model.Comments }
                    })
                                .SetPaymentCountryRegion(model.BillingCountry, null)
                                .SetShippingCountryRegion(model.ShippingSameAsBilling ? model.BillingCountry : model.ShippingCountry, null);

                    _orderService.SaveOrder(order);

                    uow.Complete();
                }
            }
            catch (ValidationException ex)
            {
                ModelState.AddModelError("", "Failed to update information");

                return(CurrentUmbracoPage());
            }

            if (model.NextStep.HasValue)
            {
                return(RedirectToUmbracoPage(model.NextStep.Value));
            }

            return(RedirectToCurrentUmbracoPage());
        }
Esempio n. 8
0
        public async Task GetCategoryAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectCategory()
        {
            Category skodaCategory;

            using (unitOfWorkProvider.Create())
            {
                skodaCategory = await categoryRepository.GetAsync(skodaCategoryId);
            }

            Assert.AreEqual(skodaCategory.Id, skodaCategoryId);
        }
Esempio n. 9
0
        public async Task GetCorporationAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectCorporation()
        {
            Corporation gotCorporation;

            using (unitOfWorkProvider.Create())
            {
                gotCorporation = await corporationRepository.GetAsync(2);
            }

            Assert.AreEqual(gotCorporation.Id, 2);
        }
Esempio n. 10
0
        public async Task GetFirstItemAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectUser()
        {
            Item firstItem;

            using (unitOfWorkProvider.Create())
            {
                firstItem = await usersRepository.GetAsync(EFTestsInstaller.ItemUser1.Id);
            }

            firstItem.Should().BeEquivalentTo(EFTestsInstaller.ItemUser1);
        }
        public async Task GetAccountAsync()
        {
            Account Ivan;

            using (unitOfWorkProvider.Create())
            {
                Ivan = await accountRepository.GetAsync(guid1);
            }

            Assert.AreEqual(Ivan.Username, accountIvan.Username);
        }
Esempio n. 12
0
        public async Task RevokeAsync(int userId)
        {
            using (var uow = _unitOfWorkProvider.Create())
            {
                var user = await _userRepository.GetById(userId);

                user.ApiKey = _apiKeyGenerator.Generate();

                await uow.CommitAsync();
            }
        }
        public async Task GetDoctorAcsync_InDB_NoIncludes_ReturnsCorrectDoctor()
        {
            Doctor doctorJohnDoe;

            using (unitOfWorkProvider.Create())
            {
                doctorJohnDoe = await doctorRepository.GetAsync(doctorJohnDoeId);
            }

            Assert.AreEqual(doctorJohnDoe.Id, doctorJohnDoeId);
        }
Esempio n. 14
0
        public async Task GetAuctionAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectAuction()
        {
            Auction kodiaqAuction;

            using (unitOfWorkProvider.Create())
            {
                kodiaqAuction = await auctionRepository.GetAsync(kodiaqAuctionId);
            }

            Assert.AreEqual(kodiaqAuction.Id, kodiaqAuctionId);
        }
        public async Task GetCategoryAsync_StoredInDbNoIncludes_ReturnsCorrectCategory()
        {
            Category smartphoneCategory;

            using (_unitOfWorkProvider.Create())
            {
                smartphoneCategory = await _categoryRepository.GetAsync(_smartphonesCategoryId);
            }

            Assert.Equal(_smartphonesCategoryId, smartphoneCategory.Id);
        }
Esempio n. 16
0
        public async Task GetOfferAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectOffer()
        {
            JobOffer offer;

            using (unitOfWorkProvider.Create())
            {
                offer = await repository.GetAsync(Initializer.GoogleAndroidOffer.Id);
            }

            Assert.NotNull(offer);
            Assert.AreEqual(offer.Id, Initializer.GoogleAndroidOffer.Id);
        }
        public async Task GetUserAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectUser()
        {
            User user;

            using (unitOfWorkProvider.Create())
            {
                user = await userRepository.GetAsync(Initializer.MadkiUser.Id);
            }

            Assert.NotNull(user);
            Assert.AreEqual(user.Id, Initializer.MadkiUser.Id);
        }
Esempio n. 18
0
        public async Task GetAnswerAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectAnswer()
        {
            QuestionAnswer answer;

            using (unitOfWorkProvider.Create())
            {
                answer = await repository.GetAsync(Initializer.AnswerJavaEeRedHat.Id);
            }

            Assert.NotNull(answer);
            Assert.AreEqual(answer.Id, Initializer.AnswerJavaEeRedHat.Id);
        }
Esempio n. 19
0
        public async Task GetSkillAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectSkill()
        {
            SkillTag skill;

            using (unitOfWorkProvider.Create())
            {
                skill = await repository.GetAsync(Initializer.JavaSkill.Id);
            }

            Assert.NotNull(skill);
            Assert.AreEqual(skill.Id, Initializer.JavaSkill.Id);
        }
        public async Task GetQuestionAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectQuestion()
        {
            Question question;

            using (unitOfWorkProvider.Create())
            {
                question = await repository.GetAsync(Initializer.JavaExperienceQuestion.Id);
            }

            Assert.NotNull(question);
            Assert.AreEqual(question.Id, Initializer.JavaExperienceQuestion.Id);
        }
Esempio n. 21
0
        public async Task GetEmployerAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectEmployer()
        {
            Employer employer;

            using (unitOfWorkProvider.Create())
            {
                employer = await employerRepository.GetAsync(Initializer.RedHatEmployer.Id);
            }

            Assert.NotNull(employer);
            Assert.AreEqual(employer.Id, Initializer.RedHatEmployer.Id);
        }
Esempio n. 22
0
        public async Task GetApplicationAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectApplication()
        {
            JobApplication application;

            using (unitOfWorkProvider.Create())
            {
                application = await repository.GetAsync(Initializer.ApplicationRedHatQuality.Id);
            }

            Assert.NotNull(application);
            Assert.AreEqual(application.Id, Initializer.ApplicationRedHatQuality.Id);
        }
        private void ExportCustomers()
        {
            try
            {
                SynchronizeStampEntity synchronizeStamp = null;
                DateTime stampTo = DateTime.Now;

                using (var uow = unitOfWorkProvider.CreateReadOnly())
                {
                    synchronizeStamp = synchronizeStampRepository.Get(SynchronizeCodes.Customer, SynchronizeDirectionType.Export);
                }

                DateTime stampFrom = synchronizeStamp?.DateTimeStamp ?? DateTime.MinValue;

                IReadOnlyCollection <int> customerIds = null;

                using (var uow = unitOfWorkProvider.CreateReadOnly())
                {
                    customerIds = customerRepository.GetModifiedCustomersIdsWithWebAccount(stampFrom, stampTo);
                }

                if (Enumerable.Any(customerIds))
                {
                    logger.LogDebug($"Starting synchronize {customerIds.Count} customers");

                    var parallelOptions = new ParallelOptions
                    {
                        MaxDegreeOfParallelism = 1
                    };

                    Parallel.ForEach(customerIds, parallelOptions, x => ProcessCustomerId(x, stampTo));

                    if (synchronizeStamp == null)
                    {
                        synchronizeStamp = SynchronizeStampFactory.Create(SynchronizeCodes.Customer, SynchronizeDirectionType.Export);
                    }

                    synchronizeStamp.DateTimeStamp = stampTo;

                    using (var uow = unitOfWorkProvider.Create())
                    {
                        synchronizeStampRepository.SaveOrUpdate(synchronizeStamp);
                        uow.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"Synchronize customers to PrestaShop error: {ex.ToString()}");
            }
        }
        public async Task GetCategoryAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectCategory()
        {
            // Arrange
            Album androidCategory;

            // Act
            using (unitOfWorkProvider.Create())
            {
                androidCategory = await categoryRepository.GetAsync(androidCategoryId);
            }

            // Assert
            Assert.AreEqual(androidCategory.Id, androidCategoryId);
        }
        public async Task GetProductAsync_AlreadyStoredInDBNoIncludes_ReturnsCorrectProduct()
        {
            // Arrange
            Product samsungGalaxyJ7Product;

            // Act
            using (unitOfWorkProvider.Create())
            {
                samsungGalaxyJ7Product = await productRepository.GetAsync(samsungGalaxyJ7Id);
            }

            // Assert
            Assert.AreEqual(samsungGalaxyJ7Product.Id, samsungGalaxyJ7Id);
        }
        public async Task InsertAsync(TodoItemInsertModel todoItemInsertModel)
        {
            var todoItemEntity = mapper.Map <TodoItemEntity>(todoItemInsertModel);

            using var unitOfWork = unitOfWorkProvider.Create();
            if (todoItemInsertModel.Username != null)
            {
                var userEntity = await userRepository.GetByUsernameAsync(todoItemInsertModel.Username);

                todoItemEntity.UserId = userEntity.Id;
            }

            todoItemRepository.Insert(todoItemEntity);
            await unitOfWork.CommitAsync();
        }
Esempio n. 27
0
        private void SynchronizeOrder()
        {
            logger.LogDebug("Starting synchronize orders");

            try
            {
                SynchronizeStampEntity synchronizeStamp = null;
                DateTime stampTo = DateTime.Now;

                using (var uow = unitOfWorkProvider.CreateReadOnly())
                {
                    synchronizeStamp = synchronizeStampRepository.Get(SynchronizeCodes.Order, SynchronizeDirectionType.Import);
                }

                DateTime stampFrom = synchronizeStamp?.DateTimeStamp ?? DateTime.MinValue;

                IReadOnlyCollection <long> psOrderIds = psOrderRepository.GetAllModifiedBetween(stampFrom, stampTo);

                if (Enumerable.Any(psOrderIds))
                {
                    logger.LogDebug($"Starting synchronize {psOrderIds.Count} orders");

                    var parallelOptions = new ParallelOptions
                    {
                        MaxDegreeOfParallelism = 1
                    };

                    Parallel.ForEach(psOrderIds, parallelOptions, x => ProcessOrderId(x, stampTo));

                    if (synchronizeStamp == null)
                    {
                        synchronizeStamp = SynchronizeStampFactory.Create(SynchronizeCodes.Order, SynchronizeDirectionType.Import);
                    }

                    synchronizeStamp.DateTimeStamp = stampTo;

                    using (var uow = unitOfWorkProvider.Create())
                    {
                        synchronizeStampRepository.SaveOrUpdate(synchronizeStamp);
                        uow.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"Synchronize orders from PrestaShop error: {ex}");
            }
        }
Esempio n. 28
0
        private async Task <RunResultMessage> ProcessInternalAsync(CreateAlgorithmMessage request)
        {
            _logger.LogInformation("Processing message - Run Id: " + request.Run.Id);

            using (_container.OpenScope())
            {
                using (var uow = _unitOfWorkProvider.Create(DbContextOptions.DisableTransactionMode))
                {
                    uow.Context.Runs.Attach(request.Run);

                    var result = await _launchService.LaunchAsync(request.Algorithm, request.Run,
                                                                  new RunSettings { Arguments = request.Arguments, Timeout = request.Timeout });

                    return(new RunResultMessage()
                    {
                        StdOut = result.StdOut,
                        StdErr = result.StdErr,
                        CreatedAt = result.CreatedAt,
                        FinishedAt = result.FinishedAt,
                        FileId = result.FileId,
                        Result = result.Result,
                        RunId = result.RunId
                    });
                }
            }
        }
Esempio n. 29
0
        public async Task <CreateOfferResult> Handle(CreateOfferCommand request, CancellationToken cancellationToken)
        {
            //calculate price
            var priceParams = ConstructPriceParams(request);
            var price       = await pricingService.CalculatePrice(priceParams);


            var o = Offer.ForPrice(
                priceParams.ProductCode,
                priceParams.PolicyFrom,
                priceParams.PolicyTo,
                null,
                price
                );

            //create and save offer
            using (var uow = uowProvider.Create())
            {
                uow.Offers.Add(o);
                uow.CommitChanges();

                //return result
                return(ConstructResult(o));
            }
        }
        public async Task <CreatePolicyResult> Handle(CreatePolicyCommand request, CancellationToken cancellationToken)
        {
            using (var uow = uowProvider.Create())
            {
                var offer = await uow.Offers.WithNumber(request.OfferNumber);

                var customer = new PolicyHolder
                               (
                    request.PolicyHolder.FirstName,
                    request.PolicyHolder.LastName,
                    request.PolicyHolder.TaxId,
                    Address.Of
                    (
                        request.PolicyHolderAddress.Country,
                        request.PolicyHolderAddress.ZipCode,
                        request.PolicyHolderAddress.City,
                        request.PolicyHolderAddress.Street
                    )
                               );
                var policy = offer.Buy(customer);

                uow.Policies.Add(policy);

                await uow.CommitChanges();

                await eventPublisher.PublishMessage(PolicyCreated(policy));

                return(new CreatePolicyResult
                {
                    PolicyNumber = policy.Number
                });
            }
        }