Пример #1
0
        public void AddCustomerListWithOneCustomerThatFailWillThrowExceptionAndRollback()
        {
            //Given a BusinessPartner repository
            var numberOfCustomerBefore = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;

            //When Adding a BusinessPartner list with one or more BusinessPartner that have a Cid (not null)
            var customerList = Enumerable.Range(1, 5)
                               .Select(i => new BusinessPartner {
                Name = "TESTAddCustomerListWithOneCustomerThatFailWillRollback " + i
            })
                               .ToList();

            customerList.ElementAt(3).Key = "000";
            customerList.ElementAt(4).Key = "000";
            Action comparison = () =>
            {
                using var uow = DalService.CreateUnitOfWork();
                uow.BusinessPartners.AddAsync(customerList).Wait();
                uow.CompleteAsync().Wait();
            };


            //Then action will throw an exception
            comparison.Should().Throw <Exception>();

            //and the number of elements in the repository will not affected - transaction will rollback
            var numberOfCustomerAfterTransaction = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;

            numberOfCustomerAfterTransaction.Should().Be(numberOfCustomerBefore);
        }
 public ActionResult <IEnumerable <ContentLimitItemPoco> > Get()
 {
     using (var dal = new DalService())
     {
         return(dal.ContentLimitItems.ToArray());
     }
 }
        public async Task GetCompany(string url)
        {
            //Given a running server with company allocated in his database
            var companyFromDb = DalService.CreateUnitOfWork().Company.GetAsync().Result;

            companyFromDb.Should().NotBeNull();

            //When a client ask for URL /api/Company
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);


            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            CompanyDto reaultObject = JsonConvert.DeserializeObject <CompanyDto>(json);

            reaultObject.Should().NotBeNull();

            //and the result body should match the company in the database
            reaultObject.Should().BeEquivalentTo(Mapper.Map <CompanyDto>(companyFromDb),
                                                 options => options.IncludingNestedObjects());
        }
Пример #4
0
        public async Task GetBusinessPartnersPaging(string url)
        {
            //Given a running server with businessPartners allocated in his database
            DalService.CreateUnitOfWork().BusinessPartners.GetAllAsync(PageRequest.Of(0, 1)).Result.Should().HaveCountGreaterThan(0);

            //When a client ask for URL /api/BusinessPartner&page=x&size=y
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);

            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            var resultObjects       = JsonConvert.DeserializeObject <IEnumerable <BusinessPartnerDto> >(json);
            var businessPartnersDto = resultObjects as BusinessPartnerDto[] ?? resultObjects.ToArray();

            businessPartnersDto.Should().NotBeNull();

            //and the result body should contain size or less elements
            var size = Convert.ToInt32(url.Split("size=")[1]);

            //var page = Convert.ToInt32(url.Split("page=")[1].Split("&")[0]);
            businessPartnersDto.Should().HaveCountLessOrEqualTo(size);
            var bpsKeys = businessPartnersDto.Select(x => x.Key);
            //and the result body should match the businessPartners in the database
            var allBusinessPartnersFromDb = DalService.CreateUnitOfWork()
                                            .BusinessPartners.FindAllAsync(x => bpsKeys.Contains(x.Key), PageRequest.Of(0, int.MaxValue)).Result
                                            .Select(e => Mapper.Map <BusinessPartnerDto>(e)).ToList();

            allBusinessPartnersFromDb.Count.Should().BeLessOrEqualTo(size);
            businessPartnersDto.Should().BeEquivalentTo(allBusinessPartnersFromDb, options => options.IncludingNestedObjects());
        }
