예제 #1
0
        private async Task <Product> GetOrCreateRecurringDonationProduct(CancellationToken token)
        {
            var products = await productService.ListAsync(
                new ProductListOptions()
            {
                Active = true,
                Type   = "service"
            },
                cancellationToken : token).ConfigureAwait(false);

            Product?product = products.FirstOrDefault(c => c.Name == RecurringDonationProduct);

            if (product == null)
            {
                product = await productService.CreateAsync(
                    new ProductCreateOptions()
                {
                    Active = true,
                    Name   = RecurringDonationProduct,
                    StatementDescriptor = "Donation CollAction",
                    Type = "service"
                },
                    cancellationToken : token).ConfigureAwait(false);
            }

            return(product);
        }
예제 #2
0
            public int Compare(Product?a, Product?b)
            {
                if (a != null && b != null)
                {
                    int result;

                    result = a.Id.CompareTo(b.Id);
                    if (result != 0)
                    {
                        return(result);
                    }
                    result = a.Description.CompareTo(b.Description);
                    if (result != 0)
                    {
                        return(result);
                    }
                    result = a.Category.CompareTo(b.Category);
                    if (result != 0)
                    {
                        return(result);
                    }
                    result = a.Rating.CompareTo(b.Rating);
                    return(result);
                }

                if (a == null && b == null)
                {
                    return(0);
                }
                if (a == null)
                {
                    return(-1);
                }
                return(1);
            }
예제 #3
0
    public ActionResult Update(Product product)
    {
        if (product == null)
        {
            return(BadRequest("Update: product cannot be null."));
        }

        Product?dbProduct = _dbContext.Products.Find(product.Id);

        if (dbProduct == null)
        {
            return(BadRequest($"Update: invalid id: {product.Id}"));
        }
        dbProduct.Copy(product);

        int numChanges = 0;

        if (ModelState.IsValid)
        {
            numChanges = _dbContext.SaveChanges();
            return(Ok(new Msg {
                Result = "Success", Message = $"{numChanges} record(s) updated."
            }));
        }

        return(BadRequest($"ModelState invalid; {numChanges} record(s) updated."));
    }
예제 #4
0
 public void SetUp()
 {
     _versionHelper          = Substitute.For <IVersionHelper>();
     _savedActivation        = new Activation();
     _savedActivation.Exists = true; //must be set for LicenseStillValid/ActivationStillValid
     _licensedProduct        = null;
 }
