public async Task <IActionResult> Edit(int id, [Bind("DiscountCodeID,DiscoundCode,Percent")] DiscountCode discountCode)
        {
            if (id != discountCode.DiscountCodeID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(discountCode);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DiscountCodeExists(discountCode.DiscountCodeID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(discountCode));
        }
示例#2
0
        private void ChangeDiscount_ButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get the index from the selected product in the list and assign it to the int variable.
                int selectedIndex = discountListBox.SelectedIndex;
                // Modify the object from selected index
                DiscountCode d = discountList.ElementAt(selectedIndex);
                d.Name = codeBox.Text;
                d.Code = 1 - (decimal.Parse(percentageBox.Text) / 100);

                string toFile = string.Empty;

                // iterate through the discountlist and add every object with , between each field and add it toFile.
                foreach (DiscountCode code in discountList)
                {
                    string currentItem = $"{code.Name},{code.Code}{Environment.NewLine}";
                    toFile += currentItem;
                }

                // Write toFile to csv and give message and update the ListBox.
                File.WriteAllText(MainApplication.MainWindow.tempAddress + "Discounts.csv", toFile);
                UpdateDiscountListBox();
                MessageBox.Show("Discount updated!");
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("No discount loaded!");
            }
        }
示例#3
0
        /// <summary>
        /// Setups the discount.
        /// </summary>
        private void SetupDiscount()
        {
            if (!PageBase.StopProcessing)
            {
                string errorMsg;
                bool   canUseDiscount = GetBL <FinanceBL>().IsDiscountCodeValidToUse(txtDiscountCode.Text.Trim(), CompanyId, out errorMsg);
                if (!canUseDiscount)
                {
                    spanErrorMsg.InnerText = errorMsg;
                    spanErrorMsg.Visible   = true;
                    return;
                }

                DiscountCode discountCode = DataContext.DiscountCodes.Where(dc => dc.Code == txtDiscountCode.Text.Trim()).FirstOrDefault();
                DiscountCode = discountCode;

                spanErrorMsg.Visible = false;
                DiscountCodeUsage    = this.GetBL <FinanceBL>().SaveDiscountCodeUsageToCompany(discountCode, UserID, CompanyId);

                popupManageDiscount.HidePopup();
                LoadDiscountCodes();

                //Trigger an event to parent
                if (InformParentToUpdateDiscountUsage != null)
                {
                    InformParentToUpdateDiscountUsage();
                }
            }
        }
示例#4
0
        public DiscountCode CreateDiscountCode(string code)
        {
            DiscountCode discountCode = this.discountCodeFixture.CreateDiscountCode(code);

            this.discountCodeFixture.DiscountCodesToDelete.Add(discountCode);
            return(discountCode);
        }
        public async Task <IActionResult> Create(DiscountCode discountCodes)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                if (files.Count > 0)
                {
                    byte[] p1 = null;
                    using (var fs1 = files[0].OpenReadStream())
                    {
                        using (var ms1 = new MemoryStream())
                        {
                            fs1.CopyTo(ms1);
                            p1 = ms1.ToArray();
                        }
                    }
                    discountCodes.Picture = p1;
                }
                _db.DiscountCode.Add(discountCodes);
                await _db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(discountCodes));
        }
示例#6
0
        public DiscountCodeDTO AddDiscountCode(DiscountCodeDTO dto)
        {
            DiscountCode discountCode = _modelMapper.FromDiscountCodeDTO(dto);
            DiscountCode created      = _discountCodeRepository.Create(discountCode);

            return(_modelMapper.ToDiscountCodeDTO(created));
        }
示例#7
0
        public void Block(int ID)
        {
            DiscountCode discount = _unitOfWork.GetRepositoryInstance <DiscountCode>().GetFirstorDefault(ID);

            discount.isActive = false;
            _unitOfWork.GetRepositoryInstance <DiscountCode>().Update(discount);
        }