Пример #5
0
 /// <summary>
 /// Возвращает экземпляр сервиса
 /// </summary>
 public IncomeService()
 {
     /*
      *  Вообще, тут должен быть Dependency Injection, но для упрощения сделано прямое
      *  создание нужного класса DAL-уровня прямо в конструкторе.
      *
      *  Как правило, бизнес-логика довольно плотно взаимодействует с DAL-уровнем.
      *  От выбранного способа хранения данных и от выбранной конкретной СУБД зависит
      *  довольно многое.
      *
      *  Даже если брать класс реляционных СУБД, то в зависимости
      *  от конкретной СУБД бизнес-логика может быть написана по-разному: для MS SQL
      *  одним образом, для PostgreSQL — другим, для Oracle — вообще третьим. Всякие
      *  красивые идеи про то, что ORM помогает сделать быстрый переход с одной СУБД
      *  на другую — как правило, бред полный. На больших проектах это никогда не работает
      *  быстро — только долго и с болью.
      *
      *  Если же рассматривать класс NoSQL СУБД, то тут бизнес-логика может быть написана
      *  совершенно иначе.
      *
      *  И в обоих случаях связь между уровнями BL и DAL — она достаточно тесная. Поэтому
      *  иногда не так страшно отойти от красивых паттернов, вроде DI, в сторону упрощения,
      *  как это сделано в данном примере.
      */
     _dalService = new DalService();
 }
Пример #6
0
        private static async Task RunAllNoContrastAndBrightness()
        {
            var originalContainerPaths = Directory.GetFiles(MainConstants.ContainerDiffFolderPath, "*.bmp",
                                                            SearchOption.TopDirectoryOnly);
            var originalKeysPaths = Directory.GetFiles(MainConstants.KeysDiffFolderPath, "*.bmp",
                                                       SearchOption.TopDirectoryOnly);


            var i = 1;

            foreach (var originalKeyPath in originalKeysPaths)
            {
                foreach (var originalFilePath in originalContainerPaths)
                {
                    var newFileName = $"{Path.GetFileNameWithoutExtension(originalFilePath)}_{Path.GetFileNameWithoutExtension(originalKeyPath)}";
                    var model       = await Executor.ProcessData(originalFilePath, Path.GetFileName(originalKeyPath),
                                                                 newFileName,
                                                                 0, 0, 0, Mode);

                    model.Mode = Mode;
                    Console.WriteLine($"Processing case #{i++} for {newFileName}");
                    await DalService.InsertResult(model);
                }
            }
        }
Пример #7
0
        public async Task GetEmployeesPageing(string url)
        {
            //Given a running server with employees allocated in his database
            DalService.CreateUnitOfWork().Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.Should().HaveCountGreaterThan(0);

            //When a client ask for URL /api/Employee&page=x&size=y
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);

            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            IEnumerable <EmployeeDto> reaultObjects = JsonConvert.DeserializeObject <IEnumerable <EmployeeDto> >(json);

            reaultObjects.Should().NotBeNull();


            //and the result body should contain size or less elements
            var size = Convert.ToInt32(url.Split("size=")[1]);
            var page = Convert.ToInt32(url.Split("page=")[1].Split("&")[0]);

            reaultObjects.Should().HaveCountLessOrEqualTo(size);

            //and the result body should match the employees in the database
            var allEmployeesFromDb = DalService.CreateUnitOfWork()
                                     .Employees.GetAllAsync(PageRequest.Of(page, size, Sort <EmployeeEntity> .By(x => x.Sn))).Result
                                     .Select(e => Mapper.Map <EmployeeDto>(e));

            reaultObjects.Should().BeEquivalentTo(allEmployeesFromDb, options => options.IncludingNestedObjects());
        }
Пример #8
0
        public async Task GetEmployeeBySn(string url)
        {
            //Given a running server with employees allocated in his database
            var employeeId     = Convert.ToInt32(url.Split("GetBySN/")[1]);
            var employeeFromDb = DalService.CreateUnitOfWork().Employees.FindByIdAsync(employeeId).Result;

            employeeFromDb.Should().NotBeNull();

            //When a client ask for URL /api/Employee/GetByID/5
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);


            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            EmployeeDto reaultObject = JsonConvert.DeserializeObject <EmployeeDto>(json);

            reaultObject.Should().NotBeNull();

            //and the result body should match the employees in the database
            reaultObject.Should().BeEquivalentTo(Mapper.Map <EmployeeDto>(employeeFromDb)
                                                 , options => options.IncludingNestedObjects());
        }