예제 #5
0
        public Product?Select(string column, string value)
        {
            try
            {
                string        cmdString = $"SELECT * FROM Ambalaj WHERE {column}={value};";
                SqlCommand    cmd       = new SqlCommand(cmdString, _cnn);
                SqlDataReader rdr       = cmd.ExecuteReader();

                Product?res = null;
                if (rdr.Read())
                {
                    var y = rdr.GetInt32(rdr.GetOrdinal("Yukseklik"));
                    var u = rdr.GetInt32(rdr.GetOrdinal("Uzunluk"));
                    var t = rdr.GetInt32(rdr.GetOrdinal("Tip"));
                    var m = rdr.GetDouble(rdr.GetOrdinal("Toplam_Siparis_Miktar"));

                    res = new Product(y, u, t, (float)m, rdr.GetString(rdr.GetOrdinal("Yontem_Kodu")));
                }

                rdr.Close();
                return(res);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return(null);
        }
예제 #6
0
        private static Activation GetSavedActivation(Product?product)
        {
            if (product == null)
            {
                return(null);
            }

            var licenseServerHelper = new LicenseServerHelper();

            var hklmLicenseChecker     = licenseServerHelper.BuildLicenseChecker((Product)product, RegistryHive.LocalMachine);
            var localMachineActivation = hklmLicenseChecker.GetSavedActivation();

            var hkcuLicenseChecker    = licenseServerHelper.BuildLicenseChecker((Product)product, RegistryHive.CurrentUser);
            var currentUserActivation = hkcuLicenseChecker.GetSavedActivation();

            if ((localMachineActivation.TimeOfActivation == DateTime.MinValue) && (currentUserActivation.TimeOfActivation == DateTime.MinValue))
            {
                if (!string.IsNullOrWhiteSpace(currentUserActivation.Key))
                {
                    return(currentUserActivation);
                }

                return(localMachineActivation);
            }

            return(localMachineActivation.TimeOfActivation >= currentUserActivation.TimeOfActivation
                ? localMachineActivation
                : currentUserActivation);
        }
예제 #7
0
        public static void AssignNonBarcodeCell(int robotNo, int height, int width, int type, int orderSize,
                                                string yontemKodu, int palletH, int palletL, int palletZ, int katMax)
        {
            PatternProduct = new Product(height, width, type, orderSize, yontemKodu);
            Cell c = new Cell(0, PatternProduct, robotNo, orderSize, palletH, palletL, palletZ, katMax);

            Cells.Add(c);
        }
예제 #8
0
        /// <summary>
        /// Complete list of all usages of your account. Uses {accountSid} from configuration in HttpProvider
        /// </summary>
        /// <param name="day">Filters usage by day of month. If no month is specified then defaults to current month. Allowed values are integers between 1 and 31 depending on the month. Leading 0s will be ignored.</param>
        /// <param name="month">Filters usage by month. Allowed values are integers between 1 and 12. Leading 0s will be ignored.</param>
        /// <param name="year">Filters usage by year. Allowed values are valid years in integer form such as "2014".</param>
        /// <param name="product">Filters usage by a specific “product” of Avaya Cloud. Each product is uniquely identified by an integer. For example: Product=1, would return all outbound call usage. The integer assigned to each product is listed below.</param>
        /// <param name="page">Used to return a particular page within the list.</param>
        /// <param name="pageSize">Used to specify the amount of list items to return per page.</param>
        /// <returns>Returns usage list</returns>
        public UsagesList ListUsages(int?day         = null, int?month = null, int?year     = null,
                                     Product?product = null, int?page  = null, int?pageSize = null)
        {
            // Get account sid from configuration
            var accountSid = HttpProvider.GetConfiguration().AccountSid;

            return(this.ListUsages(accountSid, day, month, year, product, page, pageSize));
        }
        public async Task FindProduct_returns_null_if_product_not_exists(
            string supplierName, string productCode)
        {
            Container container = GetCosmosContainer();
            var       sut       = new CosmosProductRepository(container);

            Product?actual = await sut.FindProduct(supplierName, productCode);

            actual.Should().BeNull();
        }
        public async Task CreateOrReplaceProduct_correctly_creates_new_product(Product product)
        {
            Container container = GetCosmosContainer();
            var       sut       = new CosmosProductRepository(container);

            await sut.CreateOrReplaceProduct(product);

            Product?actual = await sut.FindProduct(product.SupplierName, product.ProductCode);

            actual.Should().BeEquivalentTo(product);
        }
예제 #11
0
        public Image Update(string path, int product, ApplicationContext context)
        {
            Path = string.IsNullOrEmpty(path) ? Path : path;

            if (product > 0)
            {
                Product = context.Product?.First(p => p.Id == product);
            }

            return(this);
        }
        public async Task FindProduct_correctly_returns_entity(Product product)
        {
            Container container = GetCosmosContainer();
            await container.CreateItemAsync(product);

            var sut = new CosmosProductRepository(container);

            Product?actual = await sut.FindProduct(product.SupplierName, product.ProductCode);

            actual.Should().BeEquivalentTo(product);
        }
예제 #13
0
    public async Task MultipleUpdatesSingleBatch()
    {
        var     settings = CreateDefaultSettings().WithHttpMock();
        Product?product  = null;
        Product?product1 = null;
        Product?product2 = null;

        var batch = new ODataBatch(settings);

        batch += async c => product = await c
                                      .For <Product>()
                                      .Set(new { ProductName = "Test11", UnitPrice = 21m })
                                      .InsertEntryAsync().ConfigureAwait(false);

        await batch.ExecuteAsync().ConfigureAwait(false);

        batch  = new ODataBatch(settings);
        batch += c => c
                 .For <Product>()
                 .Key(product.ProductID)
                 .Set(new { UnitPrice = 22m })
                 .UpdateEntryAsync(false);
        batch += async c => product1 = await c
                                       .For <Product>()
                                       .Filter(x => x.ProductName == "Test11")
                                       .FindEntryAsync().ConfigureAwait(false);

        batch += c => c
                 .For <Product>()
                 .Key(product.ProductID)
                 .Set(new { UnitPrice = 23m })
                 .UpdateEntryAsync(false);
        batch += async c => product2 = await c
                                       .For <Product>()
                                       .Filter(x => x.ProductName == "Test11")
                                       .FindEntryAsync().ConfigureAwait(false);

        await batch.ExecuteAsync().ConfigureAwait(false);

        Assert.Equal(22m, product1.UnitPrice);
        Assert.Equal(23m, product2.UnitPrice);

        var client = new ODataClient(settings);

        product = await client
                  .For <Product>()
                  .Filter(x => x.ProductName == "Test11")
                  .FindEntryAsync().ConfigureAwait(false);

        Assert.Equal(23m, product.UnitPrice);
    }
        public void CustomerAddProductToCart()
        {
            int  idProduct;
            bool checkInput = false;

            Console.WriteLine("Press 0 to cancel");
back_input_choose_product:
            Console.Write("Please choose one product above by ID to add to your cart: ");
            checkInput = int.TryParse(Common.ReadDataFromConsole(), out idProduct);
            while (!checkInput || idProduct < 0 || idProduct > _shopServices.GetNumberOfProducts())
            {
                Console.WriteLine("Your input is wrong data requirement, please input again");
                goto back_input_choose_product;
            }
            if (idProduct == 0)
            {
                return;
            }
            Product?productChooseByCustomer = _shopServices.GetProduct(idProduct);

            if (productChooseByCustomer != null)
            {
                int quantityProduct;
back_input_quantity:
                Console.Write($"Please enter quantity of {productChooseByCustomer.Name} you want to order: ");
                checkInput = int.TryParse(Common.ReadDataFromConsole(), out quantityProduct);
                while (!checkInput || quantityProduct < 0 || quantityProduct > productChooseByCustomer.QuantityInStock)
                {
                    Console.WriteLine($"Please check your input quatity, max product's quantity is {productChooseByCustomer.QuantityInStock}");
                    goto back_input_quantity;
                }
                if (quantityProduct == 0)
                {
                    return;
                }
                ProductOrder?productOrder = _customerServices.GetProductOrderInCart(productChooseByCustomer.Name);
                if (productOrder == null)
                {
                    _customerServices.AddNewProductToCart(productChooseByCustomer, quantityProduct);
                }
                else
                {
                    _customerServices.UpdateQuantityProductExistsInCart(productOrder, quantityProduct);
                }
                Console.WriteLine($"{productChooseByCustomer.Name} was added into your cart\n");
            }
            else
            {
                Console.WriteLine("Cannot find product, please check again your input ID");
            }
        }
예제 #15
0
    public IActionResult Get(int key, string version = "1")
    {
        WriteLine($"ProductsController version {version}.");
        Product?p = db.Products.Find(key);

        if (p is null)
        {
            return(NotFound($"Product with id {key} not found."));
        }
        if (version == "2")
        {
            p.ProductName += " version 2.0";
        }
        return(Ok(p));
    }
        public async Task CreateOrReplaceProduct_correctly_updates_existing_product(
            Product source, string productName, Pricing pricing)
        {
            Container container = GetCosmosContainer();
            await container.CreateItemAsync(source);

            var sut     = new CosmosProductRepository(container);
            var product = new Product(source.SupplierName, source.ProductCode, productName, pricing);

            await sut.CreateOrReplaceProduct(product);

            Product?actual = await sut.FindProduct(source.SupplierName, source.ProductCode);

            actual.Should().BeEquivalentTo(product);
        }
예제 #17
0
        public async Task <IActionResult> EditProduct(int id)
        {
            await using Models.AppContext db = new Models.AppContext();
            string  email   = User.FindFirst(u => u.Type == ClaimTypes.Email).Value;
            Product?product = db.Products.Include(p => p.Seller).AsEnumerable()
                              .FirstOrDefault(p => p.Id == id && p.Seller.Email == email);

            if (product == null)
            {
                return(View("Error", new ErrorViewModel()
                {
                    RequestId = "404 Not Found."
                }));
            }
            return(View(product));
        }
    public async Task ProductRepository_BasicCRUDOperations_WorksCorrectly()
    {
        try
        {
            await GetClient().UseClientAsync(PruneDatabases);

            StockInformation stockInformation = new(5, DateTime.UtcNow);

            Product product = new(
                "Samsung TV",
                TechnologyCategoryId,
                500,
                stockInformation);

            await _productsRepository.CreateAsync(product);

            IEnumerable <Product> products = await _productsRepository.GetAsync(x => x.PartitionKey == TechnologyCategoryId);

            List <Product> productsList = products.ToList();
            productsList.Count.Should().Be(1);

            Product tvFromList = productsList.First();
            tvFromList.Should().BeEquivalentTo(product, DefaultProductEquivalencyOptions);

            tvFromList.ApplySaleDiscount(0.10);
            await _productsRepository.UpdateAsync(tvFromList);

            Product discountedTv = await _productsRepository.GetAsync(product.Id, product.CategoryId);

            discountedTv.Price.Should().Be(450);

            Product?notFoundProduct = await _productsRepository.TryGetAsync(Guid.NewGuid().ToString());

            notFoundProduct.Should().BeNull();

            await _productsRepository.DeleteAsync(discountedTv);

            products = await _productsRepository.GetAsync(x => x.PartitionKey == TechnologyCategoryId);

            products.Count().Should().Be(0);
        }
        finally
        {
            await GetClient().UseClientAsync(PruneDatabases);
        }
    }
예제 #19
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Product = await _context.Products.FindAsync(id);

            if (Product != null)
            {
                _context.Products.Remove(Product);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
예제 #20
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Product = await _context.Products
                      .Include(p => p.Category)
                      .Include(p => p.Unit).FirstOrDefaultAsync(m => m.Id == id);

            if (Product == null)
            {
                return(NotFound());
            }
            return(Page());
        }
예제 #21
0
        /// <summary>
        /// Complete list of all usages of your account
        /// </summary>
        /// <param name="accountSid">The account sid.</param>
        /// <param name="day">Filters usage by day of month. If no month is specified then defaults to current month. Allowed values are integers between 1 and 31 depending on the month. Leading 0s will be ignored.</param>
        /// <param name="month">Filters usage by month. Allowed values are integers between 1 and 12. Leading 0s will be ignored.</param>
        /// <param name="year">Filters usage by year. Allowed values are valid years in integer form such as "2014".</param>
        /// <param name="product">Filters usage by a specific “product” of Avaya Cloud. Each product is uniquely identified by an integer. For example: Product=1, would return all outbound call usage. The integer assigned to each product is listed below.</param>
        /// <param name="page">Used to return a particular page within the list.</param>
        /// <param name="pageSize">Used to specify the amount of list items to return per page.</param>
        /// <returns>Returns usage list</returns>
        public UsagesList ListUsages(string accountSid, int?day = null, int?month = null, int?year     = null,
                                     Product?product            = null, int?page  = null, int?pageSize = null)
        {
            // Get client to make request
            var client = HttpProvider.GetHttpClient();

            // Create GET request
            var request = RestRequestHelper.CreateRestRequest(Method.GET, $"Accounts/{accountSid}/Usages.json");

            // Add ListUsages query and body parameters
            this.SetParamsForListUsages(request, day, month, year, product, page, pageSize);

            // Send request
            var response = client.Execute(request);

            return(this.ReturnOrThrowException <UsagesList>(response));
        }
예제 #22
0
    public async Task <IActionResult> ProductDetail(int?id)
    {
        if (!id.HasValue)
        {
            return(BadRequest("You must pass a product ID in the route, for example, /Home/ProductDetail/21"));
        }

        Product?model = await db.Products
                        .SingleOrDefaultAsync(p => p.ProductId == id);

        if (model == null)
        {
            return(NotFound($"ProductId {id} not found."));
        }

        return(View(model)); // pass model to view and then return result
    }
예제 #23
0
    public async Task SuccessWithResults()
    {
        var     settings = CreateDefaultSettings().WithHttpMock();
        Product?product1 = null;
        Product?product2 = null;

        var batch = new ODataBatch(settings);

        batch += async c => product1 = await c
                                       .For <Product>()
                                       .Set(new Product()
        {
            ProductName = "Test1", UnitPrice = 10m
        })
                                       .InsertEntryAsync().ConfigureAwait(false);

        batch += async c => product2 = await c
                                       .For <Product>()
                                       .Set(new Product()
        {
            ProductName = "Test2", UnitPrice = 20m
        })
                                       .InsertEntryAsync().ConfigureAwait(false);

        await batch.ExecuteAsync().ConfigureAwait(false);

        Assert.NotEqual(0, product1.ProductID);
        Assert.NotEqual(0, product2.ProductID);

        var client = new ODataClient(settings);

        product1 = await client
                   .For <Product>()
                   .Filter(x => x.ProductName == "Test1")
                   .FindEntryAsync().ConfigureAwait(false);

        Assert.NotNull(product1);
        product2 = await client
                   .For <Product>()
                   .Filter(x => x.ProductName == "Test2")
                   .FindEntryAsync().ConfigureAwait(false);

        Assert.NotNull(product2);
    }
예제 #24
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Product = await _context.Products
                      .Include(p => p.Category)
                      .Include(p => p.Unit).FirstOrDefaultAsync(m => m.Id == id);

            if (Product == null)
            {
                return(NotFound());
            }
            ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Name");
            ViewData["UnitId"]     = new SelectList(_context.Units, "Id", "Name");
            return(Page());
        }