示例#8
0
        public static double DiscountedPrice(DiscountCode discountCodeFromDb, double OriginalOrderTotal)
        {
            if (discountCodeFromDb == null)
            {
                return(OriginalOrderTotal);
            }
            else
            {
                if (discountCodeFromDb.MinimumAmount < OriginalOrderTotal)
                {
                    if (Convert.ToInt32(discountCodeFromDb.DiscountCodeType) == (int)DiscountCode.EDiscountCodeType.Percent)
                    {
                        return(Math.Round(OriginalOrderTotal - (OriginalOrderTotal * discountCodeFromDb.DiscountAmount / 100), 2));
                    }



                    if (Convert.ToInt32(discountCodeFromDb.DiscountCodeType) == (int)DiscountCode.EDiscountCodeType.Dollar)
                    {
                        return(Math.Round(OriginalOrderTotal - discountCodeFromDb.DiscountAmount, 2));
                    }
                }
                else
                {
                    return(OriginalOrderTotal);
                }
            }
            return(OriginalOrderTotal);
        }
        public HttpResponseMessage Add(AddPostData postData)
        {
            DiscountCodeLists   discountCodeLists          = new DiscountCodeLists();
            List <DiscountCode> discountCodes              = new List <DiscountCode>();
            List <DiscountCode> discountCodesAlreadyExists = new List <DiscountCode>();

            foreach (string code in postData.Codes.Split(new[] { "\n" }, StringSplitOptions.None))
            {
                DiscountCode doesDiscountCodeAlreadyExist = DiscountCodeService.Instance.Get(postData.StoreId, code);
                if (doesDiscountCodeAlreadyExist == null)
                {
                    DiscountCode discountCode = new DiscountCode(postData.RuleId, code)
                    {
                        MaxUses = postData.MaxUses
                    };
                    discountCode.Save();
                    discountCodes.Add(discountCode);
                }
                else
                {
                    discountCodesAlreadyExists.Add(doesDiscountCodeAlreadyExist);
                }
            }

            discountCodeLists.DiscountCodes = discountCodes;
            discountCodeLists.DiscountCodesAlreadyExists = discountCodesAlreadyExists;

            string discountCodeListsJson = new JavaScriptSerializer().Serialize(discountCodeLists);

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StringContent(discountCodeListsJson, Encoding.UTF8, "application/json");
            return(response);
        }
示例#10
0
        public void AddDiscountCode(DiscountCode discountCode, int quantity)
        {
            discountCode.isActive = true;
            _unitOfWork.GetRepositoryInstance <DiscountCode>().Add(discountCode);
            DiscountCodeDetail discountCodeDetail = new DiscountCodeDetail();

            discountCodeDetail.discountCodeID = discountCode.id;
            discountCodeDetail.isUsed         = false;
            Random random = new Random();

            for (int i = 0; i < quantity; i++)
            {
                lock (discountCodeDetail)
                { // synchronize
                    string strString       = "abcdefghijklmnopqrstuvwxyz0123456789";
                    int    randomCharIndex = 0;
                    char   randomChar;
                    string captcha = "";
                    for (int j = 0; j < 5; j++)
                    {
                        randomCharIndex = random.Next(0, strString.Length);
                        randomChar      = strString[randomCharIndex];
                        captcha        += Convert.ToString(randomChar);
                    }
                    discountCodeDetail.code = captcha;
                    _unitOfWork.GetRepositoryInstance <DiscountCodeDetail>().Add(discountCodeDetail);
                }
            }
        }