Пример #9
0
        public void AddingCustomerWithCidShouldFailAndThrowException()
        {
            //Given a BusinessPartner repository
            var numberOfCustomerBefore = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;
            //When Adding a BusinessPartner with a Cid (not null)
            var businessPartner = new BusinessPartner
            {
                Key  = "000",
                Name = "testName"
            };
            //Than the adding function will throw an exception
            BusinessPartner addedBusinessPartner = null;
            Action          comparison           = () =>
            {
                using var uow        = DalService.CreateUnitOfWork();
                addedBusinessPartner = uow.BusinessPartners.AddAsync(businessPartner).Result;
                uow.CompleteAsync().Wait();
            };

            comparison.Should().Throw <Exception>();

            //and the database will not affected
            DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result.Should().Be(numberOfCustomerBefore);

            //and the returned BusinessPartner need to be null
            (addedBusinessPartner == null).Should().BeTrue();
        }
Пример #10
0
        //[Theory]
        //[InlineData("/api/Employee/All")]
        public async Task GetAllEmployees(string url)
        {
            //Given a running server with employees allocated in his database
            DalService.CreateUnitOfWork().Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.Should().HaveCountGreaterThan(0);

            //When a client ask for URL /api/Employee/All
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);

            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            IEnumerable <EmployeeDto> reaultObjects = JsonConvert.DeserializeObject <IEnumerable <EmployeeDto> >(json);

            reaultObjects.Should().NotBeNull();

            //and the result body should match the employees in the database
            var allEmployeesFromDb = DalService.CreateUnitOfWork().Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result
                                     .Select(e => Mapper.Map <EmployeeDto>(e));;

            reaultObjects.Should().BeEquivalentTo(allEmployeesFromDb, options => options.IncludingNestedObjects());
        }
Пример #11
0
        public void AddNewValidQuotationShouldSucceed()
        {
            var numOfQuotationBefore = DalService.CreateUnitOfWork().Quotations.CountAsync().Result;

            //Given a valid new quotation
            var validQuotation = CreateValidQuotation();

            //When adding the new quotation
            var unitOfWork = DalService.CreateUnitOfWork();
            {
                var addedQuotations = unitOfWork.Quotations.AddAsync(validQuotation).Result;
                _addedQuotationsToCancelAtDispose.Add(addedQuotations);

                //Then the result should not be null
                addedQuotations.Should().NotBeNull();
                //and the result's document sum should be close to quantity*pricePerQuantity*(100-discountPrecent)/100 + VAT
                var calculatedTotal = validQuotation.Items.Sum(i => i.PricePerQuantity * i.Quantity * (100 - i.DiscountPercent) / 100);
                Debug.Assert(addedQuotations.VatPercent != null, "addedQuotations.VatPercent != null");
                calculatedTotal += (calculatedTotal * addedQuotations.VatPercent.Value) / 100;
                addedQuotations.DocTotal.Should().BeInRange(calculatedTotal - 1, calculatedTotal + 1);
                //and the transaction should succeed
                unitOfWork.CompleteAsync().Wait();
                //and the repository should contain the new quotation
                Debug.Assert(addedQuotations.Key != null, "addedQuotations.Key != null");
                var quotationAfterCommit = DalService.CreateUnitOfWork().Quotations.FindByIdAsync(addedQuotations.Key.Value).Result;
                quotationAfterCommit.Should().NotBeNull();
                quotationAfterCommit.ValidUntil.Should().Be(validQuotation.ValidUntil);

                var numOfQuotationAfter = DalService.CreateUnitOfWork().Quotations.CountAsync().Result;
                numOfQuotationAfter.Should().Be(numOfQuotationBefore + 1);
            }
        }
