/// <summary>
    /// 第二个参数,实现相等比较器
    /// </summary>
    public static void Dome2()
    {
        Product[] fruits =
        {
            new Product {
                Name = "apple", Code = 9
            },
            new Product {
                Name = "orange", Code = 4
            },
            new Product {
                Name = "lemon", Code = 12
            }
        };

        Product apple = new Product {
            Name = "apple", Code = 9
        };
        Product kiwi = new Product {
            Name = "kiwi", Code = 8
        };

        ProductComparer prodc = new ProductComparer();

        bool hasApple = fruits.Contains(apple, prodc);
        bool hasKiwi  = fruits.Contains(kiwi, prodc);

        Console.WriteLine("Apple? " + hasApple);
        Console.WriteLine("Kiwi? " + hasKiwi);
    }
Exemple #2
0
        public void GetAll_Products_ShouldSortedListOfProducts(long consumption,
                                                               long expectedAnnualConstsBasic,
                                                               int expectedAnnualConstsPackaged)
        {
            // TODO: use mock instead or concreate implementations
            // Arrange
            var productBuider = new ProductBuilder();

            productBuider.SetConsumption(consumption);
            var productComparer = new ProductComparer <Product>();

            //auto mapper configuration
            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new ProductProfile());
            });
            var mapper             = mockMapper.CreateMapper();
            var productsController = new ProductsController(productBuider, productComparer, mapper);

            // Act
            ProductViewModel [] products = productsController.Get(consumption).ToArray();

            // Assert
            Assert.Equal(2, products.Length);
            Assert.Equal(expectedAnnualConstsBasic, products[0].AnnualCosts);
            Assert.Equal(expectedAnnualConstsPackaged, products[1].AnnualCosts);
        }
Exemple #3
0
        public void GetAllProductsTest()
        {
            var productController = new ProductsController(_productService)
            {
                Request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri(ServiceBaseUrl + "api/Products/")
                }
            };

            productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

            _response = productController.Get();

            var responseResult = JsonConvert.DeserializeObject <List <Product> >(_response.Content.ReadAsStringAsync().Result);

            Assert.AreEqual(_response.StatusCode, HttpStatusCode.OK);
            Assert.AreEqual(responseResult.Any(), true);
            var comparer = new ProductComparer();

            CollectionAssert.AreEqual(
                responseResult.OrderBy(product => product, comparer),
                _products.OrderBy(product => product, comparer), comparer);
        }
Exemple #4
0
        public static bool Test_COMPARELESS()
        {
            try
            {
                GitHubFunctions udp = new GitHubFunctions("thee7player", GitHubUpdater.LogTypeSettings.LogStatusOnly);
                Console.WriteLine("FETCH COUNT IS CURRENTLY: " + udp.getAPIFetchCount());
                //Target Repo with name
                Repo   target  = udp.GetRepository("CSGO-Event-Viewer");
                string Update1 = "0.3";
                string Update2 = "0.4.2"; //Same version as of 30/11/19
                string Update3 = "0.7";
                if (target is null)
                {
                    return(false);
                }
                //Project_APIURL <-

                bool a = ProductComparer.CompareVersionLess("thee7player", Update1, target);
                bool b = ProductComparer.CompareVersionLess("thee7player", Update2, target);
                bool c = ProductComparer.CompareVersionLess("thee7player", Update3, target);
                Console.WriteLine("FETCH COUNT AFTER !!!!!!!!!!!!!!!!! : " + udp.getAPIFetchCount());
                return(!a && b && c);
            }
            catch (Exception)
            {
                return(false);
            }
        }
    public static void Main()
    {
        ProductComparer comp = new ProductComparer();
        ArrayList       inv  = new ArrayList();

        // Add elements to the list
        inv.Add(new Product("A", 5.5, 3));
        inv.Add(new Product("B", 8.9, 2));
        inv.Add(new Product("C", 3.0, 4));
        inv.Add(new Product("D", 1.8, 8));

        Console.WriteLine("Product list before sorting:");
        foreach (Product i in inv)
        {
            Console.WriteLine("   " + i);
        }
        Console.WriteLine();

        // Sort the list using an IComparer.
        inv.Sort(comp);

        Console.WriteLine("Product list after sorting:");
        foreach (Product i in inv)
        {
            Console.WriteLine("   " + i);
        }
    }