예제 #25
0
    public ActionResult Get(int?id)
    {
        if (id == null)
        {
            return(BadRequest(new Msg {
                Result = "Failed", Message = "ID is null"
            }));
        }

        Product?product = _dbContext.Products.Find(id);

        if (product == null)
        {
            return(BadRequest(new Msg {
                Result = "Failed", Message = $"No user found with id: {id}."
            }));
        }

        return(Ok(product));
    }
예제 #26
0
        /// <summary>
        /// Добавление нового продукта
        /// </summary>
        /// <param name="name">Наименование продукта</param>
        /// <param name="product">Продукт</param>
        public void NewProduct(string name, Product?product)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            if (Products.ContainsKey(name))
            {
                throw new Exception("Товар уже существует");
            }

            Products.Add(name, (Product)product);
            HowSold.Add(name, new Product {
                CoutProduct = 0, Price = 0
            });
        }
예제 #27
0
    public ActionResult Remove(int?id)
    {
        if (id == null || id <= 0)
        {
            return(BadRequest("id either null or invalid"));
        }

        Product?product = _dbContext.Products.Find(id);

        if (product == null)
        {
            return(BadRequest("Invalid user id."));
        }

        _dbContext.Products.Remove(product);
        int numChanges = _dbContext.SaveChanges();

        return(Ok(new Msg {
            Result = "Success", Message = $"{numChanges} record(s) removed."
        }));
    }