Пример #12
0
        private static async Task GetResultsForContainerByLevel()
        {
            var items = (await DalService.GetAllResults()).Where(x =>
                                                                 x.Mode == (int)WatermarkingMode.OneContainerToAllKeysWithBrightness ||
                                                                 x.Mode == (int)WatermarkingMode.OneContainerToAllKeysWithContrast ||
                                                                 x.Mode == (int)WatermarkingMode.OneContainerToAllKeysWithNoise).ToList();

            foreach (var item in items)
            {
                item.ContainerFileName = item.ContainerFileName.Substring(0, item.ContainerFileName.IndexOf('_'));
            }


            foreach (var container in items.GroupBy(x => x.ContainerFileName))
            {
                Console.WriteLine(); Console.WriteLine();

                Console.WriteLine($"Results for {container.Key}");

                var brightnessResults = container.Where(x => x.Contrast == 0 && x.Noise == 0)
                                        .OrderBy(x => x.Brightness);
                Console.WriteLine($"Results per brightness");
                Console.WriteLine("Brightness - Encryption PSNR - Decryption PSNR - Encryption time - Decryption time - Key");
                foreach (var data in brightnessResults)
                {
                    Console.WriteLine("{0,8} {1,15} {2,15} {3,18} {4,18} {5,18}",
                                      data.Brightness, Math.Round(data.EncryptionPsnr, 2), Math.Round(data.DecryptionPsnr, 2),
                                      data.EncryptionTime.TotalMilliseconds, data.DecryptionTime.TotalMilliseconds, data.KeyFileName);
                }

                Console.WriteLine();
                var contrastResults = container.Where(x => x.Brightness == 0 && x.Noise == 0)
                                      .OrderBy(x => x.Contrast);
                Console.WriteLine($"Results per contrast");
                Console.WriteLine("Contrast - Encryption PSNR - Decryption PSNR - Encryption time - Decryption time - Key");
                foreach (var data in contrastResults)
                {
                    Console.WriteLine("{0,8} {1,15} {2,15} {3,18} {4,18} {5,18}",
                                      data.Contrast, Math.Round(data.EncryptionPsnr, 2), Math.Round(data.DecryptionPsnr, 2),
                                      data.EncryptionTime.TotalMilliseconds, data.DecryptionTime.TotalMilliseconds, data.KeyFileName);
                }

                Console.WriteLine();
                var noiseResults = container.Where(x => x.Brightness == 0 && x.Contrast == 0)
                                   .OrderBy(x => x.Noise);
                Console.WriteLine($"Results per noise");
                Console.WriteLine("Noise - Encryption PSNR - Decryption PSNR - Encryption time - Decryption time  -  Key");
                foreach (var data in noiseResults)
                {
                    Console.WriteLine("{0,8} {1,15} {2,15} {3,18} {4,18} {5,18}",
                                      data.Noise, Math.Round(data.EncryptionPsnr, 2), Math.Round(data.DecryptionPsnr, 2),
                                      data.EncryptionTime.TotalMilliseconds, data.DecryptionTime.TotalMilliseconds, data.KeyFileName);
                }

                Console.WriteLine("_______________________________________________________________________________________________________");
                Console.WriteLine();
            }
        }
Пример #13
0
 private static async Task RunDifferentNoise(List <WatermarkingResults> resultSet, string originalFilePath, string originalKeyFileName, string fileNameToCreate)
 {
     await ForEachAsync(ValuesForNoise, ParallelThreadsAmount, async noise =>
     {
         var model = await Executor.ProcessData(originalFilePath, originalKeyFileName, fileNameToCreate, 0, 0, noise, Mode);
         AddToResultSet(resultSet, model);
         model.Mode = Mode;
         await DalService.InsertResult(model);
     });
 }