Exemple #6
0
        public void Linq8()
        {
            ProductComparer comparer = new ProductComparer();


            var products = dataSource.Products.GroupBy(p => p.UnitPrice, comparer);



            foreach (var product in products)
            {
                if (comparer.DeterminePriceCategory(product.Key) == ProductPriceCategories.LowPrice)
                {
                    Console.WriteLine("Дешевые товары");
                }


                if (comparer.DeterminePriceCategory(product.Key) == ProductPriceCategories.AveragePrice)
                {
                    Console.WriteLine("Средние товары");
                }

                if (comparer.DeterminePriceCategory(product.Key) == ProductPriceCategories.HightPrice)
                {
                    Console.WriteLine("Дорогие товары");
                }

                foreach (var i in product)
                {
                    Console.WriteLine(i.UnitPrice + " " + i.ProductName);
                }
            }
        }
Exemple #7
0
    public static void Main()
    {
        /*-1*/
        MyClass <A> ml = new MyClass <A>();

        /*-2*/
        ProductComparer <Product> comp = new ProductComparer <Product>();
        List <Product>            inv  = new List <Product>();

        // Add elements to the list
        inv.Add(new Product("A", 5.5, 3));
        inv.Add(new Product("B", 8.9, 2));
        inv.Add(new Product("C", 3.0, 4));
        inv.Add(new Product("D", 1.8, 8));

        Console.WriteLine("Product list before sorting:");
        foreach (Product i in inv)
        {
            Console.WriteLine("   " + i);
        }
        Console.WriteLine();

        // Sort the list using an IComparer.
        inv.Sort(comp);

        Console.WriteLine("Product list after sorting:");
        foreach (Product i in inv)
        {
            Console.WriteLine("   " + i);
        }
    }
Exemple #8
0
        public void AddShouldThrowArgumentNullExceptionWhenOtherIsNull()
        {
            // Arrange
            var productComparer = new ProductComparer();

            // Act
            productComparer.Add(null);
        }
Exemple #9
0
        public void CompareShouldThrowArgumentNullExceptionWhenConsumptionLessThanZero()
        {
            // Arrange
            var consumption     = -300;
            var productComparer = new ProductComparer();

            // Act
            productComparer.Compare(consumption);
        }