示例#11
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (DiscountCode.Length != 0)
            {
                hash ^= DiscountCode.GetHashCode();
            }
            if (VoucherCode.Length != 0)
            {
                hash ^= VoucherCode.GetHashCode();
            }
            if (Amount != 0F)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(Amount);
            }
            if (ItemName.Length != 0)
            {
                hash ^= ItemName.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public HttpResponseMessage Add( AddPostData postData )
        {
            DiscountCodeLists discountCodeLists = new DiscountCodeLists();
              List<DiscountCode> discountCodes = new List<DiscountCode>();
              List<DiscountCode> discountCodesAlreadyExists = new List<DiscountCode>();

              foreach ( string code in postData.Codes.Split( new[] { "\n" }, StringSplitOptions.None ) ) {

            DiscountCode doesDiscountCodeAlreadyExist = DiscountCodeService.Instance.Get( postData.StoreId, code );
            if ( doesDiscountCodeAlreadyExist == null ) {
              DiscountCode discountCode = new DiscountCode( postData.RuleId, code ) {
            MaxUses = postData.MaxUses
              };
              discountCode.Save();
              discountCodes.Add( discountCode );
            } else {
              discountCodesAlreadyExists.Add( doesDiscountCodeAlreadyExist );
            }
              }

              discountCodeLists.DiscountCodes = discountCodes;
              discountCodeLists.DiscountCodesAlreadyExists = discountCodesAlreadyExists;

              string discountCodeListsJson = new JavaScriptSerializer().Serialize( discountCodeLists );

              HttpResponseMessage response = Request.CreateResponse( HttpStatusCode.OK );
              response.Content = new StringContent( discountCodeListsJson, Encoding.UTF8, "application/json" );
              return response;
        }
        public HttpResponseMessage add(DiscountCode post)
        {
            // Check for errors
            if (post == null)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null"));
            }
            else if (Language.MasterPostExists(post.language_id) == false)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist"));
            }
            else if (Currency.MasterPostExists(post.currency_code) == false)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The currency does not exist"));
            }

            // Make sure that the data is valid
            post.id                  = AnnytabDataValidation.TruncateString(post.id, 50);
            post.discount_value      = AnnytabDataValidation.TruncateDecimal(post.discount_value, 0, 9.999M);
            post.end_date            = AnnytabDataValidation.TruncateDateTime(post.end_date);
            post.minimum_order_value = AnnytabDataValidation.TruncateDecimal(post.minimum_order_value, 0, 999999999999.99M);

            // Check if the discount code exists
            if (DiscountCode.MasterPostExists(post.id) == true)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The id already exists"));
            }

            // Add the post
            DiscountCode.Add(post);

            // Return the success response
            return(Request.CreateResponse <string>(HttpStatusCode.OK, "The post has been added"));
        } // End of the add method
        public HttpResponseMessage add(DiscountCode post)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Language.MasterPostExists(post.language_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist");
            }
            else if (Currency.MasterPostExists(post.currency_code) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The currency does not exist");
            }

            // Make sure that the data is valid
            post.id = AnnytabDataValidation.TruncateString(post.id, 50);
            post.discount_value = AnnytabDataValidation.TruncateDecimal(post.discount_value, 0, 9.999M);
            post.end_date = AnnytabDataValidation.TruncateDateTime(post.end_date);
            post.minimum_order_value = AnnytabDataValidation.TruncateDecimal(post.minimum_order_value, 0, 999999999999.99M);

            // Check if the discount code exists
            if (DiscountCode.MasterPostExists(post.id) == true)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The id already exists");
            }

            // Add the post
            DiscountCode.Add(post);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added");

        } // End of the add method
        private void UpdateTargets(DiscountCode discountCode, DiscountCodeEdit discountCodeEdit)
        {
            if (discountCode.Tours == null)
            {
                discountCode.Tours = new List <Tour>();
            }
            discountCode.Tours.Clear();
            if (!discountCode.IsGlobal && discountCodeEdit.TourId != null)
            {
                discountCode.Tours =
                    discountCodeEdit.TourId.Select(i => _tourQueryService.FindTour(Convert.ToInt32(i))).ToList();
            }

            if (discountCode.Products == null)
            {
                discountCode.Products = new List <Product>();
            }
            discountCode.Products.Clear();
            if (!discountCode.IsGlobal && discountCodeEdit.ProductId != null)
            {
                discountCode.Products =
                    discountCodeEdit.ProductId.Select(i => _productQueryService.FindProduct(Convert.ToInt32(i))).ToList();
            }

            if (discountCode.ProductVariants == null)
            {
                discountCode.ProductVariants = new List <ProductVariant>();
            }
            discountCode.ProductVariants.Clear();
            if (!discountCode.IsGlobal && discountCodeEdit.ProductVariantId != null)
            {
                discountCode.ProductVariants =
                    discountCodeEdit.ProductVariantId.Select(i => _productQueryService.FindProductVariant(Convert.ToInt32(i))).ToList();
            }
        }
        public List <DiscountCode> get_all(string sortField = "", string sortOrder = "")
        {
            // Create the list to return
            List <DiscountCode> posts = DiscountCode.GetAll(sortField, sortOrder);

            // Return the list
            return(posts);
        } // End of the get_all method
        private DiscountCodeValidator MockedValidator(DiscountCode discountCode)
        {
            var variantRepo = new Mock <IRepository <ProductVariant> >();

            variantRepo.Setup(r => r.Find(It.IsAny <int>())).Returns <ProductVariant>(null);

            return(MockedValidator(discountCode, variantRepo.Object));
        }
        public DiscountCode get_by_id(string id = "")
        {
            // Create the post to return
            DiscountCode post = DiscountCode.GetOneById(id);

            // Return the post
            return(post);
        } // End of the get_by_id method