Пример #14
0
        public async Task PostBusinessPartner(string url)
        {
            //Given a running server with CardGroup and Salesman
            DbContext.Salesmen.Add(new SalesmanEntity
            {
                Sn           = -1,
                Name         = "TEST_S",
                ActiveStatus = SalesmanEntity.Status.Active
            });
            DbContext.CardGroups.Add(new CardGroup {
                Sn = 100, Name = "TEST_S"
            });
            DbContext.SaveChanges();

            var validGroupCodes = DalService.CreateUnitOfWork().BusinessPartners.GetAllGroupsAsync().Result;
            var validSalesmen   = DalService.CreateUnitOfWork().Salesmen.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result;

            var businessPartnersToPost = Enumerable.Range(1, 3).ToList()
                                         .Select(i => new BusinessPartner {
                Name         = "TestWebBusinessPartner" + i,
                GroupSn      = validGroupCodes.FirstOrDefault()?.Sn,
                SalesmanCode = validSalesmen.FirstOrDefault()?.Sn,
                PartnerType  = BusinessPartner.PartnerTypes.Customer,
                Type         = BusinessPartner.CardType.Private
            }).ToList();

            foreach (var businessPartnerToPost in businessPartnersToPost)
            {
                var jsonSend = JsonConvert.SerializeObject(Mapper.Map <BusinessPartnerDto>(businessPartnerToPost));
                //When a client ask for URL /api/BusinessPartner} with a valid BusinessPartner in the request body
                var client   = TestServer.CreateClient();
                var response = await client.PostAsync(url, new StringContent(jsonSend, Encoding.UTF8, "application/json"));


                //Then the response will be successful
                response.EnsureSuccessStatusCode(); // Status Code 200-299

                //and the result body should be null and the name need to match
                var json = await response.Content.ReadAsStringAsync();

                var resultObject = JsonConvert.DeserializeObject <BusinessPartnerDto>(json);
                resultObject.Should().NotBeNull();
                resultObject.Name.Should().Be(businessPartnerToPost.Name);
                resultObject.Should().BeEquivalentTo(businessPartnerToPost, opt => opt
                                                     .Excluding(x => x.CreationDateTime)
                                                     .Excluding(x => x.LastUpdateDateTime)
                                                     .Excluding(x => x.Key)
                                                     .IncludingNestedObjects()
                                                     );

                //and the businessPartners should be added to the database
                DalService.CreateUnitOfWork().BusinessPartners.FindByIdAsync(resultObject.Key).Result
                .Should().NotBeNull();
            }
        }
Пример #15
0
 public void Dispose()
 {
     //clear added BusinessPartner if any test failed
     using var uow = DalService.CreateUnitOfWork();
     uow.BusinessPartners.RemoveAsync(
         uow.BusinessPartners.GetAllAsync(
             PageRequest.Of(0, int.MaxValue, Sort <BusinessPartner> .By(x => x.Name))).Result
         .Select(c => c.Key)
         .Except(_customerBeforeTesting).ToList()).Wait();
     uow.CompleteAsync().Wait();
 }
        public void GetCompanyShouldSucceed()
        {
            //Given allocated company repository

            //When call to Get Company
            var company = DalService.CreateUnitOfWork().Company.GetAsync().Result;

            //Then the company should not be null
            company.Should().NotBeNull();
            //and the company should contain a name
            company.Name.Should().NotBeNullOrWhiteSpace();
        }
Пример #17
0
        private static async Task RunOneContainerForOneKey()
        {
            const string originalContainerFileName = "LenaOriginal512color";
            const string originalKeyFileName       = "kisspng-bmp";

            var originalFilePath = Path.Combine(MainConstants.ContainerFolderPath, $"{originalContainerFileName}.bmp");

            var model = await Executor.ProcessData(originalFilePath, $"{originalKeyFileName}.bmp", $"{originalContainerFileName}_{originalKeyFileName}", 0, 0, Mode);

            model.Mode = Mode;

            await DalService.InsertResult(model);
        }
