private LSDecimal Calculate_PointOfSale(Basket basket, Dictionary <string, string> existingTransactions) { WebTrace.Write("CertiTAX: Begin Calculate POS"); CertiTAX.Order taxOrder = new CertiTAX.Order(); //SET THE TAXORDER ADDRESS BuildTaxOrderAddress(taxOrder, StoreDataSource.Load().DefaultWarehouse); //BUILD THE TAXORDER OBJECT BuildTaxOrder(taxOrder, basket, 0, existingTransactions); taxOrder.Nexus = "POS"; //EXECUTE THE TRANSACTION CertiTAX.TaxTransaction taxTransaction = null; try { taxTransaction = (new CertiTAX.CertiCalc()).Calculate(taxOrder); } catch (Exception ex) { WebTrace.Write("CertiTax could not calculate tax. The error was: " + ex.Message); if (!this.IgnoreFailedConfirm) { throw; } } //PARSE THE RESULTS LSDecimal totalTax = ParseTaxTransaction(taxTransaction, basket, 0); WebTrace.Write("CertiTAX: End Calculate POS"); return(totalTax); }
/// <summary> /// Implementation of data recryption /// </summary> /// <param name="storeId">ID of the store context</param> /// <param name="oldKey">Existing key used to encrypt data</param> /// <param name="newKey">New key to be applied to encrypted data</param> private static void InternalRecryptDatabase(int storeId, byte[] oldKey, byte[] newKey) { // WE MUST INITIALIZE THE STORE CONTEXT AS THIS THREAD HAS NO HTTPCONTEXT Store store = StoreDataSource.Load(storeId); if (store != null) { // INITIALIZE THE TOKEN WITH THE STORE CONTEXT Token.Instance.InitStoreContext(store); // PROCESS RECORDS IN BATCHES OF 100 int lastCount = 0; int count = RecryptionHelper.GetRecryptionWorkload(); while ((count > 0) && (count != lastCount)) { List <RecryptRecord> records = RecryptionHelper.LoadForRecrypt(100); foreach (RecryptRecord record in records) { record.DoRecrypt(oldKey, newKey); } // if lastCount and count ever match, it means nothing changed in the last iteration // keep track of this to prevent endless looping in case a recrypt operation fails lastCount = count; count = RecryptionHelper.GetRecryptionWorkload(); } // REMOVE RECRYPT FLAG RecryptionHelper.SetRecryptionFlag(false); } }
protected void Page_Load(object sender, EventArgs e) { bool luceneEnabled = ApplicationSettings.Instance.SearchProvider == "LuceneSearchProvider"; bool sqlFtsEnabled = ApplicationSettings.Instance.SearchProvider == "SqlFtsSearchProvider"; if (luceneEnabled) { // EVICT THE STORE FROM THE SESSION CACHE AND RELOAD // THIS IS DUE TO 2ND LEVEL CACHING NOT BEING UPDATED BY THE ASYNC PROCESS Store store = AbleContext.Current.Store; AbleContext.Current.Database.GetSession().Evict(store); AbleContext.Current.DatabaseFactory.SessionFactory.Evict(store.GetType(), store); AbleContext.Current.Store = StoreDataSource.Load(store.Id); ToggleProgress(false); NoFTSPanel.Visible = false; FTSPanel.Visible = true; } else if (sqlFtsEnabled) { ToggleProgressSQLFts(false); SQLFtsPanel.Visible = true; NoFTSPanel.Visible = false; FTSPanel.Visible = false; } else { NoFTSPanel.Visible = true; FTSPanel.Visible = false; } }
protected override async void OnInitialize() { var storeDataSource = new StoreDataSource(); var categories = await storeDataSource.LoadCategories(); foreach (var category in categories) { AssignSizes(category.Products); } Categories.AddRange(categories); }
private void AsycnSendEmails(int storeId, int userId, MailMessage[] messages) { //REINITIALIZE THE TOKEN WITH SAVED STORE/USER CONTEXT Store store = StoreDataSource.Load(storeId); if (store != null) { Token.Instance.InitStoreContext(store); User user = UserDataSource.Load(userId); Token.Instance.InitUserContext(user); SendEmails(messages); } }
private PackageList PreparePackages(Warehouse origin, BasketItemCollection contents) { PackageList plist = PackageManager.GetPackageList(contents); if (plist == null || plist.Count == 0) { return(null); } ProviderUnits pUnits = GetProviderUnits(origin.Country); //GET UNITS USED BY STORE Store store = StoreDataSource.Load(Token.Instance.StoreId); MeasurementUnit storeMeasurementUnit = store.MeasurementUnit; WeightUnit storeWeightUnit = store.WeightUnit; bool requireMC = storeMeasurementUnit != pUnits.MeasurementUnit; bool requireWC = storeWeightUnit != pUnits.WeightUnit; if (requireMC && requireWC) { plist.ConvertBoth(pUnits.WeightUnit, pUnits.MeasurementUnit); } else if (requireWC) { plist.ConvertWeight(pUnits.WeightUnit); } else if (requireMC) { plist.ConvertDimensions(pUnits.MeasurementUnit); } LSDecimal maxWeight = LocaleHelper.ConvertWeight(WeightUnit.Pounds, MaxPackageWeight, pUnits.WeightUnit); LSDecimal minWeight = LocaleHelper.ConvertWeight(WeightUnit.Pounds, MinPackageWeight, pUnits.WeightUnit); if (EnablePackageBreakup && maxWeight > 0) { //compose packages (splits items larger than the maximum carrier weight) plist.Compose(maxWeight, minWeight); } else { plist.EnsureMinimumWeight(minWeight); } //convert weights to whole numbers plist.ConvertWeightToWholeNumber(); return(plist); }
private void UpdateNextOrderNumber(Store store) { OrigNextOrderNumber.Value = store.NextOrderId.ToString(); NextOrderNumberRangeValidator1.MinimumValue = (StoreDataSource.GetMaxOrderNumber() + 1).ToString(); NextOrderNumberRangeValidator1.ErrorMessage = string.Format(NextOrderNumberRangeValidator1.ErrorMessage, NextOrderNumberRangeValidator1.MinimumValue); NextOrderId.Text = OrigNextOrderNumber.Value; if (store.NextOrderId > 99999999) { NextOrderIdLabel.Text = OrigNextOrderNumber.Value; NextOrderIdLabel.Visible = true; NextOrderId.Visible = false; NextOrderNumberRangeValidator1.Enabled = false; NextOrderNumberRangeValidator1.Visible = false; } }
/// <summary> /// Upload compressed feed /// </summary> /// <param name="options">Feed configuration options</param> /// <returns>true if feed upload is successful, false otherwise</returns> public bool UploadCompressedFeed(FeedOptions options) { bool needTokenReset = false; if (Token.Instance.Store == null) { Store store = StoreDataSource.Load(options.StoreId); Token.Instance.InitStoreContext(store); needTokenReset = true; } string compressedFile = Path.Combine(options.FeedDataPath, options.CompressedFeedFileName); if (!File.Exists(compressedFile)) { UpdateStatus(100, "Can not upload. Compressed feed file does not exist. Please create the compressed feed file first.", false); return(false); } try { string remoteFileName = options.RemoteFileName; if (string.IsNullOrEmpty(remoteFileName)) { remoteFileName = options.CompressedFeedFileName; } UploadFile(options, compressedFile, options.CompressedFeedFileName); } catch (Exception e) { UpdateStatus(100, "An error occured while uploading: " + e.Message, false); Utility.Logger.Warn("FTP upload of " + options.CompressedFeedFileName + " could not be completed.", e); if (needTokenReset) { Token.ResetInstance(); } return(false); } if (needTokenReset) { Token.ResetInstance(); } UpdateStatus(100, "Compressed Feed File Uploaded.", true); return(true); }
/// <summary> /// Upload un-compressed feed /// </summary> /// <param name="options">Feed configuration options</param> /// <returns>true if feed upload is successful, false otherwise</returns> public bool UploadUncompressedFeed(FeedOptions options) { // NEED TO INITIALIZE STORE CONTEXT ( AS THIS CAN BE CALLED IN ASYN WAY AS WELL), IN CASE AN ERROR OCCURS THEN WE NEED TO LOG FOR STORE bool needTokenReset = false; if (Token.Instance.Store == null) { Store store = StoreDataSource.Load(options.StoreId); Token.Instance.InitStoreContext(store); needTokenReset = true; } string feedFile = Path.Combine(options.FeedDataPath, options.FeedFileName); if (!File.Exists(feedFile)) { UpdateStatus(100, "Can not upload. Feed file does not exist. Please Create the Feed file first.", false); return(false); } try { string remoteFileName = options.RemoteFileName; if (string.IsNullOrEmpty(remoteFileName)) { remoteFileName = options.FeedFileName; } UploadFile(options, feedFile, remoteFileName); } catch (Exception e) { UpdateStatus(100, "An error occured while uploading: " + e.Message, false); Utility.Logger.Warn("FTP upload of " + options.FeedFileName + " could not be completed.", e); if (needTokenReset) { Token.ResetInstance(); } return(false); } if (needTokenReset) { Token.ResetInstance(); } UpdateStatus(100, "Uncompressed Feed File Uploaded.", true); return(true); }
/// <summary> /// This creates the base order object / record without child data /// </summary> /// <param name="basket">The basket to generate an order record for.</param> /// <returns>The order generated from the basket</returns> /// <remarks>This is the first stage of the checkout sequence, following order /// generation all child data must be recorded. This method makes no alteration /// to the basket object.</remarks> internal static Order GenerateOrderObject(Basket basket) { //CREATE THE ORDER RECORD Order order = new Order(); order.OrderNumber = StoreDataSource.GetNextOrderNumber(true); order.OrderStatusId = OrderStatusDataSource.GetNewOrderStatus().OrderStatusId; order.OrderDate = LocaleHelper.LocalNow; //SET USER DATA order.UserId = basket.UserId; //CHECK USER AFFILIATE User user = basket.User; Affiliate affiliate = user.Affiliate; if (affiliate != null) { //IF AFFILIATE IS NOT NULL IT MEANS THAT ITS ALREADY VALIDATED BY User.ValidateAffiliate METHOD SO ASSING IT TO THE ORDER order.AffiliateId = affiliate.AffiliateId; } //SET BILLING ADDRESS CheckoutHelper.RecordBillingAddress(user, order); //SET VALUES FROM HTTPCONTEXT HttpContext context = HttpContext.Current; if (context != null) { if (context.Session != null) { string url = (string)context.Session["SessionReferrerUrl"]; if (!string.IsNullOrEmpty(url)) { order.Referrer = StringHelper.Truncate(url, 255); } } order.RemoteIP = StringHelper.Truncate(context.Request.UserHostAddress, 39); } //SAVE THE ORDER order.Save(false); return(order); }
protected void Page_PreRender(object sender, EventArgs e) { int maxOrderId = StoreDataSource.GetMaxOrderNumber(); int nextOrderId = StoreDataSource.GetNextOrderNumber(false); if (maxOrderId >= nextOrderId) { NextOrderNumberWarning.Text = string.Format(NextOrderNumberWarning.Text, nextOrderId, maxOrderId, (maxOrderId + 1)); } else { NextOrderNumberWarning.Visible = false; } // disable the selection of groups if store access is not restricted AuthorizedGroups.Attributes.Remove("disabled"); AccessRestrictionType selectedVal = (AccessRestrictionType)Enum.Parse(typeof(AccessRestrictionType), RestrictStoreAccessOptions.SelectedValue); if (selectedVal != AccessRestrictionType.AuthorizedGroupsOnly) { AuthorizedGroups.Attributes.Add("disabled", "true"); } }
/// <summary> /// Create a feed /// </summary> /// <param name="options">Feed configuration options</param> /// <returns>true if feed creation is successful, false otherwise</returns> public bool CreateFeed(FeedOptions options) { string feedFile = Path.Combine(options.FeedDataPath, options.FeedFileName); if (File.Exists(feedFile) && !options.OverwriteFeedFile) { UpdateStatus(100, "Feed File Already Exists. You should either chose to overwrite the feed file or provide a different name.", false); return(false); } string criteria = "VisibilityId<>" + (short)CatalogVisibility.Private; if (!options.IncludeAllProducts) { criteria = criteria + " AND ExcludeFromFeed=0"; } string headerRow = GetHeaderRow(); if (!headerRow.EndsWith("\r\n")) { headerRow += "\r\n"; } try { using (StreamWriter feedWriter = File.CreateText(feedFile)) { feedWriter.Write(headerRow); feedWriter.Close(); } } catch (System.UnauthorizedAccessException accessException) { UpdateStatus(100, "Access restricted on feed data folder. In order to create feeds, the current user (" + Misc.GetProcessIdentity() + ") needs write access to feeds data folder.", false); UpdateStatus(100, "Access exception : " + accessException.Message, false); return(false); } bool needTokenReset = false; if (Token.Instance.Store == null) { Store store = StoreDataSource.Load(options.StoreId); Token.Instance.InitStoreContext(store); needTokenReset = true; } try { using (StreamWriter feedWriter = File.AppendText(feedFile)) { ProductCollection products; int count = ProductDataSource.CountForCriteria(criteria); int startIndex = 0; while (startIndex < count) { // DETERMINE HOW MANY ROWS LEFT TO INCLUDE IN FEED int rowsRemaining = count - startIndex; // ONLY PROCESS 1000 ROWS AT A TIME int maxRows = (rowsRemaining > 1000) ? 1000 : rowsRemaining; // CALCULATE PROGRESS PERCENTAGE AND DISPLAY PROGRESS int percentDone = startIndex / count * 100; UpdateStatus(percentDone, "Generating feed for products from " + startIndex + " to " + (startIndex + maxRows) + " out of " + count + " products."); // GET THE ROWS TO BE OUTPUT products = ProductDataSource.LoadForCriteria(criteria, maxRows, startIndex); // GENERATE THE FEED DATA string feedData = GetFeedData(products); // WRITE DATA TO THE FEED FILE if (!feedData.EndsWith("\r\n")) { feedData += "\r\n"; } feedWriter.Write(feedData); feedWriter.Flush(); // LOOP TO THE NEXT BLOCK OF DATA startIndex += 1000; } // CLOSE THE FEED FILE feedWriter.Close(); } } catch (Exception e) { Logger.Warn("Error Feed Creator Thread : " + e.Message, e); UpdateStatus(100, "Error while creating feed file." + e.Message, false); return(false); } finally { if (needTokenReset) { Token.ResetInstance(); } } UpdateStatus(100, string.Format("Feed file generated at {0}.", options.FeedDataPath), true); return(true); }
protected void Page_PreRender(object sender, EventArgs e) { List <string> alertList; DateTime cacheDate; CacheWrapper alertWrapper = Cache.Get("AdminAlerts") as CacheWrapper; if (alertWrapper == null) { alertList = new List <string>(); //Check if installation directory still exists if (System.IO.Directory.Exists(Request.MapPath("~/Install"))) { string alertText = "The 'Install' directory still exists in your store. It should be removed immediately after the Installation is complete."; alertList.Add(alertText); } // CHECK IF EMAIL TEMPLATES ARE CONFIGURED, WITHOUT EMAIL SERVER SETTINGS Store store = AbleContext.Current.Store; if ((store.EmailTemplates.Count > 0)) { if (string.IsNullOrEmpty(store.Settings.SmtpServer)) { string alertText = "You have email templates configured, but you have not provided an SMTP (mail) server. Without a serv" + "er, email notifications cannot be sent. <a href=\'Store/EmailTemplates/Settings.aspx\'>Click here</a> to configure " + "email now."; alertList.Add(alertText); } } //VALIDATE ORDER STATUSES //CHECK FOR A STATUS ATTACHED TO THE ORDER PLACED EVENT OrderStatus status = OrderStatusTriggerDataSource.LoadForStoreEvent(StoreEvent.OrderPlaced); if (status == null) { status = new OrderStatus(); status.Name = "Payment Pending"; status.DisplayName = "Payment Pending"; status.IsActive = false; status.IsValid = true; status.Triggers.Add(new OrderStatusTrigger(StoreEvent.OrderPlaced, status)); status.Save(); alertList.Add("You did not have an order status assigned to the 'Order Placed' event, so one was created for you. <a href=\"Store/OrderStatuses/Default.aspx\">Click here</a> to check the order status configuration for your store."); } //CHECK FOR A STATUS ATTACHED TO THE ORDER CANCELLED EVENT status = OrderStatusTriggerDataSource.LoadForStoreEvent(StoreEvent.OrderCancelled); if (status == null) { status = new OrderStatus(); status.Name = "Cancelled"; status.DisplayName = "Cancelled"; status.IsActive = false; status.IsValid = false; status.Triggers.Add(new OrderStatusTrigger(StoreEvent.OrderCancelled, status)); status.Save(); alertList.Add("You did not have an order status assigned to the 'Order Cancelled' event, so one was created for you. <a href=\"Store/OrderStatuses/Default.aspx\">Click here</a> to check the order status configuration for your store."); } //MAKE SURE AT LEAST ONE PRODUCT EXISTS int productCount = ProductDataSource.CountAll(); if (productCount == 0) { alertList.Add("You have not yet added any products in your store. <a href=\"Catalog/Browse.aspx\">Click here</a> to manage your catalog now."); } //MAKE SURE AT LEAST ONE SHIPPING METHOD EXISTS int shipMethodCount = ShipMethodDataSource.CountAll(); if (shipMethodCount == 0) { alertList.Add("You do not have any shipping methods configured. Your customers will not be able to complete checkout if the order contains any shippable products. <a href=\"Shipping/Methods/Default.aspx\">Click here</a> to manage shipping methods now."); } //CHECK FOR LOW INVENTORY PRODUCTS int lowInventoryProducts = ProductInventoryDataSource.GetLowProductInventoryCount(); if (lowInventoryProducts > 0) { alertList.Add("One or more products are at or below their low inventory warning level. You can view these products <a href=\"Reports/LowInventory.aspx\">here</a>."); } //CHECK FOR PRESENCE OF ERRORS int errorCount = ErrorMessageDataSource.CountAll(); if (errorCount > 0) { string errorAlert = string.Format("There are {0} messages in your <a href=\"Help/ErrorLog.aspx\">error log</a>. You should review these messages and take corrective action if necessary.", errorCount); alertList.Add(errorAlert); } //Check of SSL is not enabled StoreSettingsManager storeSettings = AbleContext.Current.Store.Settings; if (!storeSettings.SSLEnabled) { string alertText = "SSL is not enabled. Your store is currently being accessed over an insecure connection. <a href=\"Store/Security/Default.aspx\">Click Here</a> to change SSL settings."; alertList.Add(alertText); } //MAKE SURE ORDER NUMBER INCREMENT IS VALID if (store.OrderIdIncrement < 1) { string alertText = "The order number increment for your store was " + store.OrderIdIncrement + " (invalid). The increment has been updated to 1. <a href=\"Store/StoreSettings.aspx\">Click Here</a> to review this setting."; alertList.Add(alertText); store.OrderIdIncrement = 1; store.Save(); } //ALERT FOR ORDER NUMBER PROBLEM int maxOrderNumber = StoreDataSource.GetMaxOrderNumber(); int nextOrderNumber = StoreDataSource.GetNextOrderNumber(false); if (maxOrderNumber >= nextOrderNumber) { int newOrderNumber = maxOrderNumber + store.OrderIdIncrement; StoreDataSource.SetNextOrderNumber(newOrderNumber); string alertText = "The next order number of {0} is less than the highest assigned order number of {1}. We have automatically increased your next order number to {2} to prevent errors. <a href=\"Store/StoreSettings.aspx\">Click Here</a> to review this setting."; alertList.Add(string.Format(alertText, nextOrderNumber, maxOrderNumber, newOrderNumber)); } //MAKE SURE A VALID ENCRYPTION KEY IS PRESENT bool encryptionKeyValid; try { encryptionKeyValid = EncryptionKeyManager.IsKeyValid(EncryptionKeyManager.Instance.CurrentKey.KeyData); } catch { encryptionKeyValid = false; } if (!encryptionKeyValid) { //ENCRYPTION KEY IS MISSING OR INVALID, SEE WHETHER WE ARE STORING CARD DATA if (storeSettings.EnableCreditCardStorage) { string alertText = "Your store encryption key is missing or invalid, and you have not disabled storage of card data. You should either <a href=\"Store/Security/EncryptionKey.aspx\">set the encryption key</a> or <a href=\"Store/Security/Default.aspx\">disable credit card storage</a>."; alertList.Add(alertText); } } // ALERT FOR PRODUCT IMAGE LOOKUP BY SKU if (storeSettings.ImageSkuLookupEnabled) { // SEARCH FOR PRODUCTS MISSING SKU AND MISSING IMAGE URLs ICriteria productCriteria = NHibernateHelper.CreateCriteria <Product>() .Add(new Disjunction() .Add(Restrictions.IsNull("Sku")) .Add(Restrictions.Eq("Sku", string.Empty))) .Add(new Disjunction() .Add(Restrictions.IsNull("ImageUrl")) .Add(Restrictions.IsNull("IconUrl")) .Add(Restrictions.IsNull("ThumbnailUrl"))) .Add(Restrictions.Eq("VisibilityId", (byte)CatalogVisibility.Public)); IList <Product> products = ProductDataSource.LoadForCriteria(productCriteria); if (products != null && products.Count > 0) { StringBuilder textBuilder = new StringBuilder(); textBuilder.Append("Following product(s) are missing SKU, and also do not have image paths provided:<br/>"); textBuilder.Append("<ul>"); int counter = 0; // PRODUCT COUNTER, SHOW ONLY FIRST FIVE PRODUCTS foreach (Product product in products) { counter++; textBuilder.Append("<li><a href=\"products/EditProduct.aspx?ProductId=" + product.Id + "\">" + product.Name + "</a>.</li>"); if (counter >= 5) { break; } } textBuilder.Append("<ul>"); alertList.Add(textBuilder.ToString()); } } // LOOK FOR UNREAD NOTES ICriteria orderNoteCriteria = NHibernateHelper.CreateCriteria <OrderNote>() .Add(Restrictions.Eq("IsRead", false)) .Add(Restrictions.Not(Restrictions.Eq("NoteTypeId", (byte)NoteType.SystemPublic))) .Add(Restrictions.Not(Restrictions.Eq("NoteTypeId", (byte)NoteType.SystemPrivate))); int unreadNoteCount = OrderNoteDataSource.CountForCriteria(orderNoteCriteria); if (unreadNoteCount > 0) { string alertText = "There are {0} unread order note(s). <a href=\"Orders/OrderNotesManager.aspx\">review now</a>"; alertList.Add(string.Format(alertText, unreadNoteCount)); } // CHECK ANON USER MAINTENANCE SETTINGS if (store.Settings.AnonymousUserLifespan < 1 || store.Settings.AnonymousAffiliateUserLifespan < 1) { alertList.Add("You have not configured the number of days to save anonymous user records. You should visit the <a href=\"Store/Maintenance.aspx\">Configure > Maintenance</a> menu, view the status of the anonymous user database, and update your anonymous user maintenance settings."); } // ALERT FOR DUPLICATE COUPON CODES IList <Coupon> duplicateCoupons = NHibernateHelper.CreateSQLQuery("SELECT * FROM ac_Coupons WHERE CouponCode IN (SELECT LOWER(CouponCode) FROM ac_Coupons GROUP BY CouponCode HAVING COUNT(*) > 1)").AddEntity(typeof(Coupon)).List <Coupon>(); if (duplicateCoupons.Count > 0) { Dictionary <string, List <Coupon> > codeCounts = new Dictionary <string, List <Coupon> >(); foreach (Coupon coupon in duplicateCoupons) { string normalizedKey = coupon.CouponCode.ToUpperInvariant(); if (!codeCounts.ContainsKey(normalizedKey)) { codeCounts[normalizedKey] = new List <Coupon>(); } codeCounts[normalizedKey].Add(coupon); } StringBuilder alertText = new StringBuilder(); alertText.Append("<p>You have coupons that have duplicate codes. Duplicates should be eliminated as a unique constraint will be applied in a future release:</p>"); foreach (string couponCode in codeCounts.Keys) { alertText.Append("<p><b>" + couponCode + ":</b> "); string delimiter = string.Empty; foreach (Coupon coupon in codeCounts[couponCode]) { alertText.Append(delimiter); alertText.Append("<a href=\"Marketing/Coupons/EditCoupon.aspx?CouponId=" + coupon.Id + "\">" + coupon.Name + "</a>"); delimiter = ", "; } alertText.Append("</p>"); } alertList.Add(alertText.ToString()); } //UPDATE CACHE alertWrapper = new CacheWrapper(alertList); Cache.Remove("AdminAlerts"); Cache.Add("AdminAlerts", alertWrapper, null, DateTime.UtcNow.AddMinutes(15), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } else { alertList = (List <string>)alertWrapper.CacheValue; } cacheDate = alertWrapper.CacheDate; if (alertList.Count == 0) { alertList.Add("no action items available"); } AlertList.DataSource = alertList; AlertList.DataBind(); CachedAt.Text = string.Format("{0:g}", cacheDate); }
private void SaveSettings() { Store store = AbleContext.Current.Store; StoreSettingsManager settings = store.Settings; store.Name = StoreName.Text; store.VolumeDiscountMode = (VolumeDiscountMode)DiscountMode.SelectedIndex; store.WeightUnit = (WeightUnit)AlwaysConvert.ToInt(WeightUnit.SelectedValue); store.MeasurementUnit = (MeasurementUnit)AlwaysConvert.ToInt(MeasurementUnit.SelectedValue); settings.TimeZoneCode = TimeZoneOffset.SelectedValue; settings.TimeZoneOffset = GetTimeZoneOffset(TimeZoneOffset.SelectedValue); settings.PostalCodeCountries = PostalCodeCountries.Text.Replace(" ", string.Empty); settings.SiteDisclaimerMessage = SiteDisclaimerMessage.Text.Trim(); // INVENTORY store.Settings.EnableInventory = EnableInventory.Checked; settings.InventoryDisplayDetails = CurrentInventoryDisplayMode.SelectedIndex == 1; settings.InventoryInStockMessage = InStockMessage.Text; settings.InventoryOutOfStockMessage = OutOfStockMessage.Text; settings.InventoryAvailabilityMessage = InventoryAvailabilityMessage.Text; settings.InventoryRestockNotificationLink = RestockNotificationLink.Text; settings.InventoryRestockNotificationEmailTemplateId = AlwaysConvert.ToInt(RestockNotificationEmail.SelectedValue); // ORDERS short increment = AlwaysConvert.ToInt16(OrderIdIncrement.Text); if (increment >= 1) { store.OrderIdIncrement = increment; } settings.CheckoutTermsAndConditions = CheckoutTerms.Text.Trim(); settings.OrderMinimumAmount = AlwaysConvert.ToDecimal(OrderMinAmount.Text); settings.OrderMaximumAmount = AlwaysConvert.ToDecimal(OrderMaxAmount.Text); settings.AcceptOrdersWithInvalidPayment = IgnoreFailedPayments.Checked; settings.EnablePartialPaymentCheckouts = AllowPartialPaymnets.Checked; settings.EnableOnePageCheckout = EnableOnePageCheckout.Checked; settings.AllowAnonymousCheckout = AllowGuestCheckout.Checked || LimitedGuestCheckout.Checked; settings.AllowAnonymousCheckoutForDigitalGoods = !LimitedGuestCheckout.Checked; settings.EnableCustomerOrderNotes = EnableOrderNotes.Checked; settings.EnableShipMessage = EnableShipMessage.Checked; settings.EnableShipToMultipleAddresses = EnableShipToMultipleAddresses.Checked; // PRODUCTS PURCHASING settings.ProductPurchasingDisabled = ProductPurchasingDisabled.Checked; // WISHLISTS ENABLED settings.WishlistsEnabled = WishlistsEnabled.Checked; // RESTRICT STORE ACCESS settings.RestrictStoreAccess = (AccessRestrictionType)Enum.Parse(typeof(AccessRestrictionType), RestrictStoreAccessOptions.SelectedValue); if (settings.RestrictStoreAccess == AccessRestrictionType.AuthorizedGroupsOnly) { IList <Group> allGroups = GroupDataSource.LoadForStore(AbleContext.Current.StoreId, "Name ASC"); IList <Group> nonAdminGroups = allGroups.FindAll(grp => !grp.IsInRole(Role.AllAdminRoles)) as IList <Group>; // remove permissions for all non-admin groups Role authorizedUserRole = RoleDataSource.LoadForRolename(Role.CustomerRoles[0]); foreach (Group group in nonAdminGroups) { group.Roles.Remove(authorizedUserRole); } foreach (ListItem item in AuthorizedGroups.Items) { if (item.Selected) { int groupId = AlwaysConvert.ToInt(item.Value); foreach (Group group in nonAdminGroups) { // add permissions for selected groups if (groupId == group.Id) { group.Roles.Add(authorizedUserRole); } } } } nonAdminGroups.Save(); } // SEARCH SETTINGS settings.WishlistSearchEnabled = EnableWishlistSearch.Checked; settings.MinimumSearchLength = AlwaysConvert.ToInt(MinimumSearchLength.Text); settings.PopularSearchThreshold = AlwaysConvert.ToInt(PopularSearchThreshold.Text); settings.CategorySearchDisplayLimit = AlwaysConvert.ToInt(CategorySearchDisplayLimit.Text); settings.EnablePaymentProfilesStorage = PaymentStorage.Checked; // HTML EDITOR SETTING settings.EnableWysiwygEditor = EnableHtmlEditor.Checked; store.Save(); // CHECK NEXT ORDER NUMBER if (OrigNextOrderNumber.Value != NextOrderId.Text) { // NEXT ORDER NUMBER WAS UPDATED store.NextOrderId = StoreDataSource.SetNextOrderNumber(AlwaysConvert.ToInt(NextOrderId.Text)); OrigNextOrderNumber.Value = store.NextOrderId.ToString(); } else { // DETERMINE CORRECT VALUE FOR NEXT ORDER NUMBER OrigNextOrderNumber.Value = StoreDataSource.GetNextOrderNumber(false).ToString(); } OrderIdIncrement.Text = store.OrderIdIncrement.ToString(); UpdateNextOrderNumber(store); store.Save(); if (SearchProvider.SelectedValue != ApplicationSettings.Instance.SearchProvider) { ApplicationSettings.Instance.SearchProvider = SearchProvider.SelectedValue; ApplicationSettings.Instance.Save(); if (SearchProvider.SelectedValue == "SqlFtsSearchProvider") { bool fullTextSearch = false; // FTS IS TURNED ON, MAKE SURE THE CATALOG IS AVAILABLE if (KeywordSearchHelper.EnsureCatalog()) { // CATALOG IS FOUND, MAKE SURE INDEXES ARE AVAILABLE if (KeywordSearchHelper.EnsureIndexes()) { // FTS CAN BE SAFELY ENABLED fullTextSearch = true; } } if (!fullTextSearch) { KeywordSearchHelper.RemoveCatalog(); } } if (SearchProvider.SelectedValue == "LuceneSearchProvider") { AbleContext.Resolve <IFullTextSearchService>().AsyncReindex(); } } }