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 HttpResponseMessage update(ProductOptionType post) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (Product.MasterPostExists(post.product_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The product does not exist"); } else if (OptionType.MasterPostExists(post.option_type_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The option type does not exist"); } // Get the saved post ProductOptionType savedPost = ProductOptionType.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 ProductOptionType.Update(post); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful"); } // End of the update method
} // End of the GetByProductId method /// <summary> /// Get product option types based on option type id /// </summary> /// <param name="optionTypeId">A option type id</param> /// <returns>A list of product option type posts</returns> public static List <ProductOptionType> GetByOptionTypeId(Int32 optionTypeId) { // Create the list to return List <ProductOptionType> posts = new List <ProductOptionType>(10); // Create the connection string and the sql statement. string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.product_option_types WHERE option_type_id = @option_type_id ORDER BY id ASC;"; // 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("@option_type_id", optionTypeId); // 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 data from the select command. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read. while (reader.Read()) { ProductOptionType productOptionType = new ProductOptionType(); productOptionType.id = Convert.ToInt32(reader["id"]); productOptionType.product_id = Convert.ToInt32(reader["product_id"]); productOptionType.option_type_id = Convert.ToInt32(reader["option_type_id"]); productOptionType.sort_order = Convert.ToInt16(reader["sort_order"]); posts.Add(productOptionType); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) { reader.Close(); } } } } // Return the list of posts return(posts); } // End of the GetByOptionTypeId method
} // End of the Add method #endregion #region Update methods /// <summary> /// Update a product option type post /// </summary> /// <param name="post">A reference to a product option type post</param> public static void Update(ProductOptionType post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.product_option_types SET sort_order = @sort_order " + "WHERE id = @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("@id", post.id); cmd.Parameters.AddWithValue("@sort_order", post.sort_order); // 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
public HttpResponseMessage update(ProductOptionType post) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Product.MasterPostExists(post.product_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The product does not exist")); } else if (OptionType.MasterPostExists(post.option_type_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The option type does not exist")); } // Get the saved post ProductOptionType savedPost = ProductOptionType.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 ProductOptionType.Update(post); // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The update was successful")); } // End of the update method
public List <ProductOptionType> get_all(Int32 languageId = 0) { // Create the list to return List <ProductOptionType> posts = ProductOptionType.GetAll(languageId); // Return the list return(posts); } // End of the get_all method
public ProductOptionType get_by_id(Int32 id = 0, Int32 languageId = 0) { // Create the post to return ProductOptionType post = ProductOptionType.GetOneById(id, languageId); // Return the post return(post); } // End of the get_by_id method
public List <ProductOptionType> get_by_product_id(Int32 id = 0, Int32 languageId = 0) { // Create the list to return List <ProductOptionType> posts = ProductOptionType.GetByProductId(id, languageId); // Return the list return(posts); } // End of the get_by_product_id method
} // End of the GetOneById method /// <summary> /// Get one product option type based on id /// </summary> /// <param name="id">An id</param> /// <param name="languageId">A language id</param> /// <returns>A reference to a product option type post</returns> public static ProductOptionType GetOneById(Int32 id, Int32 languageId) { // Create the post to return ProductOptionType post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT T.id, T.product_id, T.option_type_id, O.google_name, D.title, T.sort_order, 1 as selected FROM dbo.product_option_types " + "AS T INNER JOIN dbo.option_types_detail AS D ON T.option_type_id = D.option_type_id AND T.id = @id AND D.language_id = @language_id " + "INNER JOIN dbo.option_types AS O ON D.option_type_id = O.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 a parameters cmd.Parameters.AddWithValue("@id", id); 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 ProductOptionType(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 delete(Int32 id = 0) { // Create an error code variable Int32 errorCode = 0; // Delete the post errorCode = ProductOptionType.DeleteOnId(id); // Check if there is an error if (errorCode != 0) { return(Request.CreateResponse <string>(HttpStatusCode.Conflict, "Foreign key constraint")); } // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The delete was successful")); } // End of the delete method
} // End of the constructor #endregion #region Insert methods /// <summary> /// Add one product option type post /// </summary> /// <param name="post">A reference to a product option type post</param> public static long Add(ProductOptionType post) { // Create the long to return long idOfInsert = 0; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "INSERT INTO dbo.product_option_types (product_id, option_type_id, sort_order) " + "VALUES (@product_id, @option_type_id, @sort_order);SELECT SCOPE_IDENTITY();"; // 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_id", post.product_id); cmd.Parameters.AddWithValue("@option_type_id", post.option_type_id); cmd.Parameters.AddWithValue("@sort_order", post.sort_order); // 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 idOfInsert = Convert.ToInt64(cmd.ExecuteScalar()); } catch (Exception e) { throw e; } } } // Return the id of the inserted item return idOfInsert; } // End of the Add method
} // End of the constructor #endregion #region Insert methods /// <summary> /// Add one product option type post /// </summary> /// <param name="post">A reference to a product option type post</param> public static long Add(ProductOptionType post) { // Create the long to return long idOfInsert = 0; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "INSERT INTO dbo.product_option_types (product_id, option_type_id, sort_order) " + "VALUES (@product_id, @option_type_id, @sort_order);SELECT SCOPE_IDENTITY();"; // 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_id", post.product_id); cmd.Parameters.AddWithValue("@option_type_id", post.option_type_id); cmd.Parameters.AddWithValue("@sort_order", post.sort_order); // 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 idOfInsert = Convert.ToInt64(cmd.ExecuteScalar()); } catch (Exception e) { throw e; } } } // Return the id of the inserted item return(idOfInsert); } // End of the Add method
public HttpResponseMessage add(ProductOptionType post) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Product.MasterPostExists(post.product_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The product does not exist")); } else if (OptionType.MasterPostExists(post.option_type_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The option type does not exist")); } // Add the post ProductOptionType.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(ProductOptionType post) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } else if (Product.MasterPostExists(post.product_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The product does not exist"); } else if (OptionType.MasterPostExists(post.option_type_id) == false) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The option type does not exist"); } // Add the post ProductOptionType.Add(post); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added"); } // 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
public ActionResult product(string id = "") { // Get the domain, the product, the currency and the value added tax Domain currentDomain = Tools.GetCurrentDomain(); Product currentProduct = Product.GetOneByPageName(id, currentDomain.front_end_language); // Make sure that the product not is null if (currentProduct == null) { Response.StatusCode = 404; Response.Status = "404 Not Found"; Response.Write(Tools.GetHttpNotFoundPage()); return new EmptyResult(); } // Get additional data Currency currency = Currency.GetOneById(currentDomain.currency); ValueAddedTax valueAddedTax = ValueAddedTax.GetOneById(currentProduct.value_added_tax_id); Category currentCategory = Category.GetOneById(currentProduct.category_id, currentDomain.front_end_language); currentCategory = currentCategory != null ? currentCategory : new Category(); // Get the product price and product code decimal productPrice = currentProduct.unit_price; string productCode = currentProduct.product_code; string manufacturerCode = currentProduct.manufacturer_code; string variantImageUrl = currentProduct.variant_image_filename; // Get product option types and product options List<ProductOptionType> productOptionTypes = ProductOptionType.GetByProductId(currentProduct.id, currentDomain.front_end_language); Dictionary<Int32, List<ProductOption>> productOptions = new Dictionary<int, List<ProductOption>>(productOptionTypes.Count); // Loop all the product option types for (int i = 0; i < productOptionTypes.Count; i++) { List<ProductOption> listProductOptions = ProductOption.GetByProductOptionTypeId(productOptionTypes[i].id, currentDomain.front_end_language); if (listProductOptions.Count > 0) { productPrice += listProductOptions[0].price_addition; productCode += listProductOptions[0].product_code_suffix; manufacturerCode += listProductOptions[0].mpn_suffix; variantImageUrl = variantImageUrl.Replace("[" + i + "]", listProductOptions[0].product_code_suffix); } // Add all the product options for the option type to the dictionary productOptions.Add(productOptionTypes[i].option_type_id, ProductOption.GetByProductOptionTypeId(productOptionTypes[i].id, currentDomain.front_end_language)); } // Adjust the product price with the currency conversion rate productPrice *= (currency.currency_base / currency.conversion_rate); // Round the price to the minor unit for the currency Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals); decimal ordinaryPrice = Math.Round(productPrice * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; productPrice = Math.Round(productPrice * (1 - currentProduct.discount) * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; // Check if prices should include vat bool pricesIncludesVat = Session["PricesIncludesVat"] != null ? Convert.ToBoolean(Session["PricesIncludesVat"]) : currentDomain.prices_includes_vat; // Add vat if prices should include vat if (pricesIncludesVat == true) { ordinaryPrice += Math.Round(ordinaryPrice * valueAddedTax.value * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; productPrice += Math.Round(productPrice * valueAddedTax.value * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; } // Calculate the comparison price decimal comparisonPrice = 0; if (currentProduct.unit_pricing_measure > 0 && currentProduct.unit_pricing_base_measure > 0) { comparisonPrice = (currentProduct.unit_pricing_base_measure / currentProduct.unit_pricing_measure) * productPrice; comparisonPrice = Math.Round(comparisonPrice * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; } // Get the translated texts KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC"); // Get a chain of parent categories List<Category> parentCategoryChain = Category.GetParentCategoryChain(currentCategory, currentDomain.front_end_language); // Create the bread crumb list List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(10); breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/")); for (int i = 0; i < parentCategoryChain.Count; i++) { breadCrumbs.Add(new BreadCrumb(parentCategoryChain[i].title, "/home/category/" + parentCategoryChain[i].page_name)); } breadCrumbs.Add(new BreadCrumb(currentProduct.title, "/home/product/" + currentProduct.page_name)); // Update page views if (currentProduct.page_views <= Int32.MaxValue - 1) { Product.UpdatePageviews(currentProduct.id, currentProduct.page_views + 1); } // Get the unit Unit unit = Unit.GetOneById(currentProduct.unit_id, currentDomain.front_end_language); // Set form values ViewBag.BreadCrumbs = breadCrumbs; ViewBag.CurrentDomain = currentDomain; ViewBag.TranslatedTexts = tt; ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language); ViewBag.CurrentCategory = currentCategory; ViewBag.Currency = currency; ViewBag.CurrentProduct = currentProduct; ViewBag.ValueAddedTax = valueAddedTax; ViewBag.ProductOptionTypes = productOptionTypes; ViewBag.ProductOptions = productOptions; ViewBag.ProductPrice = productPrice; ViewBag.OrdinaryPrice = ordinaryPrice; ViewBag.ComparisonPrice = comparisonPrice; ViewBag.Unit = unit != null ? unit : new Unit(); ViewBag.ProductCode = productCode; ViewBag.ManufacturerCode = manufacturerCode; ViewBag.VariantImageUrl = variantImageUrl; ViewBag.UserSettings = (Dictionary<string, string>)Session["UserSettings"]; ViewBag.PricesIncludesVat = pricesIncludesVat; ViewBag.CultureInfo = Tools.GetCultureInfo(ViewBag.CurrentLanguage); // Return the view return currentDomain.custom_theme_id == 0 ? View() : View("/Views/theme/product.cshtml"); } // End of the product method
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
} // End of the Add method #endregion #region Update methods /// <summary> /// Update a product option type post /// </summary> /// <param name="post">A reference to a product option type post</param> public static void Update(ProductOptionType post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.product_option_types SET sort_order = @sort_order " + "WHERE id = @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("@id", post.id); cmd.Parameters.AddWithValue("@sort_order", post.sort_order); // 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
} // End of the GetOneById method /// <summary> /// Get one product option type based on id /// </summary> /// <param name="id">An id</param> /// <param name="languageId">A language id</param> /// <returns>A reference to a product option type post</returns> public static ProductOptionType GetOneById(Int32 id, Int32 languageId) { // Create the post to return ProductOptionType post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT T.id, T.product_id, T.option_type_id, O.google_name, D.title, T.sort_order, 1 as selected FROM dbo.product_option_types " + "AS T INNER JOIN dbo.option_types_detail AS D ON T.option_type_id = D.option_type_id INNER JOIN dbo.option_types AS O ON D.option_type_id = O.id " + "WHERE T.id = @id AND D.language_id = @language_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 a parameters cmd.Parameters.AddWithValue("@id", id); 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 ProductOptionType(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
/// <summary> /// Create a google shopping file /// </summary> /// <param name="domain">A reference to the domain</param> public static void Create(Domain domain) { // Create the directory path string directoryPath = HttpContext.Current.Server.MapPath("/Content/domains/" + domain.id.ToString() + "/marketing/"); // Check if the directory exists if (System.IO.Directory.Exists(directoryPath) == false) { // Create the directory System.IO.Directory.CreateDirectory(directoryPath); } // Create the file string filepath = directoryPath + "GoogleShopping.xml.gz"; // Get all data that we need Currency currency = Currency.GetOneById(domain.currency); Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals); Country country = Country.GetOneById(domain.country_id, domain.front_end_language); // Create variables GZipStream gzipStream = null; XmlTextWriter xmlTextWriter = null; try { // Create a gzip stream gzipStream = new GZipStream(new FileStream(filepath, FileMode.Create), CompressionMode.Compress); // Create a xml text writer xmlTextWriter = new XmlTextWriter(gzipStream, new UTF8Encoding(true)); // Set the base url string baseUrl = domain.web_address; // Write the start of the document xmlTextWriter.WriteStartDocument(); // Write the rss tag xmlTextWriter.WriteStartElement("rss"); xmlTextWriter.WriteAttributeString("version", "2.0"); xmlTextWriter.WriteAttributeString("xmlns:g", "http://base.google.com/ns/1.0"); // Write the channel tag xmlTextWriter.WriteStartElement("channel"); // Write information about the channel xmlTextWriter.WriteStartElement("title"); xmlTextWriter.WriteString(domain.webshop_name); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteStartElement("link"); xmlTextWriter.WriteString(baseUrl); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteStartElement("description"); xmlTextWriter.WriteString("Products"); xmlTextWriter.WriteEndElement(); // Get products Int32 page = 1; List <Product> products = Product.GetActiveReliable(domain.front_end_language, 50, page, "title", "ASC"); while (products.Count > 0) { // Loop all the products for (int i = 0; i < products.Count; i++) { // Do not include affiliate products if (products[i].affiliate_link != "") { continue; } // Get all the product options List <ProductOptionType> productOptionTypes = ProductOptionType.GetByProductId(products[i].id, domain.front_end_language); // Check if the product has product options or not if (productOptionTypes.Count > 0) { // Get all the product options Dictionary <Int32, List <ProductOption> > productOptions = new Dictionary <Int32, List <ProductOption> >(productOptionTypes.Count); // Loop all the product option types for (int j = 0; j < productOptionTypes.Count; j++) { List <ProductOption> listProductOptions = ProductOption.GetByProductOptionTypeId(productOptionTypes[j].id, domain.front_end_language); productOptions.Add(j, ProductOption.GetByProductOptionTypeId(productOptionTypes[j].id, domain.front_end_language)); } // Get all the product combinations List <ProductOption[]> productCombinations = new List <ProductOption[]>(); ProductOption.GetProductCombinations(productCombinations, productOptions, 0, new ProductOption[productOptions.Count]); // Loop all the product combinations foreach (ProductOption[] optionArray in productCombinations) { // Get a product copy Product productCopy = products[i].Clone(); // Create an array with google variants List <string[]> googleVariants = new List <string[]>(); // Loop all the product options in the array Int32 optionCounter = 0; foreach (ProductOption option in optionArray) { // Adjust product values productCopy.product_code += option.product_code_suffix; productCopy.manufacturer_code += option.mpn_suffix; productCopy.title += " - " + option.title; productCopy.unit_price += option.price_addition; productCopy.unit_freight += option.freight_addition; productCopy.variant_image_filename = productCopy.variant_image_filename.Replace("[" + optionCounter.ToString() + "]", option.product_code_suffix); // Get the product option type ProductOptionType productOptionType = ProductOptionType.GetOneById(option.product_option_type_id, domain.front_end_language); // Add the google variant if (productOptionType.google_name != "") { googleVariants.Add(new string[] { productOptionType.google_name, option.title }); } // Add to the option counter optionCounter++; } // Write the product item to the xml file WriteProductItem(xmlTextWriter, domain, country, productCopy, currency, decimalMultiplier, googleVariants); } } else { // Write the product item to the xml file WriteProductItem(xmlTextWriter, domain, country, products[i], currency, decimalMultiplier, new List <string[]>(0)); } } // Get more products page = page + 1; products = Product.GetActiveReliable(domain.front_end_language, 50, page, "title", "ASC"); } // Write the end of the document (close rss and channel) xmlTextWriter.WriteEndDocument(); } catch (Exception e) { throw e; } finally { // Close streams if (xmlTextWriter != null) { // Close the XmlTextWriter xmlTextWriter.Close(); } if (gzipStream != null) { // Close the gzip stream gzipStream.Close(); } } } // End of the Create method
/// <summary> /// Create a PriceRunner file /// </summary> /// <param name="domain">A reference to the domain</param> public static void Create(Domain domain) { // Create the directory path string directoryPath = HttpContext.Current.Server.MapPath("/Content/domains/" + domain.id.ToString() + "/marketing/"); // Check if the directory exists if (System.IO.Directory.Exists(directoryPath) == false) { // Create the directory System.IO.Directory.CreateDirectory(directoryPath); } // Create the filepath string filepath = directoryPath + "PriceRunner.txt"; // Get all data that we need Currency currency = Currency.GetOneById(domain.currency); Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals); Country country = Country.GetOneById(domain.country_id, domain.front_end_language); // Create a stream writer StreamWriter writer = null; try { // Create the file to write UTF-8 encoded text writer = File.CreateText(filepath); // Write the heading for the file writer.WriteLine("Category|Product name|SKU|Price|Shipping Cost|Product URL|Manufacturer SKU|Manufacturer|EAN or UPC|Description|Image URL|Stock Status|Delivery time|Product state|ISBN"); // Get products Int32 page = 1; List<Product> products = Product.GetActiveReliable(domain.front_end_language, 50, page, "title", "ASC"); while(products.Count > 0) { // Loop all the products for (int i = 0; i < products.Count; i++) { // Do not include affiliate products if (products[i].affiliate_link != "") { continue; } // Get all the product options List<ProductOptionType> productOptionTypes = ProductOptionType.GetByProductId(products[i].id, domain.front_end_language); // Check if the product has product options or not if (productOptionTypes.Count > 0) { // Get all the product options Dictionary<Int32, List<ProductOption>> productOptions = new Dictionary<Int32, List<ProductOption>>(productOptionTypes.Count); // Loop all the product option types for (int j = 0; j < productOptionTypes.Count; j++) { List<ProductOption> listProductOptions = ProductOption.GetByProductOptionTypeId(productOptionTypes[j].id, domain.front_end_language); productOptions.Add(j, ProductOption.GetByProductOptionTypeId(productOptionTypes[j].id, domain.front_end_language)); } // Get all the product combinations List<ProductOption[]> productCombinations = new List<ProductOption[]>(); ProductOption.GetProductCombinations(productCombinations, productOptions, 0, new ProductOption[productOptions.Count]); // Loop all the product combinations foreach (ProductOption[] optionArray in productCombinations) { // Get a product copy Product productCopy = products[i].Clone(); // Loop all the product options in the array Int32 optionCounter = 0; foreach (ProductOption option in optionArray) { // Adjust product values productCopy.product_code += option.product_code_suffix; productCopy.manufacturer_code += option.mpn_suffix; productCopy.title += " - " + option.title; productCopy.unit_price += option.price_addition; productCopy.unit_freight += option.freight_addition; productCopy.variant_image_filename = productCopy.variant_image_filename.Replace("[" + optionCounter.ToString() + "]", option.product_code_suffix); // Get the product option type ProductOptionType productOptionType = ProductOptionType.GetOneById(option.product_option_type_id, domain.front_end_language); // Add to the option counter optionCounter++; } // Write the product item to the file WriteProductItem(writer, domain, country, productCopy, currency, decimalMultiplier); } } else { // Write the product item to the file WriteProductItem(writer, domain, country, products[i], currency, decimalMultiplier); } } // Get more products page = page + 1; products = Product.GetActiveReliable(domain.front_end_language, 50, page, "title", "ASC"); } } catch (Exception e) { throw e; } finally { // Close the stream writer if it is different from null if (writer != null) { writer.Close(); } } } // End of the Create method
public ActionResult add_product(FormCollection collection) { // Get the product id Int32 productId = Convert.ToInt32(collection["hiddenProductId"]); // Get the current domain Domain domain = Tools.GetCurrentDomain(); // Get the currency Currency currency = Currency.GetOneById(domain.currency); // Get the product by id Product product = Product.GetOneById(productId, domain.front_end_language); // Get translated texts KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC"); // Make sure that the product not is null if (product == null) { Response.StatusCode = 404; Response.Status = "404 Not Found"; Response.Write(Tools.GetHttpNotFoundPage()); return new EmptyResult(); } // Get form data decimal quantity = 0; decimal.TryParse(collection["txtQuantity"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out quantity); string[] productOptionTypeIds = collection.GetValues("productOptionTypeId"); string[] selectedOptionIds = collection.GetValues("selectProductOption"); // Get other values string productName = product.title; string productCode = product.product_code; string manufacturerCode = product.manufacturer_code; decimal unitPrice = product.unit_price; decimal unitFreight = product.unit_freight + product.toll_freight_addition; string variantImageUrl = product.variant_image_filename; // Update the added to cart statistic if(product.added_in_basket <= Int32.MaxValue - 1) { Product.UpdateAddedInBasket(product.id, product.added_in_basket + 1); } // Check if the product has a affiliate link if (product.affiliate_link != "") { // Redirect the user to the affiliate site return Redirect(product.affiliate_link); } // The count of option ids Int32 optionIdCount = selectedOptionIds != null ? selectedOptionIds.Length : 0; // Loop option identities and add to the price, freight and product code for (int i = 0; i < optionIdCount; i++) { // Convert the ids Int32 optionTypeId = Convert.ToInt32(productOptionTypeIds[i]); Int32 optionId = Convert.ToInt32(selectedOptionIds[i]); // Get the product option type and the product option ProductOptionType productOptionType = ProductOptionType.GetOneById(optionTypeId, domain.front_end_language); ProductOption productOption = ProductOption.GetOneById(optionTypeId, optionId, domain.front_end_language); // Add to values productName += "," + productOptionType.title + ": " + productOption.title; productCode += productOption.product_code_suffix; manufacturerCode += productOption.mpn_suffix; unitPrice += productOption.price_addition; unitFreight += productOption.freight_addition; variantImageUrl = variantImageUrl.Replace("[" + i + "]", productOption.product_code_suffix); } // Add delivery time to the product name productName += "," + tt.Get("delivery_time") + ": " + product.delivery_time; // Adjust the price and the freight with the conversion rate unitPrice *= (currency.currency_base / currency.conversion_rate); unitFreight *= (currency.currency_base / currency.conversion_rate); // Round the price to the minor unit for the currency Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals); unitPrice = Math.Round(unitPrice * (1 - product.discount) * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; unitFreight = Math.Round(unitFreight * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; // Get the value added tax ValueAddedTax vat = ValueAddedTax.GetOneById(product.value_added_tax_id); // Create a cart item CartItem cartItem = new CartItem(); cartItem.product_code = productCode; cartItem.product_id = product.id; cartItem.manufacturer_code = manufacturerCode; cartItem.product_name = productName; cartItem.quantity = quantity; cartItem.unit_price = unitPrice; cartItem.unit_freight = unitFreight; cartItem.vat_percent = vat.value; cartItem.variant_image_url = variantImageUrl; cartItem.use_local_images = product.use_local_images; // Add the cart item to the shopping cart CartItem.AddToShoppingCart(cartItem); // Redirect the user to the same product page return RedirectToAction("product", "home", new { id = product.page_name, cu = "true" }); } // End of the add_product method
public ActionResult add_to_cart(FormCollection collection) { // Get form data Int32 productId = Convert.ToInt32(collection["pid"]); decimal quantity = 0; decimal.TryParse(collection["qty"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out quantity); string[] productOptionTypeIds = collection["optionTypes"].Split('|'); string[] selectedOptionIds = collection["optionIds"].Split('|'); // Get the current domain Domain domain = Tools.GetCurrentDomain(); // Get the currency Currency currency = Currency.GetOneById(domain.currency); // Get the product by id Product product = Product.GetOneById(productId, domain.front_end_language); // Get translated texts KeyStringList tt = StaticText.GetAll(domain.front_end_language, "id", "ASC"); // Make sure that the product not is null if (product == null) { return new EmptyResult(); } // Get product values string productName = product.title; string productCode = product.product_code; string manufacturerCode = product.manufacturer_code; decimal unitPrice = product.unit_price; decimal unitFreight = product.unit_freight + product.toll_freight_addition; string variantImageUrl = product.variant_image_filename; // Update the added to cart statistic if (product.added_in_basket <= Int32.MaxValue - 1) { Product.UpdateAddedInBasket(product.id, product.added_in_basket + 1); } // The count of option ids Int32 optionIdCount = selectedOptionIds != null && selectedOptionIds[0] != "" ? selectedOptionIds.Length : 0; // Loop option identities and add to the price, freight and product code for (int i = 0; i < optionIdCount; i++) { // Convert the ids Int32 optionTypeId = Convert.ToInt32(productOptionTypeIds[i]); Int32 optionId = Convert.ToInt32(selectedOptionIds[i]); // Get the product option type and the product option ProductOptionType productOptionType = ProductOptionType.GetOneById(optionTypeId, domain.front_end_language); ProductOption productOption = ProductOption.GetOneById(optionTypeId, optionId, domain.front_end_language); // Add to values productName += "," + productOptionType.title + ": " + productOption.title; productCode += productOption.product_code_suffix; manufacturerCode += productOption.mpn_suffix; unitPrice += productOption.price_addition; unitFreight += productOption.freight_addition; variantImageUrl = variantImageUrl.Replace("[" + i + "]", productOption.product_code_suffix); } // Add delivery time to the product name productName += "," + tt.Get("delivery_time") + ": " + product.delivery_time; // Adjust the price and the freight with the conversion rate unitPrice *= (currency.currency_base / currency.conversion_rate); unitFreight *= (currency.currency_base / currency.conversion_rate); // Round the price to the minor unit for the currency Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals); unitPrice = Math.Round(unitPrice * (1 - product.discount) * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; unitFreight = Math.Round(unitFreight * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; // Get the value added tax ValueAddedTax vat = ValueAddedTax.GetOneById(product.value_added_tax_id); // Create a cart item CartItem cartItem = new CartItem(); cartItem.product_code = productCode; cartItem.product_id = product.id; cartItem.manufacturer_code = manufacturerCode; cartItem.product_name = productName; cartItem.quantity = quantity; cartItem.unit_price = unitPrice; cartItem.unit_freight = unitFreight; cartItem.vat_percent = vat.value; cartItem.variant_image_url = variantImageUrl; cartItem.use_local_images = product.use_local_images; // Add the cart item to the shopping cart CartItem.AddToShoppingCart(cartItem); // Check if prices should include VAT or not bool pricesIncludesVat = Session["PricesIncludesVat"] != null ? Convert.ToBoolean(Session["PricesIncludesVat"]) : domain.prices_includes_vat; // Get the current culture info CultureInfo cultureInfo = Tools.GetCultureInfo(Language.GetOneById(domain.front_end_language)); // Get cart statistics Dictionary<string, decimal> cartStatistics = CartItem.GetCartStatistics(domain, pricesIncludesVat); // Create the dictionary to return Dictionary<string, string> cartData = new Dictionary<string, string>(3); cartData.Add("cart_quantity", cartStatistics["total_quantity"].ToString("##,0.##", cultureInfo)); cartData.Add("cart_amount", cartStatistics["total_amount"].ToString("##,0.##", cultureInfo) + " " + domain.currency + (pricesIncludesVat == true ? " (" + tt.Get("including_vat").ToLower() + ")" : " (" + tt.Get("excluding_vat").ToLower() + ")")); cartData.Add("units_in_cart", tt.Get("units_in_cart").ToLower()); // Return a dictionary with cart data return Json(cartData); } // End of the add_to_cart method
} // End of the GetBySearch method #endregion #region Delete methods /// <summary> /// Delete a option type post on id /// </summary> /// <param name="id">The id number for the option type post</param> /// <returns>An error code</returns> public static Int32 DeleteOnId(int id) { // Delete options by option type id List<Option> options = Option.GetByOptionTypeId(id); for (int i = 0; i < options.Count; i++) { ProductOption.DeleteOnOptionId(options[i].id); Option.DeleteOnId(options[i].id); } // Delete product option types List<ProductOptionType> productOptionTypes = ProductOptionType.GetByOptionTypeId(id); for (int i = 0; i < productOptionTypes.Count; i++) { ProductOptionType.DeleteOnId(productOptionTypes[i].id); } // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "DELETE FROM dbo.option_types_detail WHERE option_type_id = @id;DELETE FROM dbo.option_types WHERE id = @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)) { // Set command timeout to 90 seconds cmd.CommandTimeout = 90; // Add parameters cmd.Parameters.AddWithValue("@id", id); // 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 (SqlException e) { // Check for a foreign key constraint error if (e.Number == 547) { return 5; } else { throw e; } } catch (Exception e) { throw e; } } } // Return the code for success return 0; } // End of the DeleteOnId method