Пример #18
0
        public async void MultiThreadedAddingCustomersShouldSucceed()
        {
            //Given a BusinessPartner Repository
            var readonlyUow            = DalService.CreateUnitOfWork();
            var numberOfCustomerBefore = readonlyUow.BusinessPartners.CountAsync().Result;
            //when a number of different threads want to add some BusinessPartner to the repository at the same time
            const int numOfThreads           = 5;
            const int nymOfCustomerPerThread = 5;


            var taskList = Enumerable.Range(1, numOfThreads).ToList().Select(i =>
            {
                return(Task <List <BusinessPartner> > .Factory.StartNew(() =>
                {
                    var cc = Enumerable.Range(1, nymOfCustomerPerThread)
                             .Select(j => new BusinessPartner {
                        Name = $"TESTAddCustomerList thread={i}:index={j}"
                    })
                             .ToList();
                    using var u = DalService.CreateUnitOfWork();
                    var customerListAfter = u.BusinessPartners.AddAsync(cc).Result.ToList();
                    u.CompleteAsync().Wait();
                    return customerListAfter;
                }));
            }).ToArray();
            var r = (await Task.WhenAll(taskList)).ToList();

            //Then the BusinessPartner Repository will contain all of the BusinessPartner from the different threads
            var numberOfCustomerAfter = readonlyUow.BusinessPartners.CountAsync().Result;

            numberOfCustomerAfter.Should().Be(numberOfCustomerBefore + numOfThreads * nymOfCustomerPerThread);

            r.ForEach(bps =>
            {
                var keys          = bps.Select(cf => cf.Key);
                var addedCustomer = readonlyUow.BusinessPartners
                                    .FindAllAsync(c => keys.Contains(c.Key),
                                                  PageRequest.Of(0, nymOfCustomerPerThread + 1)).Result;
                addedCustomer.Select(c => new[] { c.Key, c.Name })
                .Should().BeEquivalentTo(bps.Select(c => new[] { c.Key, c.Name }),
                                         options => options.IncludingNestedObjects());
            });

            //clear test
            var customersToRemove = r.Aggregate((x1, x2) => x1.Union(x2).ToList());

            using var uow = DalService.CreateUnitOfWork();
            uow.BusinessPartners.RemoveAsync(customersToRemove.Select(c => c.Key).ToList()).Wait();
            uow.CompleteAsync().Wait();
        }
Пример #19
0
 public void Dispose()
 {
     _addedQuotationsToCancelAtDispose.Where(q => q?.Key != null).ToList()
     .ForEach(q =>
     {
         using (var u = DalService.CreateUnitOfWork())
         {
             if (q.Key != null)
             {
                 u.Quotations.CancelAsync(q.Key.Value).Wait();
             }
             u.CompleteAsync().Wait();
         }
     });
 }
Пример #20
0
        public async Task <OrderEntity> CloseDocument(int key, CancellationToken cancellationToken)
        {
            using (var transaction = DalService.CreateUnitOfWork())
            {
                var doc = await transaction.Quotations.FindByIdAsync(key);


                var closedDoc = await GetRepository(transaction).CloseAsync(key);

                cancellationToken.ThrowIfCancellationRequested();
                await transaction.CompleteAsync();

                return(closedDoc);
            }
        }
Пример #21
0
        public void FindBySnWithInValidSnShouldReturnNull()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated Quotation repository
            unitOfWork.Quotations.CountAsync().Result.Should().BeGreaterThan(0);
            //and a invalid SN that match an existing entry
            const short invalidSn = short.MinValue;

            //When call to FIndBySN with the invalid SN
            var gainQuotation = unitOfWork.Quotations.FindByIdAsync(invalidSn).Result;

            //Then the returned quotation should be null
            gainQuotation.Should().BeNull();
        }
Пример #22
0
        public void GetAllEmployeesShouldSucceed()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated employee's repository
            unitOfWork.Employees.CountAsync().Result.Should().BeGreaterThan(0);

            //When GetAll Employees
            var allEmployees = unitOfWork.Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.ToList();

            //Then the number of gain employees should match the number of  allocated employees
            allEmployees.Count().Should().Be(unitOfWork.Employees.CountAsync().Result);

            //and each employee should have an unique SN
            allEmployees.Select(e => e.Sn).Distinct().Count().Should().Be(allEmployees.Count());
        }
Пример #23
0
        private static async Task GetResultsForSimpleMode()
        {
            var items = (await DalService.GetAllResults()).Where(x => x.Mode == 3 || x.Mode == 4).ToList();

            Console.WriteLine();
            Console.WriteLine("Red - Green - Blue - Encryption PSNR - Decryption PSNR - Encryption time - Decryption time - Name");
            Console.WriteLine();
            foreach (var item in items)
            {
                item.ContainerFileName = item.ContainerFileName.Substring(0, item.ContainerFileName.IndexOf('_'));
                Console.WriteLine("{0,4} {1,5} {2,5} {3,18} {4,18} {5,16} {6,17} {7,20}",
                                  item.AverageRedColor, item.AverageGreenColor, item.AverageBlueColor,
                                  Math.Round(item.EncryptionPsnr, 2), Math.Round(item.DecryptionPsnr, 2),
                                  item.EncryptionTime.TotalMilliseconds, item.DecryptionTime.TotalMilliseconds,
                                  item.ContainerFileName);
            }
        }