Exemple #10
0
        public static bool Test_GetRelease()
        {
            try
            {
                GitHubFunctions udp = new GitHubFunctions("TheE7Player", GitHubUpdater.LogTypeSettings.LogStatusOnly);

                /*Bypass the waiting process (FOR TESTING)
                 * Repo t = new Repo();
                 * t.setProject_Name("CSGO-Event-Viewer");
                 * t.setProject_Full_Name ( "TheE7Player/CSGO-Event-Viewer");
                 * t.setProject_URL ( "https://github.com/TheE7Player/CSGO-Event-Viewer");
                 * t.setProject_APIURL ( "https://api.github.com/repos/TheE7Player/CSGO-Event-Viewer");
                 * t.setProject_Description ("A Java project to allow users to see what events you can use with logic_eventlistener");
                 * t.setProject_Language ("Java");
                 * t.setProjects_Creation_Date ("2019-11-16T19:00:17Z");
                 * t.setProjects_Latest_Update_Date ("2019-11-30T16:23:40Z");
                 * t.setProjects_Latest_Push_Date ("2019-11-30T16:23:38Z"); */

                bool          findFiles = true;
                Release[]     r         = ProductComparer.GetUpdates(udp.GetRepository("CSGO-Event-Viewer"), findFiles, 2);
                List <Assets> _files    = null;
                Console.WriteLine(" -- INFORMATION FROM RELEASES -- ");

                if (r is null)
                {
                    return(false);
                }

                foreach (Release a in r)
                {
                    _files = a.Assets; //<- Get files from each release

                    Console.WriteLine($"Release: {a.Name}");
                    Console.WriteLine($"└─ Tag: {a.Tag }");
                    Console.WriteLine($"└─ Url: {a.URL}");
                    Console.WriteLine($"└─ Prerelease: {a.isPreRelease }");

                    Console.WriteLine("└─ Dates:");
                    Console.WriteLine($"     └─ Created Date (When drafted) : { a.Created}");
                    Console.WriteLine($"     └─ Published Date (When visible to public): { a.Published }");

                    Console.WriteLine($"└─ Downloadable files {_files.Count}: ");
                    foreach (Assets x in _files)
                    {
                        Console.WriteLine($"     └─ File { x.itemName } : { x.getItemSize(Assets.DisplaySize.Megabytes) } ({x.getItemSize(Assets.DisplaySize.Kilobytes) }) -> { x.itemDownloadUrl}");
                    }
                }
                Console.WriteLine(" -- INFORMATION FROM RELEASES -- ");

                return((findFiles) ? r != null && _files != null : r != null);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemple #11
0
        public void GetAllProductsTest()
        {
            var products    = _productService.GetAllProducts();
            var productList = products.Select(productEntity => new Product {
                ProductId = productEntity.ProductId, ProductName = productEntity.ProductName
            }).ToList();
            var comparer = new ProductComparer();

            Assert.Equal(productList.Count, _products.Count);
        }
        public void Equal_When_All_Fields_Are_Equal()
        {
            var x = CreateProduct();
            var y = CreateProduct();

            var comparer = new ProductComparer();
            bool result = comparer.Equals(x, y);

            Assert.IsTrue(result);
        }
Exemple #13
0
        public void AddShouldSuccess()
        {
            // Arrange
            var name            = TariffConstants.BasicTariffName;
            var product         = new Product(name);
            var productComparer = new ProductComparer();

            // Act
            productComparer.Add(product);
        }
        public void Return_Correct_HashCode_From_Fields()
        {
            var product = CreateProduct();
            int expectedHashCode = product.AtKode ^ product.AtNmNr ^ product.HpKode ^ (byte)product.MutKod;

            var comparer = new ProductComparer();
            int result = comparer.GetHashCode(product);

            Assert.AreEqual(expectedHashCode, result);
        }
        public void GetAllProductsTest()
        {
            var products    = _productServices.GetAllProducts();
            var productList = products.Select(productEntity => new Product {
                ProductId = productEntity.ProductId, ProductName = productEntity.ProductName
            }).ToList();
            var comparer = new ProductComparer();

            CollectionAssert.AreEqual(productList.OrderBy(product => product, comparer), _products.OrderBy(product => product, comparer), comparer);
        }
        public async Task <IHttpActionResult> Products(Guid userId)
        {
            var products = await _authProduct.AccountProductsGetAsync(userId);

            products.Sort(ProductComparer.Comparer);
            products.Reverse();

            ProductComparer.ProductOrderer(products);

            return(Ok(products.ConvertAll(ProductConvertor.AccountProductConvertor)));
        }
        public void Not_Equal_When_HpKode_Is_Different()
        {
            var x = CreateProduct();
            var y = CreateProduct();
            y.HpKode = 4;

            var comparer = new ProductComparer();
            bool result = comparer.Equals(x, y);

            Assert.IsFalse(result);
        }
        public void Setup()
        {
            products = new List <LoanProduct>
            {
                new LoanProduct(1, "a", 1),
                new LoanProduct(2, "b", 2),
                new LoanProduct(3, "c", 3)
            };

            sut = new ProductComparer(new LoanAmount("USD", 200_000m), products);
        }
        public void Not_Equal_When_MutKod_Is_Different()
        {
            var x = CreateProduct();
            var y = CreateProduct();
            y.MutKod = MutKod.RecordUpdated;

            var comparer = new ProductComparer();
            bool result = comparer.Equals(x, y);

            Assert.IsFalse(result);
        }
        public static void Main()
        {
            var productComparer = new ProductComparer();

            productComparer.Add(new Product(TariffConstants.BasicTariffName));
            productComparer.Add(new Product(TariffConstants.PackagedTariffName));

            productComparer.CompareAndPrint(3500);
            productComparer.CompareAndPrint(4500);
            productComparer.CompareAndPrint(6000);
        }
Exemple #21
0
        public void CompareAndPrintShouldSuccess()
        {
            // Arrange
            var productComparer = new ProductComparer();
            var product1        = new Product(TariffConstants.BasicTariffName);
            var product2        = new Product(TariffConstants.PackagedTariffName);

            // Act
            productComparer.Add(product1);
            productComparer.Add(product2);
            productComparer.CompareAndPrint(3400);
        }
Exemple #22
0
        public async Task GetAllProductsTest()
        {
            var productController = ControllerCreater("api/Products", HttpMethod.Get);

            response = await productController.Get();

            var responseResult = JsonConvert.DeserializeObject <List <Product> >(response.Content.ReadAsStringAsync().Result);

            Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
            Assert.AreEqual(responseResult.Any(), true);
            var comparer = new ProductComparer();
            //CollectionAssert.AreEqual(
            //responseResult.OrderBy(product => product, comparer),
        }
        public void Compare_Products_ShouldCompareProducts(long consumptionProductLeft,
                                                           long consumptionProductRight,
                                                           int comparisonResult)
        {
            // Arrange
            var productComparer = new ProductComparer <Product>();

            // Act
            Product productLeft  = Product.Create("pLeft", consumptionProductLeft, new BasicTariffCalculator());
            Product productRight = Product.Create("pRight", consumptionProductRight, new BasicTariffCalculator());

            // Assert
            Assert.Equal(comparisonResult, productComparer.Compare(productLeft, productRight));
        }
Exemple #24
0
        public void GetProductByRightIdTest()
        {
            var mobileProduct = _productService.GetProductById(2);

            if (mobileProduct != null)
            {
                var config = new MapperConfiguration(cfg =>
                                                     cfg.CreateMap <ProductEntity, Product>());

                var     mapper       = config.CreateMapper();
                Product productModel = mapper.Map <Product>(mobileProduct);
                var     comparer     = new ProductComparer();
                Assert.Equal(productModel.ToString(), _products.Find(a => a.ProductName.Contains("Mobile")).ToString());
            }
        }
Exemple #25
0
        public ActionResult Searching(string searchkey, int page = 1, int pageSize = 6)
        {
            if (searchkey == null)
            {
                searchkey = (string)Session[Constants.LISTPRODUCT_SEARCHKEY];
            }
            Session[Constants.LISTPRODUCT_SEARCHKEY] = searchkey;
            Session[Constants.CURRENT_URL]           = HttpContext.Request.RawUrl;

            var             author             = new AuthorDao().ListAuthorBySearchKey(searchkey);
            var             publisher          = new PublisherDao().ListPublisherBySearchKey(searchkey);
            var             productsearch      = new ProductDao().ListProductBySearching(searchkey);
            var             productbyauthor    = new ProductDao().ListProductByListAuthor(author);
            var             productbypublisher = new ProductDao().ListProductByListPublisher(publisher);
            var             listsearch         = productsearch.Concat(productbyauthor).Concat(productbypublisher).ToList();
            ProductComparer productComparer    = new ProductComparer();

            listsearch = listsearch.Distinct(productComparer).OrderByDescending(x => x.Name).ToList();

            Session[Constants.CATEGORY_ACTIVE]        = null;
            Session[Constants.CATE_ID]                = Convert.ToInt64(0);
            Session[Constants.LISTPRODUCT]            = listsearch;
            Session[Constants.LISTPRODUCT_VIEWNAME]   = "Index";
            Session[Constants.LISTPRODUCT_ACTIONNAME] = "Searching";

            Session[Constants.MINPRICE]          = Convert.ToDecimal(0);
            Session[Constants.MAXPRICE]          = decimal.MaxValue;
            Session[Constants.SORT_ACTIVE]       = 1;
            Session[Constants.SORTSTATUS_ACTIVE] = 1;

            Session[Constants.STATUSNAME_PRODUCT] = "Tìm kiếm : " + searchkey;

            int    totalRecord = listsearch.Count();
            string link        = "/ProductClient/Searching?searchkey=" + searchkey + "&";
            var    listfinal   = listsearch.Skip((page - 1) * pageSize).Take(pageSize).ToList();

            SetPagination(totalRecord, pageSize, page, link);

            if (Session[Constants.USER_INFO] != null)
            {
                new LogDao().SetLog("Searching", "Tìm kiếm : " + searchkey.ToString() + ", Trang : " + page.ToString(), ((User)Session[Constants.USER_INFO]).ID);
            }

            return(View((string)Session[Constants.LISTPRODUCT_VIEWNAME], listfinal));
        }
        public async Task GetAllProductsTest()
        {
            var products = await productService.GetAllProducts();

            var productList =
                products.Select(productEntity =>
                                new Product {
                Id = productEntity.Id, Name = productEntity.Name, CreateDate = productEntity.CreateDate, isActive = productEntity.isActive
            }).
                ToList();

            var comparer = new ProductComparer();

            CollectionAssert.AreEqual(
                productList.OrderBy(product => product, comparer),
                expectedProducts.OrderBy(product => product, comparer),
                comparer);
        }
Exemple #27
0
        public void GetAllProductsTest()
        {
            var products = _productService.GetAllProducts();

            if (products != null)
            {
                var productList =
                    products.Select(
                        productEntity =>
                        new Product {
                    Id = productEntity.Id, Name = productEntity.Name, Description = productEntity.Description, DeliveryPrice = productEntity.DeliveryPrice, Price = productEntity.Price
                }).
                    ToList();
                var comparer = new ProductComparer();
                CollectionAssert.AreEqual(
                    productList.OrderBy(product => product, comparer),
                    _products.OrderBy(product => product, comparer), comparer);
            }
        }
Exemple #28
0
        public void CompareShouldReturnListWithCorrectOrder()
        {
            // Arrange
            var productComparer = new ProductComparer();
            var product1        = new Product(TariffConstants.BasicTariffName);
            var product2        = new Product(TariffConstants.PackagedTariffName);
            var expectedResult  = new List <Product>();

            expectedResult.Add(product2);
            expectedResult.Add(product1);

            // Act
            productComparer.Add(product1);
            productComparer.Add(product2);
            var actualResult = productComparer.Compare(3400).ToList();

            // Assert
            CollectionAssert.AreEqual(expectedResult, actualResult);
        }
        public async Task <IHttpActionResult> Data(bool isIncludeModules = false)
        {
            try
            {
                var sessionProducts = await GetSessionTokenProducts();

                if (object.Equals(sessionProducts.SessionToken, null))
                {
                    return(AccountUnauthorized());
                }

                sessionProducts.Products.Sort(ProductComparer.Comparer);
                sessionProducts.Products.Reverse();

                ProductComparer.ProductOrderer(sessionProducts.Products);

                var accountDetailsProducts = new AccountDetailsProducts
                {
                    Details  = await GetAccountDetails(),
                    Products = sessionProducts.Products.ConvertAll(ProductConvertor.AccountProductConvertor)
                };

                if (isIncludeModules && sessionProducts.SessionToken.AccountProductId.HasValue)
                {
                    var product = sessionProducts.Products.FirstOrDefault(e => e.AccountProductId == sessionProducts.SessionToken.AccountProductId.Value && !e.IsDisabled);

                    if (!object.Equals(product, null))
                    {
                        var modules  = UserManagerHelper.GetAllowedModules(sessionProducts.Products, product.AccountProductId);
                        var active   = UserManagerHelper.GetActiveProducts(sessionProducts.Products, modules, product.AccountProductId);
                        var features = GetModuleFeatures(product, modules);

                        accountDetailsProducts.Id             = product.AccountProductId;
                        accountDetailsProducts.Modules        = modules;
                        accountDetailsProducts.ModuleFeatures = features;
                        accountDetailsProducts.ActiveProducts = active;
                    }
                }

                return(Ok(accountDetailsProducts));
            }
            catch (Exception exc) { return(Request.HttpExceptionResult(exc)); }
        }
Exemple #30
0
        public void Get_Products_ShouldThrowBadRequestException()
        {
            // Arrange
            var productBuider = new ProductBuilder();

            productBuider.SetConsumption(-1000);
            var productComparer = new ProductComparer <Product>();

            //auto mapper configuration
            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new ProductProfile());
            });
            var mapper             = mockMapper.CreateMapper();
            var productsController = new ProductsController(productBuider, productComparer, mapper);

            // Act
            // Assert
            Assert.Throws <BadRequestException>(() => productsController.Get(-1000));
        }