예제 #28
0
        private void AddToCatalogueOrUpdateIfExisting(string name, Package packageDetails)
        {
            Product?temp = Catalogue.Find(x => x.Name == name);

            if (temp?.Name != null)
            {
                temp?.PackageDetails.Add(packageDetails);
            }
            else
            {
                var entry = new Product
                {
                    Name           = name,
                    PackageDetails = new List <Package> {
                        packageDetails
                    }
                };

                Catalogue.Add(entry);
            }
        }
예제 #29
0
        public override PrivateUser Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType is not JsonTokenType.StartObject)
            {
                throw new JsonException();
            }

            var externalUrlsConverter = options.GetConverter <ExternalUrls>();
            var followersConverter    = options.GetConverter <Followers>();
            var imageArrayConverter   = options.GetConverter <ImageArray>();
            var uriConverter          = options.GetConverter <Uri>();

            string       id           = string.Empty;
            Uri          uri          = null !;
            Uri          href         = null !;
            string?      email        = null;
            string?      displayName  = null;
            CountryCode? country      = null;
            ImageArray   images       = Array.Empty <Image>();
            Product?     product      = null;
            Followers    followers    = null !;
            ExternalUrls externalUrls = null !;

            while (reader.Read())
            {
                if (reader.TokenType is JsonTokenType.EndObject)
                {
                    break;
                }

                if (reader.TokenType is not JsonTokenType.PropertyName)
                {
                    throw new JsonException();
                }

                var propertyName = reader.GetString();

                reader.Read(); // Read to next token.

                switch (propertyName)
                {
                case "id":
                    id = reader.GetString() !;
                    break;

                case "uri":
                    uri = uriConverter.Read(ref reader, typeof(ExternalUrls), options) !;
                    break;

                case "href":
                    href = uriConverter.Read(ref reader, typeof(ExternalUrls), options) !;
                    break;

                case "email":
                    email = reader.GetString();
                    break;

                case "display_name":
                    displayName = reader.GetString();
                    break;

                case "country":
                    var countryCode = reader.GetString();
                    country = countryCode is not null
                            ? EnumConverters.CountryCodeConverter.FromSpotifyString(countryCode)
                            : null;

                    break;

                case "images":
                    images = imageArrayConverter.Read(ref reader, typeof(ImageArray), options) !;
                    break;

                case "product":
                    product = ProductConverter.FromSpotifyString(reader.GetString() !);
                    break;

                case "followers":
                    followers = followersConverter.Read(ref reader, typeof(Followers), options) !;
                    break;

                case "external_urls":
                    externalUrls = externalUrlsConverter.Read(ref reader, typeof(ExternalUrls), options) !;
                    break;

                default:
                    reader.Skip();
                    break;
                }
            }

            return(new(id, uri, href, email, displayName, country, images, product, followers, externalUrls));
        }
예제 #30
0
 public bool Equals(Product?other)
 =>
 other != null &&
 Id == other.Id &&
 Name == other.Name &&
 EAN == other.EAN;