Пример #24
0
        public async Task UpdateBusinessPartner(string url)
        {
            //Given a running server with businessPartners allocated in his database
            using var unitOfWork = DalService.CreateUnitOfWork();
            var bpsInDb = DbContext.BusinessPartners.Take(3).ToList();
            await unitOfWork.CompleteAsync();

            foreach (var businessPartnerFromDb in bpsInDb)
            {
                //When a client update the name of a valid BusinessPartner and ask for URL /api/BusinessPartner with the updated BusinessPartner
                var updateName = businessPartnerFromDb.Name + " UPDATENAME";
                businessPartnerFromDb.Name = updateName;
                var bpDtoToSend = Mapper.Map <BusinessPartnerDto>(businessPartnerFromDb);
                var jsonSend    = JsonConvert.SerializeObject(bpDtoToSend);
                var client      = TestServer.CreateClient();
                var response    = await client.PutAsync($"{url}/{businessPartnerFromDb.Key}", new StringContent(jsonSend, Encoding.UTF8, "application/json"));

                //Then the response will be successful
                response.EnsureSuccessStatusCode(); // Status Code 200-299

                //and the result body should be null
                var json = await response.Content.ReadAsStringAsync();

                var resultBpDto = JsonConvert.DeserializeObject <BusinessPartnerDto>(json);
                resultBpDto.Should().NotBeNull();

                //and the result should contain the updated name

                resultBpDto.Name.Should().Be(updateName);
                resultBpDto.Should().BeEquivalentTo(bpDtoToSend, config => config.Excluding(x => x.LastUpdateDateTime));
                var resultBp = Mapper.Map <BusinessPartner>(resultBpDto);

                Debug.Assert(businessPartnerFromDb.CreationDateTime != null, "businessPartnerFromDb.CreationDateTime != null");
                resultBp.LastUpdateDateTime.Should()
                .BeAfter(businessPartnerFromDb.LastUpdateDateTime ?? businessPartnerFromDb.CreationDateTime.Value);


                //and the BusinessPartner should be updated in database
                var updatedBusinessPartner = DalService.CreateUnitOfWork().BusinessPartners
                                             .FindAllAsync(c => c.Key == resultBpDto.Key,
                                                           PageRequest.Of(0, 10, Sort <BusinessPartner> .By(x => x.Key))).Result.ElementAt(0);
                updatedBusinessPartner.Name.Should().Be(updateName);
            }
        }
Пример #25
0
        private static async Task RunOneKeyForAllContainersNoContrastAndBrightness()
        {
            const string originalKeyFileName = "BabooOriginal128color.bmp";

            var originalContainerPaths = Directory.GetFiles(MainConstants.ContainerDiffFolderPath, "*.bmp",
                                                            SearchOption.TopDirectoryOnly);

            var results = new List <WatermarkingResults>();

            foreach (var originalFilePath in originalContainerPaths)
            {
                var model = await Executor.ProcessData(originalFilePath, originalKeyFileName, Path.GetFileNameWithoutExtension(originalFilePath), 0, 0, Mode);

                model.Mode = Mode;
                AddToResultSet(results, model);
            }

            await DalService.InsertResults(results);
        }
Пример #26
0
        public void FindBySnWithValidSnShouldSucceed()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated Quotation repository
            unitOfWork.Quotations.CountAsync().Result.Should().BeGreaterThan(0);
            //and a valid SN that match an existing entry
            var validKey = unitOfWork.Quotations.GetAllAsync(PageRequest.Of(0, Int32.MaxValue)).Result
                           .ElementAt(new Random().Next(unitOfWork.Quotations.CountAsync().Result)).Key.Value;

            //When call to FIndBySN with the valid SN
            var gainQuotation = unitOfWork.Quotations.FindByIdAsync(validKey).Result;

            //Then the returned quotation should not be null
            gainQuotation.Should().NotBeNull();

            //and contain a SN that match the searched SN
            gainQuotation.Key.Value.Should().Be(validKey);
        }