Exemple #31
0
        public async Task <IHttpActionResult> Products()
        {
            try
            {
                var sessionProducts = await GetSessionTokenProducts();

                if (object.Equals(sessionProducts.SessionToken, null))
                {
                    return(AccountUnauthorized());
                }

                sessionProducts.Products.Sort(ProductComparer.Comparer);
                sessionProducts.Products.Reverse();

                ProductComparer.ProductOrderer(sessionProducts.Products);

                return(Ok(sessionProducts.Products.ConvertAll(ProductConvertor.AccountProductConvertor)));
            }
            catch (Exception exc) { return(Request.HttpExceptionResult(exc)); }
        }
Exemple #32
0
            public static void Main()
            {
                IComparer <Product> comp  = new ProductComparer();
                Product             book  = new Product(name: "C++ Primer", price: 100);
                Product             book2 = new Product(name: "C++ Primer", price: 10);
                Product             pc    = new Product(name: "Apple PC", price: 10000);
                Product             hdd   = new Product(name: "Seagate 1TB", price: 100);
                Product             bbc   = new Product(name: "BBC", price: 5);

                Product[] products = new Product[] { book, book2, pc, hdd, bbc };
                Array.Sort(products, comp);
                foreach (Product p in products)
                {
                    Console.WriteLine($"{p.Name}:{p.Price}");
                }
                Product bbc2 = new Product(name: "BBC", price: 5);

                Console.WriteLine(comp.Compare(bbc2, bbc));//引用对象地址不同,comp.Compare方法返回比较的属性相同
                Product none = null;

                Console.WriteLine(comp.Compare(none, bbc) == 0);
                Console.ReadKey();
            }
