public HttpResponseMessage add(ProductOption post) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (ProductOptionType.MasterPostExists(post.product_option_type_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The product option type does not exist"); } else if (Option.MasterPostExists(post.option_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The option does not exist"); } // Make sure that the data is valid post.mpn_suffix = AnnytabDataValidation.TruncateString(post.mpn_suffix, 10); post.price_addition = AnnytabDataValidation.TruncateDecimal(post.price_addition, 0, 9999999999.99M); post.freight_addition = AnnytabDataValidation.TruncateDecimal(post.freight_addition, 0, 9999999999.99M); // Add the post ProductOption.Add(post); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added"); } // End of the add method
public async Task CreateProductOption(Guid productId, ProductOption productOption) { var product = await GetProductFromRepository(productId); _Logger.LogInformation("Add product option for product: {Id}", productId); product.AddProductOption(productOption); await _productRepository.Save(product); }
public async Task <ProductOption> CreateAsync(ProductOption productOption) { await _context.ProductOptions.AddAsync(productOption); await _context.SaveChangesAsync(); return(productOption); }
public void GetByIdFailureTest() { ProductOptionRepository repo = new ProductOptionRepository(); ProductOption test = repo.GetByID(Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")); Assert.IsNull(test); }
public bool AnyExistingAttributeOptionsWithName(ProductOption option) { return(_session.QueryOver <ProductOption>() .Where( specificationOption => specificationOption.Name.IsInsensitiveLike(option.Name, MatchMode.Exact)) .RowCount() > 0); }
//extended method public void UpdateProductOption(ProductOption productOption) { context.Entry(productOption).State = System.Data.EntityState.Modified; foreach (var pov in productOption.Values) { context.Entry(pov).State = System.Data.EntityState.Modified; } }
public async Task <ProductOption> CreatOptionAsync(ProductOption option) { await _dataBaseContext.ProductOption.AddAsync(option); await _dataBaseContext.SaveChangesAsync(); return(option); }
protected void FileImageAlbum_FileUploaded(object sender, FileUploadedEventArgs e) { var FileImageAlbum = (RadAsyncUpload)sender; //var Parent = FileImageAlbum.NamingContainer; //var ProductID = ((HiddenField)Parent.FindControl("hdnProductID")).Value; var ProductOptionCategoryID = string.IsNullOrEmpty(Request.QueryString["poi"]) ? "" : Request.QueryString["poi"]; //var RadListView1 = (RadListView)Parent.FindControl("RadListView1"); //var RadListView2 = (RadListView)Parent.FindControl("RadListView2"); string newName = Guid.NewGuid().GetHashCode().ToString("X") + e.File.GetExtension(); string targetFolder = "~/res/productoption/" + newName; e.File.SaveAs(Server.MapPath(targetFolder)); string bgColor = "#ffffff"; ResizeCropImage.CreateThumbNailWithBackGroundColor("~/res/productoption/", "~/res/productoption/thumbs/", newName, 70, 82, bgColor); ResizeCropImage.ResizeWithBackGroundColor(targetFolder, 1000, 1182, bgColor); //ResizeCropImage.ResizeByCondition(targetFolder + newName, 800, 800); //ResizeCropImage.CreateThumbNailByCondition("~/res/productoption/", "~/res/productoption/thumbs/", newName, 120, 120); if (string.IsNullOrEmpty(ProductOptionCategoryID)) { TempImage.Rows.Add(new object[] { newName }); RadListView2.DataSource = TempImage; RadListView2.DataBind(); } else { var oProductOption = new ProductOption(); oProductOption.ProductOptionInsert(newName, "", "", "", "", "", "", "", "", "", "", "", "", "", ProductOptionCategoryID, "1", "0", "0", "1", "" ); RadListView1.Rebind(); } }
} // End of the UpdateFreightAdditions method #endregion #region Get methods /// <summary> /// Get one product option post based on id /// </summary> /// <param name="productOptionTypeId">A product option type id</param> /// <param name="optionId">A option id</param> /// <returns>A reference to a product option post</returns> public static ProductOption GetOneById(Int32 productOptionTypeId, Int32 optionId) { // Create the post to return ProductOption post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT product_option_type_id, option_id, mpn_suffix, price_addition, freight_addition, " + "'Empty' AS product_code_suffix, 'Empty' AS title, 0 AS selected FROM dbo.product_options " + "WHERE product_option_type_id = @product_option_type_id AND option_id = @option_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 a parameters cmd.Parameters.AddWithValue("@product_option_type_id", productOptionTypeId); cmd.Parameters.AddWithValue("@option_id", optionId); // Create a reader 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 ProductOption(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
protected void AddBtn_Click(object sender, EventArgs e) { try { txtError.Text = string.Empty; if (!string.IsNullOrEmpty(txtName.Text)) { ProductOption option = new ProductOption(); option.OptionName = txtName.Text; List <ProductOption> childList = null; bool flag = true; if (txtParent.Checked) { childList = new List <ProductOption>(); GridDataItemCollection coll = grdOptions.Items; if (coll != null) { for (int i = 0; i < coll.Count; i++) { CheckBox chk = coll[i].FindControl("txtSelected") as CheckBox; if (chk != null) { GridDataItem dataitem = coll[i]; if (chk.Checked) { GridEditableItem editItem = coll[i] as GridEditableItem; int id = (int)editItem.GetDataKeyValue("ProductOptionID"); ProductOption childOption = (from po in entities.ProductOptions where po.OptionID == id select po).FirstOrDefault(); } } } } } if (flag) { entities.ProductOptions.Add(option); entities.SaveChanges(); SessionMessage = "Product option has been saved successfully."; Response.Redirect("ProductOptions.aspx"); } } else { txtError.Text = "You must provide all valid values."; } } catch (Exception ex) { txtError.Text = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; } }
public void Create(Guid productId, IProductOption option) { if (_repo.Get(option.Id) == null) { var toCreate = new ProductOption(option); toCreate.ProductId = productId; _repo.Save(toCreate, false); } }
public bool UpdateOption(Guid id, ProductOption option) { _dalObj = new ProductsDAL(); if (!_dalObj.UpdateOption(id, option)) { return(false); } return(true); }
//CreateChild public void CreateChild(Guid id, ProductOptionDTO child) { Product product = this._store.Get(id); ProductOption productOption = new ProductOption(); this._mapper.Map(child, productOption); product.ProductOptions.Add(productOption); this._store.Update(product); }
public void UpdateOption(Guid id, ProductOption option) { var entity = db.ProductOptions.FirstOrDefault(e => e.Id == id); entity.ProductId = option.ProductId; entity.Name = option.Name; entity.Description = option.Description; db.SaveChanges(); }
public async Task <ProductOption> UpdateProductOption(ProductOption productOption) { var updatedProductOption = _productContext.ProductOptions.Attach(productOption); _productContext.Entry(productOption).State = EntityState.Modified; await _productContext.SaveChangesAsync(); return(updatedProductOption); }
// Create a product option public bool Create(Guid productId, ProductOption productOption) { // Check if item exists already if (_repo.GetItemForProduct(productId, new Guid(productOption.Id)) != null) { return(false); } return(_repo.Save(productId, productOption)); }
public bool SaveNewProductOption(ProductOption option) { if (GetOptionById(option.Id) == null) { productOptionRepo.Insert(option); return(true); } return(false); }
public bool UpdateProductOption(ProductOption option) { if (GetOptionById(option.Id) != null) { productOptionRepo.Update(option); return(true); } return(false); }
public ProductOption GetProductOption(Guid productId, Guid id) { ProductOption prodOpt = null; _dalObj = new ProductsDAL(); prodOpt = _dalObj.GetProductOption(productId, id); return(prodOpt); }
public async Task <ProductOption> CreateProductOption(ProductOption productOption, Product product) { productOption.Product = product; await _context.ProductOptions.AddAsync(productOption); await _context.SaveChangesAsync(); return(productOption); }
public void AddProductOption(ProductOption productOption, int quantity = 1) { if (CanAddProductOption(productOption, quantity).Any()) { throw new InvalidOperationException(); } _includedProductOptions.Add(new IncludedProductOptionInTariff(productOption.Id, quantity)); }
public void CreateOption(Guid productId, ProductOption option) { option.ProductId = productId; using (ProductContext db = new ProductContext()) { db.ProductOptions.Add(option); db.SaveChanges(); } }
private ProductOption CreateOption(string name) { var option = new ProductOption { Name = name }; Session.Transact(session => session.Save(option)); return(option); }
public IHttpActionResult UpdateOption(Guid id, ProductOption option) { _logger.Info("ProductController: UpdateOption " + Environment.NewLine + DateTime.Now); if (!_productServices.UpdateOption(id, option)) { return(Content(HttpStatusCode.NotFound, "Product not found")); } return(Content(HttpStatusCode.Accepted, option)); }
public ProductOption LoadOptionById(Guid id) { using (var conn = Helpers.NewConnection()) { string query = "SELECT * FROM ProductOption WHERE Id = @Id"; ProductOption result = conn.Query <ProductOption>(query, new { id }).SingleOrDefault(); return(result); } }
public void AddProductOption(Guid productId, ProductOption option) { using (var conn = Helpers.NewConnection()) { option.ProductId = productId; string query = "INSERT INTO ProductOption VALUES(@Id,@ProductId,@Name,@Description)"; conn.Execute(query, option); } }
public async Task <ProductOption> CreateOption(ProductOption productOption) { productOption.AddedDate = DateTime.Now; await _context.ProductOptions.AddAsync(productOption); await _context.SaveChangesAsync(); return(productOption); }
public void UpdateOption(Guid id, ProductOption option) { var updatedOption = new ProductOption(id).Update(option); if (!updatedOption.IsNew) { updatedOption.Save(); } }
public void DeleteOption(Guid id) { using (ProductContext db = new ProductContext()) { ProductOption productOptionToRemove = db.ProductOptions.Where(p => p.Id == id).FirstOrDefault(); db.ProductOptions.Remove(productOptionToRemove); db.SaveChanges(); } }
public async Task UpdateOption(int id, ProductOption productOption) { var option = await GetOptionById(id); option.ModifiedDate = DateTime.Now; option.Title = productOption.Title; option.Type = productOption.Type; await _context.SaveChangesAsync(); }
public async Task UpdateAsync(ProductOption productOption) { var updateResult = await _productOptionRepository.UpdateAsync(productOption); if (updateResult == 0) { throw new ProductOptionNotFoundException(productOption.Id); } }
} // End of the constructor #endregion #region Insert methods /// <summary> /// Add one product option post /// </summary> /// <param name="post">A reference to a product option post</param> public static void Add(ProductOption post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "INSERT INTO dbo.product_options (product_option_type_id, option_id, mpn_suffix, " + "price_addition, freight_addition) " + "VALUES (@product_option_type_id, @option_id, @mpn_suffix, @price_addition, @freight_addition);"; // 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("@product_option_type_id", post.product_option_type_id); cmd.Parameters.AddWithValue("@option_id", post.option_id); cmd.Parameters.AddWithValue("@mpn_suffix", post.mpn_suffix); cmd.Parameters.AddWithValue("@price_addition", post.price_addition); cmd.Parameters.AddWithValue("@freight_addition", post.freight_addition); // 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(ProductOption post) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (ProductOptionType.MasterPostExists(post.product_option_type_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The product option type does not exist"); } else if (Option.MasterPostExists(post.option_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The option does not exist"); } // Make sure that the data is valid post.mpn_suffix = AnnytabDataValidation.TruncateString(post.mpn_suffix, 10); post.price_addition = AnnytabDataValidation.TruncateDecimal(post.price_addition, 0, 9999999999.99M); post.freight_addition = AnnytabDataValidation.TruncateDecimal(post.freight_addition, 0, 9999999999.99M); // Get the saved post ProductOption savedPost = ProductOption.GetOneById(post.product_option_type_id, post.option_id); // Check if the post exists if (savedPost == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist"); } // Update the post ProductOption.Update(post); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful"); } // End of the update method
} // End of the GetOneById method /// <summary> /// Get one product option post based on id /// </summary> /// <param name="productOptionTypeId">A product option type id</param> /// <param name="optionId">A option id</param> /// <param name="optionId">A language id</param> /// <returns>A reference to a product option post</returns> public static ProductOption GetOneById(Int32 productOptionTypeId, Int32 optionId, Int32 languageId) { // Create the post to return ProductOption post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT P.product_option_type_id, P.option_id, P.mpn_suffix, P.price_addition, P.freight_addition, " + "O.product_code_suffix, D.title, 1 as selected FROM dbo.product_options AS P INNER JOIN " + "dbo.options AS O ON P.option_id = O.id INNER JOIN dbo.options_detail AS D ON P.option_id = D.option_id " + "WHERE P.product_option_type_id = @product_option_type_id AND P.option_id = @option_id AND " + "D.language_id = @language_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 a parameters cmd.Parameters.AddWithValue("@product_option_type_id", productOptionTypeId); cmd.Parameters.AddWithValue("@option_id", optionId); cmd.Parameters.AddWithValue("@language_id", languageId); // Create a reader 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 ProductOption(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
} // End of the GetOtherOptions method /// <summary> /// This recursive method will get all combinations of a product (variants) /// </summary> /// <param name="productCombinations">A list that should be filled with product combinations</param> /// <param name="lists">A dictionary with product option lists</param> /// <param name="depth">The current depth</param> /// <param name="current">The current product option array</param> public static void GetProductCombinations(List<ProductOption[]> productCombinations, Dictionary<Int32, List<ProductOption>> productOptions, Int32 depth, ProductOption[] current) { // Loop the dictionary list for (int i = 0; i < productOptions[depth].Count; i++) { // Get the list of product variants List<ProductOption> variants = productOptions[depth]; // Get the current variant current[depth] = variants[i]; // Check if we have reached the end or not if (depth < productOptions.Count - 1) { GetProductCombinations(productCombinations, productOptions, depth + 1, current); } else { // Add a copy of the array to the results list ProductOption[] resultArray = new ProductOption[current.Length]; current.CopyTo(resultArray, 0); productCombinations.Add(resultArray); } } } // End of the GetProductCombinations method
protected void RadListView1_ItemCommand(object sender, RadListViewCommandEventArgs e) { try { if (e.CommandName == "PerformInsert") { var item = e.ListViewItem; var FileImageName = (RadUpload)item.FindControl("FileImageName"); var strProductName = ((Label)FormView1.FindControl("lblProductName")).Text.Trim(); var strConvertedProductName = Common.ConvertTitle(strProductName); var strImageName = FileImageName.UploadedFiles.Count > 0 ? Guid.NewGuid().GetHashCode().ToString("X") + FileImageName.UploadedFiles[0].GetExtension() : ""; var strTitle = ((RadTextBox)item.FindControl("txtTitle")).Text.Trim(); var strDescription = ((RadTextBox)item.FindControl("txtDescription")).Text.Trim(); var strTitleEn = ((RadTextBox)item.FindControl("txtTitleEn")).Text.Trim(); var strDescriptionEn = ((RadTextBox)item.FindControl("txtDescriptionEn")).Text.Trim(); var IsAvailable = ((CheckBox)item.FindControl("chkAddIsAvailable")).Checked.ToString(); var Priority = ((RadNumericTextBox)item.FindControl("txtPriority")).Text.Trim(); var oProductOption = new ProductOption(); oProductOption.ProductOptionInsert( strImageName, "", "", strTitle, strConvertedProductName, strDescription, "", "", "", "", strTitleEn, strDescriptionEn, "", "", Request.QueryString["poi"], "1", "0", "0", IsAvailable, Priority); string strFullPath = "~/res/productoption/" + strImageName; if (!string.IsNullOrEmpty(strImageName)) { FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); string bgColor = "#ffffff"; ResizeCropImage.CreateThumbNailWithBackGroundColor("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 70, 82, bgColor); ResizeCropImage.ResizeWithBackGroundColor(strFullPath, 1000, 1182, bgColor); //ResizeCropImage.ResizeByCondition(strFullPath, 600, 600); //ResizeCropImage.CreateThumbNailByCondition("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 120, 120); } RadListView1.InsertItemPosition = RadListViewInsertItemPosition.None; } else if (e.CommandName == "Update") { var item = e.ListViewItem; var FileImageName = (RadUpload)item.FindControl("FileImageName"); var dsUpdateParam = ObjectDataSource1.UpdateParameters; var strProductOptionID = ((HiddenField)item.FindControl("hdnProductOptionID")).Value; //var strProductName = ((Label)FormView1.FindControl("lblProductName")).Text.Trim(); //var strConvertedProductName = Common.ConvertTitle(strProductName); var strOldImageName = ((HiddenField)item.FindControl("hdnImageName")).Value; var strIsAvailable = ((CheckBox)item.FindControl("chkAddIsAvailable")).Checked.ToString(); var strImageName = FileImageName.UploadedFiles.Count > 0 ? Guid.NewGuid().GetHashCode().ToString("X") + FileImageName.UploadedFiles[0].GetExtension() : ""; var strProductOptionCategoryID = string.IsNullOrEmpty(Request.QueryString["poi"]) ? "" : Request.QueryString["poi"]; dsUpdateParam["ImageName"].DefaultValue = !string.IsNullOrEmpty(strImageName) ? strImageName : strOldImageName; //dsUpdateParam["ConvertedProductName"].DefaultValue = strConvertedProductName; dsUpdateParam["IsAvailable"].DefaultValue = strIsAvailable; dsUpdateParam["ProductOptionCategoryID"].DefaultValue = strProductOptionCategoryID; if (!string.IsNullOrEmpty(strImageName)) { var strOldImagePath = Server.MapPath("~/res/productoption/" + strOldImageName); var strOldThumbImagePath = Server.MapPath("~/res/productoption/thumbs/" + strOldImageName); if (File.Exists(strOldImagePath)) File.Delete(strOldImagePath); if (File.Exists(strOldThumbImagePath)) File.Delete(strOldThumbImagePath); //strImageName = (string.IsNullOrEmpty(strConvertedProductName) ? "" : strConvertedProductName + "-") + strProductOptionID + strImageName.Substring(strImageName.LastIndexOf('.')); string strFullPath = "~/res/productoption/" + strImageName; FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); string bgColor = "#ffffff"; ResizeCropImage.CreateThumbNailWithBackGroundColor("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 70, 82, bgColor); ResizeCropImage.ResizeWithBackGroundColor(strFullPath, 1000, 1182, bgColor); //ResizeCropImage.ResizeByCondition(strFullPath, 600, 600); //ResizeCropImage.CreateThumbNailByCondition("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 120, 120); } } else if (e.CommandName == "Delete") { var strOldImageName = ((HiddenField)e.ListViewItem.FindControl("hdnImageName")).Value; DeleteImage(strOldImageName); } else if (e.CommandName == "QuickUpdate") { string ProductOptionID, Priority, IsAvailable; var oProductOption = new ProductOption(); foreach (RadListViewDataItem item in RadListView1.Items) { ProductOptionID = item.GetDataKeyValue("ProductOptionID").ToString(); Priority = ((RadNumericTextBox)item.FindControl("txtPriority")).Text.Trim(); IsAvailable = ((CheckBox)item.FindControl("chkIsAvailable")).Checked.ToString(); oProductOption.ProductOptionQuickUpdate( ProductOptionID, "1", "0", "0", IsAvailable, Priority ); } } else if (e.CommandName == "DeleteSelected") { var oProductOption = new ProductOption(); string ProductOptionID, OldImageName; foreach (RadListViewDataItem item in RadListView1.Items) { var chkSelect = (CheckBox)item.FindControl("chkSelect"); if (chkSelect.Checked) { ProductOptionID = item.GetDataKeyValue("ProductOptionID").ToString(); OldImageName = ((HiddenField)item.FindControl("hdnImageName")).Value; DeleteImage(OldImageName); oProductOption.ProductOptionDelete(ProductOptionID); } } } RadListView1.Rebind(); } catch (Exception ex) { lblError.Text = ex.Message; } }
} // End of the Add method #endregion #region Update methods /// <summary> /// Update a product option post /// </summary> /// <param name="post">A reference to a product option post</param> public static void Update(ProductOption post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.product_options SET mpn_suffix = @mpn_suffix, price_addition = @price_addition, " + "freight_addition = @freight_addition WHERE product_option_type_id = @product_option_type_id AND option_id = @option_id;"; // 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("@product_option_type_id", post.product_option_type_id); cmd.Parameters.AddWithValue("@option_id", post.option_id); cmd.Parameters.AddWithValue("@mpn_suffix", post.mpn_suffix); cmd.Parameters.AddWithValue("@price_addition", post.price_addition); cmd.Parameters.AddWithValue("@freight_addition", post.freight_addition); // 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
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e) { if (e.CommandName == "alpha" || e.CommandName == "NoFilter") { String value = null; switch (e.CommandName) { case ("alpha"): { value = string.Format("{0}%", e.CommandArgument); break; } case ("NoFilter"): { value = "%"; break; } } ObjectDataSource1.SelectParameters["ProductOptionTitle"].DefaultValue = value; ObjectDataSource1.DataBind(); RadGrid1.Rebind(); } else if (e.CommandName == "QuickUpdate") { string ProductOptionID, Priority, IsShowOnHomePage, IsHot, IsNew, IsAvailable; var oProductOption = new ProductOption(); foreach (GridDataItem item in RadGrid1.Items) { ProductOptionID = item.GetDataKeyValue("ProductOptionID").ToString(); Priority = ((RadNumericTextBox)item.FindControl("txtPriority")).Text.Trim(); IsShowOnHomePage = ((CheckBox)item.FindControl("chkIsShowOnHomePage")).Checked.ToString(); IsHot = ((CheckBox)item.FindControl("chkIsHot")).Checked.ToString(); IsNew = ((CheckBox)item.FindControl("chkIsNew")).Checked.ToString(); IsAvailable = ((CheckBox)item.FindControl("chkIsAvailable")).Checked.ToString(); oProductOption.ProductOptionQuickUpdate( ProductOptionID, IsShowOnHomePage, IsHot, IsNew, IsAvailable, Priority ); } } else if (e.CommandName == "DeleteSelected") { string OldImageName; var oProductOption = new ProductOption(); foreach (GridDataItem item in RadGrid1.SelectedItems) { OldImageName = ((HiddenField)item.FindControl("hdnImageName")).Value; DeleteImage(OldImageName); } } else if (e.CommandName == "PerformInsert" || e.CommandName == "Update") { var command = e.CommandName; var row = command == "PerformInsert" ? (GridEditFormInsertItem)e.Item : (GridEditFormItem)e.Item; var FileImageName = (RadUpload)row.FindControl("FileImageName"); var oProductOption = new ProductOption(); string strProductOptionID = ((HiddenField)row.FindControl("hdnProductOptionID")).Value; string strOldImageName = ((HiddenField)row.FindControl("hdnOldImageName")).Value; string strImageName = FileImageName.UploadedFiles.Count > 0 ? FileImageName.UploadedFiles[0].GetName() : ""; string strPriority = ((RadNumericTextBox)row.FindControl("txtPriority")).Text.Trim(); string strMetaTittle = ((RadTextBox)row.FindControl("txtMetaTittle")).Text.Trim(); string strMetaDescription = ((RadTextBox)row.FindControl("txtMetaDescription")).Text.Trim(); string strProductOptionTitle = ((RadTextBox)row.FindControl("txtProductOptionTitle")).Text.Trim(); string strConvertedProductOptionTitle = Common.ConvertTitle(strProductOptionTitle); string strDescription = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtDescription")).Content.Trim())); string strContent = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtContent")).Content.Trim())); string strTag = ((RadTextBox)row.FindControl("txtTag")).Text.Trim(); //string strProductOptionCategoryID = ((RadComboBox)row.FindControl("ddlCategory")).SelectedValue; string strProductOptionCategoryID = string.IsNullOrEmpty(Request.QueryString["poi"]) ? "" : Request.QueryString["poi"]; string strIsShowOnHomePage = ((CheckBox)row.FindControl("chkIsShowOnHomePage")).Checked.ToString(); string strIsHot = ((CheckBox)row.FindControl("chkIsHot")).Checked.ToString(); string strIsNew = ((CheckBox)row.FindControl("chkIsNew")).Checked.ToString(); string strIsAvailable = ((CheckBox)row.FindControl("chkIsAvailable")).Checked.ToString(); if (e.CommandName == "PerformInsert") { strImageName = oProductOption.ProductOptionInsert( strImageName, strMetaTittle, strMetaDescription, strProductOptionTitle, strConvertedProductOptionTitle, strDescription, strContent, strTag, "", "", "", "", "", "", strProductOptionCategoryID, strIsShowOnHomePage, strIsHot, strIsNew, strIsAvailable, strPriority ); string strFullPath = "~/res/productoption/" + strImageName; if (!string.IsNullOrEmpty(strImageName)) { FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); string bgColor = "#ffffff"; ResizeCropImage.CreateThumbNailWithBackGroundColor("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 70, 82, bgColor); ResizeCropImage.ResizeWithBackGroundColor(strFullPath, 550, 650, bgColor); //ResizeCropImage.ResizeByCondition(strFullPath, 800, 800); //ResizeCropImage.CreateThumbNailByCondition("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 120, 120); } RadGrid1.Rebind(); } else { var dsUpdateParam = ObjectDataSource1.UpdateParameters; var strOldImagePath = Server.MapPath("~/res/productoption/" + strOldImageName); var strOldThumbImagePath = Server.MapPath("~/res/productoption/thumbs/" + strOldImageName); dsUpdateParam["ProductOptionTitle"].DefaultValue = strProductOptionTitle; dsUpdateParam["ConvertedProductOptionTitle"].DefaultValue = strConvertedProductOptionTitle; dsUpdateParam["ImageName"].DefaultValue = strImageName; dsUpdateParam["ProductOptionCategoryID"].DefaultValue = strProductOptionCategoryID; dsUpdateParam["IsShowOnHomePage"].DefaultValue = strIsShowOnHomePage; dsUpdateParam["IsHot"].DefaultValue = strIsHot; dsUpdateParam["IsNew"].DefaultValue = strIsNew; dsUpdateParam["IsAvailable"].DefaultValue = strIsAvailable; if (!string.IsNullOrEmpty(strImageName)) { if (File.Exists(strOldImagePath)) File.Delete(strOldImagePath); if (File.Exists(strOldThumbImagePath)) File.Delete(strOldThumbImagePath); strImageName = (string.IsNullOrEmpty(strConvertedProductOptionTitle) ? "" : strConvertedProductOptionTitle + "-") + strProductOptionID + strImageName.Substring(strImageName.LastIndexOf('.')); string strFullPath = "~/res/productoption/" + strImageName; FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); string bgColor = "#ffffff"; ResizeCropImage.CreateThumbNailWithBackGroundColor("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 70, 82, bgColor); ResizeCropImage.ResizeWithBackGroundColor(strFullPath, 550, 650, bgColor); //ResizeCropImage.ResizeByCondition(strFullPath, 800, 800); //ResizeCropImage.CreateThumbNailByCondition("~/res/productoption/", "~/res/productoption/thumbs/", strImageName, 120, 120); } } } if (e.CommandName == "DeleteImage") { var oProductOption = new ProductOption(); var lnkDeleteImage = (LinkButton)e.CommandSource; var s = lnkDeleteImage.Attributes["rel"].ToString().Split('#'); var strProductOptionID = s[0]; var strImageName = s[1]; oProductOption.ProductOptionImageDelete(strProductOptionID); DeleteImage(strImageName); RadGrid1.Rebind(); } }
public decimal GetFinalPriceForProduct(ProductOption o) { return GetFinalPriceForProduct(o.GetBestSource().Pricing); }
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters 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 form values (Product) Int32 productId = Convert.ToInt32(collection["txtId"]); Int32 categoryId = Convert.ToInt32(collection["selectCategory"]); string title = collection["txtTitle"]; string productCode = collection["txtProductCode"]; string manufacturer_code = collection["txtManufacturerCode"]; string gtin = collection["txtGtin"]; decimal price = 0; decimal.TryParse(collection["txtPrice"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out price); decimal freight = 0; decimal.TryParse(collection["txtFreight"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out freight); Int32 unitId = Convert.ToInt32(collection["selectUnit"]); decimal discount = 0; decimal.TryParse(collection["txtDiscount"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out discount); decimal mountTimeHours = 0; decimal.TryParse(collection["txtMountTimeHours"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out mountTimeHours); bool from_price = Convert.ToBoolean(collection["cbFromPrice"]); string brand = collection["txtBrand"]; string supplierErpId = collection["txtSupplierErpId"]; string description = collection["txtDescription"]; string extra_content = collection["txtExtraContent"]; string metaDescription = collection["txtMetaDescription"]; string metaKeywords = collection["txtMetaKeywords"]; string pageName = collection["txtPageName"]; string condition = collection["selectCondition"]; string variant_image_filename = collection["txtVariantImageFileName"]; string metaRobots = collection["selectMetaRobots"]; string availability_status = collection["selectAvailabilityStatus"]; DateTime availability_date = DateTime.MinValue; DateTime.TryParse(collection["txtAvailabilityDate"], out availability_date); string gender = collection["selectGender"]; string age_group = collection["selectAgeGroup"]; bool adult_only = Convert.ToBoolean(collection["cbAdultOnly"]); decimal unit_pricing_measure = 0; decimal.TryParse(collection["txtUnitPricingMeasure"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out unit_pricing_measure); Int32 unit_pricing_base_measure = 0; Int32.TryParse(collection["txtUnitPricingBaseMeasure"].Replace(",", "."), out unit_pricing_base_measure); Int32 comparison_unit = Convert.ToInt32(collection["selectComparisonUnit"]); string energy_efficiency_class = collection["selectEnergyClass"]; bool downloadable_files = Convert.ToBoolean(collection["cbDownloadableFiles"]); string deliveryTime = collection["txtDeliveryTime"]; string affiliateLink = collection["txtAffiliateLink"]; decimal toll_freight_addition = 0; decimal.TryParse(collection["txtTollFreight"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out toll_freight_addition); Int32 valueAddedTaxId = Convert.ToInt32(collection["selectValueAddedTax"]); string accountCode = collection["txtAccountCode"]; string google_category = collection["txtGoogleCategory"]; bool use_local_images = Convert.ToBoolean(collection["cbLocalImages"]); bool use_local_files = Convert.ToBoolean(collection["cbLocalFiles"]); DateTime date_added = DateTime.MinValue; DateTime.TryParse(collection["txtDateAdded"], out date_added); string size_type = collection["selectSizeType"]; string size_system = collection["selectSizeSystem"]; bool inactive = Convert.ToBoolean(collection["cbInactive"]); // Get form values (ProductOptionTypes) string[] productOptionTypeIds = collection.GetValues("productOptionTypeId"); string[] optionTypeIds = collection.GetValues("optionTypeId"); string[] optionTypeSelectedInput = collection.GetValues("optionTypeSelected"); string[] optionTypeTitles = collection.GetValues("optionTypeTitle"); // Get counts Int32 optionTypeIdsCount = optionTypeIds != null ? optionTypeIds.Length : 0; Int32 optionTypeSelectedInputCount = optionTypeSelectedInput != null ? optionTypeSelectedInput.Length : 0; // Get option type selected input List<string> optionTypeSelected = new List<string>(optionTypeIdsCount); int counter = 0; while (counter < optionTypeSelectedInputCount) { if (optionTypeSelectedInput[counter] == "true") { optionTypeSelected.Add("true"); counter += 2; } else { optionTypeSelected.Add("false"); counter += 1; } } // Get form values (ProductOptions) string[] keyOptionTypeIds = collection.GetValues("keyOptionTypeId"); string[] optionIds = collection.GetValues("optionId"); string[] optionSelectedInput = collection.GetValues("optionSelected"); string[] optionTitles = collection.GetValues("optionTitle"); string[] optionSuffixes = collection.GetValues("optionSuffix"); string[] optionMpnSuffixes = collection.GetValues("optionMpnSuffix"); string[] optionPriceAdditions = collection.GetValues("optionPriceAddition"); string[] optionFreightAdditions = collection.GetValues("optionFreightAddition"); // Get counts Int32 keyOptionTypeIdsCount = keyOptionTypeIds != null ? keyOptionTypeIds.Length : 0; Int32 optionSelectedInputCount = optionSelectedInput != null ? optionSelectedInput.Length : 0; // Get option selected input List<string> optionSelected = new List<string>(keyOptionTypeIdsCount); counter = 0; while (counter < optionSelectedInputCount) { if (optionSelectedInput[counter] == "true") { optionSelected.Add("true"); counter += 2; } else { optionSelected.Add("false"); counter += 1; } } // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get the product Product product = Product.GetOneById(productId, adminLanguageId); // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Check if the product exists if (product == null) { // Create a new product product = new Product(); } // Set values for the product product.category_id = categoryId; product.title = title; product.product_code = productCode; product.manufacturer_code = manufacturer_code; product.gtin = gtin; product.unit_price = price; product.unit_freight = freight; product.unit_id = unitId; product.discount = discount; product.mount_time_hours = mountTimeHours; product.from_price = from_price; product.brand = brand; product.supplier_erp_id = supplierErpId; product.main_content = description; product.extra_content = extra_content; product.meta_description = metaDescription; product.meta_keywords = metaKeywords; product.page_name = pageName; product.condition = condition; product.variant_image_filename = variant_image_filename; product.meta_robots = metaRobots; product.gender = gender; product.age_group = age_group; product.adult_only = adult_only; product.unit_pricing_measure = unit_pricing_measure; product.unit_pricing_base_measure = unit_pricing_base_measure; product.comparison_unit_id = comparison_unit; product.size_type = size_type; product.size_system = size_system; product.energy_efficiency_class = energy_efficiency_class; product.downloadable_files = downloadable_files; product.delivery_time = deliveryTime; product.affiliate_link = affiliateLink; product.toll_freight_addition = toll_freight_addition; product.value_added_tax_id = valueAddedTaxId; product.account_code = accountCode; product.google_category = google_category; product.use_local_images = use_local_images; product.use_local_files = use_local_files; product.availability_status = availability_status; product.availability_date = AnnytabDataValidation.TruncateDateTime(availability_date); product.date_added = AnnytabDataValidation.TruncateDateTime(date_added); product.inactive = inactive; // Count the product option types Int32 optionTypesCount = productOptionTypeIds != null ? productOptionTypeIds.Length : 0; // Create the list of product option types List<ProductOptionType> productOptionTypes = new List<ProductOptionType>(optionTypesCount); // Add all product option types to the list for (int i = 0; i < optionTypesCount; i++) { // Create a product option type ProductOptionType productOptionType = new ProductOptionType(); productOptionType.id = Convert.ToInt32(productOptionTypeIds[i]); productOptionType.product_id = productId; productOptionType.option_type_id = Convert.ToInt32(optionTypeIds[i]); productOptionType.selected = Convert.ToBoolean(optionTypeSelected[i]); productOptionType.title = optionTypeTitles[i]; productOptionType.sort_order = Convert.ToInt16(i); // Add the product option type to the list productOptionTypes.Add(productOptionType); } // Create a dictionary for product options Dictionary<Int32, List<ProductOption>> productOptions = new Dictionary<Int32, List<ProductOption>>(optionTypesCount); // Count product options Int32 optionsCount = keyOptionTypeIds != null ? keyOptionTypeIds.Length : 0; // Create a new list of product options List<ProductOption> listProductOptions = new List<ProductOption>(10); // Create a error message string errorMessage = string.Empty; // Add all product options to the list for (int j = 0; j < optionsCount; j++) { // Create a product option Int32 optionTypeId = Convert.ToInt32(keyOptionTypeIds[j]); ProductOption productOption = new ProductOption(); productOption.product_option_type_id = Convert.ToInt32(keyOptionTypeIds[j]); productOption.option_id = Convert.ToInt32(optionIds[j]); productOption.selected = Convert.ToBoolean(optionSelected[j]); productOption.title = optionTitles[j]; productOption.product_code_suffix = optionSuffixes[j]; productOption.mpn_suffix = optionMpnSuffixes[j]; decimal.TryParse(optionPriceAdditions[j].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out productOption.price_addition); decimal.TryParse(optionFreightAdditions[j].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out productOption.freight_addition); // Add the product option to the list listProductOptions.Add(productOption); // Check for errors if (productOption.mpn_suffix.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("mpn_suffix"), "10") + "<br/>"; } if (productOption.price_addition < 0 || productOption.price_addition > 9999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("price_addition"), "9 999 999 999.99") + "<br/>"; } if (productOption.freight_addition < 0 || productOption.freight_addition > 9999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("freight_addition"), "9 999 999 999.99") + "<br/>"; } // Check if we should add the list and create a new list if ((j + 1) >= optionsCount) { // Add the post to the hash table productOptions.Add(optionTypeId, listProductOptions); } else if (keyOptionTypeIds[j + 1] != keyOptionTypeIds[j]) { // Add the post to the hash table productOptions.Add(optionTypeId, listProductOptions); // Create a new list listProductOptions = new List<ProductOption>(10); } } // Get a product on page name Product productOnPageName = Product.GetOneByPageName(product.page_name, adminLanguageId); // Check for errors if (productOnPageName != null && product.id != productOnPageName.id) { errorMessage += "• " + String.Format(tt.Get("error_field_language_unique"), tt.Get("page_name")) + "<br/>"; } if (product.page_name == string.Empty) { errorMessage += "• " + String.Format(tt.Get("error_field_required"), tt.Get("page_name")) + "<br/>"; } if (AnnytabDataValidation.CheckPageNameCharacters(product.page_name) == false) { errorMessage += "• " + String.Format(tt.Get("error_field_bad_chars"), tt.Get("page_name")) + "<br/>"; } if(product.category_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("category").ToLower()) + "<br/>"; } if (product.page_name.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("page_name"), "100") + "<br/>"; } if (product.unit_price < 0 || product.unit_price > 9999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("price"), "9 999 999 999.99") + "<br/>"; } if (product.unit_freight < 0 || product.unit_freight > 9999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("freight"), "9 999 999 999.99") + "<br/>"; } if (product.toll_freight_addition < 0 || product.toll_freight_addition > 9999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("toll_freight_addition"), "9 999 999 999.99") + "<br/>"; } if (product.discount < 0 || product.discount > 9.999M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("discount"), "9.999") + "<br/>"; } if (product.title.Length > 200) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("title"), "200") + "<br/>"; } if (product.product_code.Length > 20) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("product_code"), "20") + "<br/>"; } if (product.manufacturer_code.Length > 20) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("manufacturer_code"), "20") + "<br/>"; } if (product.gtin.Length > 20) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("gtin").ToUpper(), "20") + "<br/>"; } if (product.brand.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("brand").ToUpper(), "50") + "<br/>"; } if (product.supplier_erp_id.Length > 20) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("supplier_erp_id").ToUpper(), "20") + "<br/>"; } if (product.mount_time_hours < 0 || product.mount_time_hours > 9999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("mount_time_hours"), "9 999.99") + "<br/>"; } if (product.meta_description.Length > 200) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("meta_description"), "200") + "<br/>"; } if (product.meta_keywords.Length > 200) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("keywords"), "200") + "<br/>"; } if (product.account_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("account_code"), "10") + "<br/>"; } if (product.delivery_time.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("delivery_time"), "50") + "<br/>"; } if (product.affiliate_link.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("affiliate_link"), "100") + "<br/>"; } if (product.variant_image_filename.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("variant_image_filename"), "50") + "<br/>"; } if (product.google_category.Length > 250) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("google_category"), "300") + "<br/>"; } if (product.unit_pricing_measure < 0 || product.unit_pricing_measure > 99999.99999M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("unit_pricing_measure"), "99 999.99999") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the product if (product.id != 0) { // Update the product UpdateProduct(product, productOptionTypes, productOptions, adminLanguageId); } else { // Add the product AddProduct(product, productOptionTypes, productOptions, adminLanguageId); } // Redirect the user to the list return Redirect("/admin_products" + returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Units = Unit.GetAll(adminLanguageId, "name", "ASC"); ViewBag.Product = product; ViewBag.ProductOptionTypes = productOptionTypes; ViewBag.ProductOptions = productOptions; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method