Пример #27
0
        public void FindByIdEmployeesShouldSucceed()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated employee's repository
            unitOfWork.Employees.CountAsync().Result.Should().BeGreaterThan(0);

            var allEmployees = unitOfWork.Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.ToList();
            var validSn      = unitOfWork.Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result
                               .ElementAt(new Random().Next(allEmployees.Count() - 1)).Sn;
            //When call to FindByID  with a valid SN
            var employee = unitOfWork.Employees.FindByIdAsync(validSn).Result;

            //Then the employee should not be null
            employee.Should().NotBeNull();

            //and have the searched SN
            employee.Sn.Should().Be(validSn);
        }
Пример #28
0
        private static async Task RunOneContainerForAllKeysNoContrastAndBrightness()
        {
            const string originalContainerFileName = "LenaOriginal512color";
            var          originalFilePath          = Path.Combine(MainConstants.ContainerFolderPath, $"{originalContainerFileName}.bmp");

            var originalKeysPaths = Directory.GetFiles(MainConstants.KeysDiffFolderPath, "*.bmp",
                                                       SearchOption.TopDirectoryOnly);

            var results = new List <WatermarkingResults>();

            await ForEachAsync(originalKeysPaths, 20, async originalKeyPath =>
            {
                var model = await Executor.ProcessData(originalFilePath, Path.GetFileName(originalKeyPath),
                                                       Path.GetFileNameWithoutExtension(originalKeyPath), 0, 0, 0, Mode);
                model.Mode = Mode;
                await DalService.InsertResult(model);
                AddToResultSet(results, model);
            });

//await DalService.InsertResults(results);
        }
        public object Put([FromBody] ContentLimitItemPoco poco)
        {
            var model = poco.ToModel();

            if (!model.IsValid)
            {
                return(new
                {
                    isSuccess = false,
                    messages = model.ValidationResults()
                });
            }

            using (var dal = new DalService())
            {
                dal.Update(poco);
                dal.SaveChanges();

                return(new { isSuccess = true, record = poco });
            }
        }
Пример #30
0
        private static async Task GetResultsForDiffContrastAndBrightness()
        {
            var items = (await DalService.GetAllResults()).Where(x => x.Mode == 1 || x.Mode == 2).ToList();

            foreach (var item in items)
            {
                item.ContainerFileName = item.ContainerFileName.Substring(0, item.ContainerFileName.IndexOf('_'));
            }


            foreach (var container in items.GroupBy(x => x.ContainerFileName))
            {
                Console.WriteLine(); Console.WriteLine();

                Console.WriteLine($"Results for {container.Key}");

                var brightnessResults = container.Where(x => x.Contrast == 0)
                                        .OrderBy(x => x.Brightness);
                Console.WriteLine($"Results per brightness");
                Console.WriteLine("Brightness - Encryption PSNR - Decryption PSNR - Encryption time - Decryption time");
                foreach (var data in brightnessResults)
                {
                    Console.WriteLine("{0,8} {1,15} {2,15} {3,18} {4,18}",
                                      data.Brightness, Math.Round(data.EncryptionPsnr, 2), Math.Round(data.DecryptionPsnr, 2),
                                      data.EncryptionTime.TotalMilliseconds, data.DecryptionTime.TotalMilliseconds);
                }

                Console.WriteLine();
                var contrastResults = container.Where(x => x.Brightness == 0)
                                      .OrderBy(x => x.Contrast);
                Console.WriteLine($"Results per contrast");
                Console.WriteLine("Contrast - Encryption PSNR - Decryption PSNR - Encryption time - Decryption time");
                foreach (var data in contrastResults)
                {
                    Console.WriteLine("{0,8} {1,15} {2,15} {3,18} {4,18}",
                                      data.Contrast, Math.Round(data.EncryptionPsnr, 2), Math.Round(data.DecryptionPsnr, 2),
                                      data.EncryptionTime.TotalMilliseconds, data.DecryptionTime.TotalMilliseconds);
                }
            }
        }