Exemple #33
0
        public static bool Test_COMPAREVERISON()
        {
            bool OutOfDate, SameVersion, HigherVersion;

            try
            {
                GitHubFunctions udp = new GitHubFunctions("thee7player", GitHubUpdater.LogTypeSettings.LogStatusOnly);

                //Target Repo with name
                Repo target = udp.GetRepository("CSGO-Event-Viewer");

                if (target is null)
                {
                    return(false);
                }

                string Update1 = "0.3";
                string Update2 = "0.4.2"; //Same version as of 10/12/19
                string Update3 = "0.7";

                OutOfDate     = ProductComparer.CompareVersionEqual("thee7player", Update1, target);
                SameVersion   = ProductComparer.CompareVersionEqual("thee7player", Update2, target);
                HigherVersion = ProductComparer.CompareVersionEqual("thee7player", Update3, target);

                /*EXPECTED Results:
                 | OutOfDate - Should return 'false' as 0.3 < 0.4.1
                 | SameVersion - Should return 'true' as 0.4.1 equals 0.4.1
                 | HigherVersion - should return 'false' as 0.7 > 0.4.1
                 */
                return(!OutOfDate && SameVersion && !HigherVersion);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemple #34
0
 public void Setup()
 {
     this.sut = new ProductComparer(new LoanAmount("USD", 200_000m), products);
 }