示例#19
0
 public DiscountCodeDTO ToDiscountCodeDTO(DiscountCode discountCode)
 {
     return(new DiscountCodeDTO
     {
         Code = discountCode.Code,
         Amount = discountCode.Amount
     });
 }
示例#20
0
        public DiscountCode CreateDiscountCode(DiscountCodeDraft discountCodeDraft)
        {
            IClient      commerceToolsClient = this.GetService <IClient>();
            DiscountCode discountCode        = commerceToolsClient
                                               .ExecuteAsync(new CreateCommand <DiscountCode>(discountCodeDraft)).Result;

            return(discountCode);
        }
示例#21
0
        public void Create(DTODiscountCode context)
        {
            DiscountCode model = new DiscountCode {
                Code = context.Code, DiscountPerCent = context.DiscountPerCent
            };

            uowDiscount.DiscountRepository.Create(model);
        }
示例#22
0
        public ActionResult DeleteConfirmed(int id)
        {
            DiscountCode discountCode = db.DiscountCodes.Find(id);

            db.DiscountCodes.Remove(discountCode);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public ActionResult Edit([Bind(Include = "Id,Code,Persent")] DiscountCode discountCode)
 {
     if (ModelState.IsValid)
     {
         userAppManager.EditDiscountCode(discountCode);
         return(RedirectToAction("Index"));
     }
     return(View(discountCode));
 }
        private DiscountCodeValidator MockedValidator(DiscountCode discountCode,
                                                      IRepository <ProductVariant> variantRepo)
        {
            var code    = discountCode == null ? "invalid" : discountCode.Code;
            var service = new Mock <IDiscountCodeQueryService>();

            service.Setup(r => r.FindByCode(code)).Returns(discountCode);

            return(new DiscountCodeValidator(service.Object, variantRepo));
        }
示例#25
0
        public ActionResult DeleteConfirmed(Guid id)
        {
            DiscountCode discountCode = db.DiscountCodes.Find(id);

            discountCode.IsDeleted    = true;
            discountCode.DeletionDate = DateTime.Now;

            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#26
0
        public void CreateDiscountCode()
        {
            IClient           commerceToolsClient = this.discountCodeFixture.GetService <IClient>();
            DiscountCodeDraft discountCodeDraft   = this.discountCodeFixture.GetDiscountCodeDraft();
            DiscountCode      discountCode        = commerceToolsClient
                                                    .ExecuteAsync(new CreateCommand <DiscountCode>(discountCodeDraft)).Result;

            this.discountCodeFixture.DiscountCodesToDelete.Add(discountCode);
            Assert.Equal(discountCodeDraft.Code, discountCode.Code);
        }
示例#27
0
 public ActionResult Edit([Bind(Include = "idDiscountCode,code,numberOfUses")] DiscountCode discountCode)
 {
     if (ModelState.IsValid)
     {
         db.Entry(discountCode).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(discountCode));
 }
        public ActionResult Create([Bind(Include = "Id,Code,Percentage")] DiscountCode discountCode)
        {
            if (ModelState.IsValid)
            {
                db.DiscountCodes.Add(discountCode);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(discountCode));
        }
示例#29
0
 public ActionResult Edit([Bind(Include = "Id,Code,ExpireDate,IsPercent,Amount,IsMultiUsing,IsActive,CreationDate,CreateUserId,LastModifiedDate,IsDeleted,DeletionDate,DeleteUserId,Description")] DiscountCode discountCode)
 {
     if (ModelState.IsValid)
     {
         discountCode.IsDeleted       = false;
         db.Entry(discountCode).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(discountCode));
 }
示例#30
0
        public ActionResult Create([Bind(Include = "idDiscountCode,code,numberOfUses")] DiscountCode discountCode)
        {
            if (ModelState.IsValid)
            {
                db.DiscountCodes.Add(discountCode);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(discountCode));
        }
        public async Task ShouldGetDiscountCodeByIdAsync()
        {
            Response <DiscountCode> response = await _client.DiscountCodes().GetDiscountCodeByIdAsync(_testDiscountCode.Id);

            Assert.IsTrue(response.Success);

            DiscountCode discountCode = response.Result;

            Assert.NotNull(discountCode.Id);
            Assert.AreEqual(_testDiscountCode.Id, discountCode.Id);
        }
示例#32
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one discount code based on id
    /// </summary>
    /// <param name="id">The id for the post</param>
    /// <returns>A reference to a discount code post</returns>
    public static DiscountCode GetOneById(string id)
    {
        // Create the post to return
        DiscountCode post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.discount_codes WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", id);

                // Create a MySqlDataReader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new DiscountCode(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
        public HttpResponseMessage Add( AddPostData postData )
        {
            List<DiscountCode> discountCodes = new List<DiscountCode>();

              foreach ( string code in postData.Codes.Split( new[] { "\n" }, StringSplitOptions.None ) ) {
            DiscountCode discountCode = new DiscountCode( postData.RuleId, code ) {
              MaxUses = postData.MaxUses
            };
            discountCode.Save();
            discountCodes.Add( discountCode );
              }

              HttpResponseMessage response = Request.CreateResponse( HttpStatusCode.OK );
              response.Content = new StringContent( discountCodes.ToJson(), Encoding.UTF8, "application/json" );
              return response;
        }
示例#34
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one discount code
    /// </summary>
    /// <param name="post">A reference to a discount code post</param>
    public static void Add(DiscountCode post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.discount_codes (id, language_id, currency_code, discount_value, free_freight, end_date, "
            + "once_per_customer, exclude_products_on_sale, minimum_order_value) "
            + "VALUES (@id, @language_id, @currency_code, @discount_value, @free_freight, @end_date, @once_per_customer, "
            + "@exclude_products_on_sale, @minimum_order_value);";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@currency_code", post.currency_code);
                cmd.Parameters.AddWithValue("@discount_value", post.discount_value);
                cmd.Parameters.AddWithValue("@free_freight", post.free_freight);
                cmd.Parameters.AddWithValue("@end_date", post.end_date);
                cmd.Parameters.AddWithValue("@once_per_customer", post.once_per_customer);
                cmd.Parameters.AddWithValue("@exclude_products_on_sale", post.exclude_products_on_sale);
                cmd.Parameters.AddWithValue("@minimum_order_value", post.minimum_order_value);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Add method
        public HttpResponseMessage update(DiscountCode post)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Language.MasterPostExists(post.language_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist");
            }
            else if (Currency.MasterPostExists(post.currency_code) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The currency does not exist");
            }

            // Make sure that the data is valid
            post.id = AnnytabDataValidation.TruncateString(post.id, 50);
            post.discount_value = AnnytabDataValidation.TruncateDecimal(post.discount_value, 0, 9.999M);
            post.end_date = AnnytabDataValidation.TruncateDateTime(post.end_date);
            post.minimum_order_value = AnnytabDataValidation.TruncateDecimal(post.minimum_order_value, 0, 999999999999.99M);

            // Get the saved post
            DiscountCode savedPost = DiscountCode.GetOneById(post.id);

            // Check if the post exists
            if (savedPost == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist");
            }

            // Update the post
            DiscountCode.Update(post);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful");

        } // End of the update method
        public ActionResult edit(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get the return url
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get all the form values
            string id = collection["txtId"];
            Int32 language_id = Convert.ToInt32(collection["selectLanguage"]);
            string currency_code = collection["selectCurrency"];
            decimal discount_value = 0;
            decimal.TryParse(collection["txtDiscountValue"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out discount_value);
            bool free_freight = Convert.ToBoolean(collection["cbFreeFreight"]);
            bool once_per_customer = Convert.ToBoolean(collection["cbOncePerCustomer"]);
            bool exclude_products_on_sale = Convert.ToBoolean(collection["cbExcludeProductsOnSale"]);
            DateTime end_date = Convert.ToDateTime(collection["txtEndDate"]);
            decimal minimum_order_value = 0;
            decimal.TryParse(collection["txtMinimumOrderValue"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out minimum_order_value);

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");

            // Get the discount code
            DiscountCode discountCode = DiscountCode.GetOneById(id);
            bool postExists = true;

            // Check if the discount code exists
            if (discountCode == null)
            {
                // Create an empty discount code
                discountCode = new DiscountCode();
                postExists = false;
            }

            // Update values
            discountCode.id = id;
            discountCode.language_id = language_id;
            discountCode.currency_code = currency_code;
            discountCode.discount_value = discount_value;
            discountCode.free_freight = free_freight;
            discountCode.once_per_customer = once_per_customer;
            discountCode.exclude_products_on_sale = exclude_products_on_sale;
            discountCode.end_date = AnnytabDataValidation.TruncateDateTime(end_date);
            discountCode.minimum_order_value = minimum_order_value;

            // Create a error message
            string errorMessage = string.Empty;

            if (discountCode.id.Length == 0 || discountCode.id.Length > 50)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_certain_length"), tt.Get("id"), "1", "50") + "<br/>";
            }
            if (discountCode.language_id == 0)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("language").ToLower()) + "<br/>";
            }
            if (discountCode.currency_code == "")
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("currency").ToLower()) + "<br/>";
            }
            if (discountCode.discount_value < 0 || discountCode.discount_value > 9.999M)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_range"), tt.Get("discount"), "9.999") + "<br/>";
            }
            if (discountCode.minimum_order_value < 0 || discountCode.minimum_order_value > 999999999999.99M)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_range"), tt.Get("minimum_order_value"), "999 999 999 999.99") + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Check if we should add or update the discount code
                if (postExists == false)
                {
                    // Add the discount code
                    DiscountCode.Add(discountCode);
                }
                else
                {
                    // Update the discount code
                    DiscountCode.Update(discountCode);
                }

                // Redirect the user to the list
                return Redirect("/admin_discount_codes" + returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.TranslatedTexts = tt;
                ViewBag.Languages = Language.GetAll(currentDomain.back_end_language, "id", "ASC");
                ViewBag.DiscountCode = discountCode;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

        } // End of the edit method
示例#37
0
    } // End of the Add method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a discount code
    /// </summary>
    /// <param name="post">A reference to a discount code post</param>
    public static void Update(DiscountCode post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.discount_codes SET language_id = @language_id, currency_code = @currency_code, discount_value = @discount_value, "
            + "free_freight = @free_freight, end_date = @end_date, once_per_customer = @once_per_customer, exclude_products_on_sale = @exclude_products_on_sale, "
            + "minimum_order_value = @minimum_order_value WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@currency_code", post.currency_code);
                cmd.Parameters.AddWithValue("@discount_value", post.discount_value);
                cmd.Parameters.AddWithValue("@free_freight", post.free_freight);
                cmd.Parameters.AddWithValue("@end_date", post.end_date);
                cmd.Parameters.AddWithValue("@once_per_customer", post.once_per_customer);
                cmd.Parameters.AddWithValue("@exclude_products_on_sale", post.exclude_products_on_sale);
                cmd.Parameters.AddWithValue("@minimum_order_value", post.minimum_order_value);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Update method
示例#38
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one discount code based on id
    /// </summary>
    /// <param name="id">The id for the post</param>
    /// <returns>A reference to a discount code post</returns>
    public static DiscountCode GetOneById(string id)
    {
        // Create the post to return
        DiscountCode post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.discount_codes WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", id);

                // Create a MySqlDataReader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new DiscountCode(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method