private void AddEventToCart(Event currentEvent) { CatalogManager catalog = new CatalogManager(); Product product = catalog.GetProduct(ProductId); HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("shoppingCartId"); OrdersManager orderm = new OrdersManager(); OptionsDetails optionDetails = new OptionsDetails(); // Check if shopping cart cookie exists in the current request. if (cookie == null) //if it does not exist... { CartOrder cartItem = orderm.CreateCartOrder(); //create a new cart order var shoppingcartid = cartItem.Id; // that id is equal to the cookie value HttpCookie Cookie = new HttpCookie("shoppingCartId"); //create a new shopping cart cookie DateTime now = DateTime.Now; // Set the cookie value. Cookie.Value = shoppingcartid.ToString(); // Set the cookie expiration date. Cookie.Expires = now.AddYears(1); // Add the cookie. HttpContext.Current.Response.Cookies.Add(Cookie); //give cart item currency of USD because it cannot be null cartItem.Currency = "USD"; //add the product to the cart orderm.AddToCart(cartItem, product, optionDetails, 1); //save all changes orderm.SaveChanges(); } else //if the cookie does exist { Guid guid = new Guid(cookie.Value.ToString()); //get the cookie value as the guid CartOrder cartItem = orderm.GetCartOrder(guid); //get the cart based on the cookie value orderm.AddToCart(cartItem, product, optionDetails, 1); // add the item to the cart orderm.SaveChanges(); //save changes } }
private void ShoppingCartGrid_RentalsItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e) { if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem) { var cartDetail = (CartDetail)e.Item.DataItem; RadDatePicker startDatePicker = (RadDatePicker)e.Item.FindControl("startDatePicker"); RadDatePicker endDatePicker = (RadDatePicker)e.Item.FindControl("endDatePicker"); //Hide the date pickers if it's not a notebook ProductType notebook = CatalogManager.GetProductTypes().Where(pt => pt.Title == "Notebook").SingleOrDefault(); Product product = CatalogManager.GetProduct(cartDetail.ProductId); if (product.ClrType != notebook.ClrType) { startDatePicker.Visible = false; endDatePicker.Visible = false; } else { DateTime startDate; DateTime endDate; if (DateTime.TryParse(DataExtensions.GetValue <string>(cartDetail, "startDate"), out startDate)) { startDatePicker.SelectedDate = startDate; } if (DateTime.TryParse(DataExtensions.GetValue <string>(cartDetail, "endDate"), out endDate)) { endDatePicker.SelectedDate = startDate; } } } }
/// <inheritdoc/> protected override ExitCode ExecuteHelper() { try { var appEntry = GetAppEntry(IntegrationManager, ref InterfaceUri); if (AdditionalArgs.Count == 2) { CreateAlias(appEntry, AdditionalArgs[0], _command); } else if (_command != null) { throw new OptionException(string.Format(Resources.NoAddCommandWithoutAlias, "--command"), "command"); } if (WindowsUtils.IsWindows && !CatalogManager.GetCachedSafe().ContainsFeed(appEntry.InterfaceUri)) { WindowsUtils.BroadcastMessage(AddedNonCatalogAppWindowMessageID); // Notify Zero Install GUIs of changes } return(ExitCode.OK); } #region Error handling catch (InvalidOperationException ex) // WebException is a subclass of InvalidOperationException but we don't want to catch it here when(ex is not WebException) { // Application already in AppList Handler.OutputLow(Resources.DesktopIntegration, ex.Message); return(ExitCode.NoChanges); } #endregion }
/// <inheritdoc/> protected override ExitCode ExecuteHelper(ICategoryIntegrationManager integrationManager, FeedUri interfaceUri) { #region Sanity checks if (integrationManager == null) { throw new ArgumentNullException(nameof(integrationManager)); } if (interfaceUri == null) { throw new ArgumentNullException(nameof(interfaceUri)); } #endregion try { var entry = CreateAppEntry(integrationManager, ref interfaceUri); if (!CatalogManager.GetCachedSafe().ContainsFeed(entry.InterfaceUri)) { WindowsUtils.BroadcastMessage(AddedNonCatalogAppWindowMessageID); // Notify Zero Install GUIs of changes } return(ExitCode.OK); } #region Error handling catch (InvalidOperationException ex) // WebException is a subclass of InvalidOperationException but we don't want to catch it here when(!(ex is WebException)) { // Application already in AppList Handler.OutputLow(Resources.DesktopIntegration, ex.Message); return(ExitCode.NoChanges); } #endregion }
static void Main(string[] args) { try { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Console.Title = Constants.ConsoleTitle; Console.CursorVisible = false; Console.SetWindowSize(Constants.ConsoleWidowsWidth, Constants.ConsoleWindowHeight); DateTime Timer1 = DateTime.Now; Output.WriteHeader(); ConfigurationManager.Initialize(); DatabaseManager.Initialize(); SpacesManager.Initialize(); CatalogManager.Initialize(); ChestManager.Initialize(); SessionsManager.Initialize(); SocketManager.Initialize(); Input.Initialize(); using (DatabaseClient client = DatabaseManager.GetClient()) { client.ExecuteScalar("UPDATE boombang_statics SET Clients=0 WHERE ID = 1"); } Output.WriteLine("Server started seddefully (" + new TimeSpan(DateTime.Now.Ticks + Timer1.Ticks).TotalSeconds + " seconds)! Press the enter key to execute a command."); } catch (Exception ex) { Output.WriteLine("Can't initialize the server. Exception: " + ex.ToString(), OutputLevel.CriticalError); Console.ReadKey(); } }
public GameContext() { HabboEncryptionV2.Initialize(new RSAKeys()); _moderationManager = new ModerationManager(); _itemDataManager = new ItemDataManager(); _catalogManager = new CatalogManager(_itemDataManager); _navigatorManager = new NavigatorManager(); _roomManager = new RoomManager(); _chatManager = new ChatManager(); _groupManager = new GroupManager(); _questManager = new QuestManager(); _achievementManager = new AchievementManager(); _talentTrackManager = new TalentTrackManager(); _hotelViewManager = new HotelViewManager(); _gameDataManager = new GameDataManager(); _botManager = new BotManager(); _cacheManager = new CacheManager(); _rewardManager = new RewardManager(); _badgeManager = new BadgeManager(); _permissionManager = new PermissionManager(); _subscriptionManager = new SubscriptionManager(); _gameCycle = new Task(GameCycle); _gameCycle.Start(); _cycleActive = true; }
private Item GetCatalogItem(ICatalogItemContext data, Database database) { var id = GetCatalogItemFromCache(data.Id, data.Catalog); if (!ID.IsNullOrEmpty(id)) { return(id == ID.Undefined ? null : database.GetItem(id)); } Item item = null; switch (data.ItemType) { case CatalogItemType.Product: item = CatalogManager.GetProduct(data.Id, data.Catalog); break; case CatalogItemType.Category: item = CatalogManager.GetCategoryItem(data.Id, data.Catalog); break; } if (item != null) { AddCatalogItemToCache(data.Id, data.Catalog, item); } return(item); }
public void ShouldAddProductToTheAcquirerCatalog() { string sku = "999-vyk-317", description = "Cheese cake"; _tenantRepositoryMock.Setup(m => m.Acquirer).Returns(new Tenant(Constants.Configuration.Acquirer, Constants.Configuration.Acquirer, new TenantConfig("p", "s", "ps"))); _tenantRepositoryMock.Setup(m => m.Acquiree).Returns(new Tenant(Constants.Configuration.Acquiree, Constants.Configuration.Acquiree, new TenantConfig("p", "s", "ps"))); _productRepositoryMock.Setup(m => m.GetBySku(Constants.Configuration.Acquirer, "999-vyk-317")) .Returns(new Product(sku, description)); _inventoryManager = new InventoryManager(_productRepositoryMock.Object, _supplierRepositoryMock.Object, _supplierProductBarcodeRepositoryMock.Object, _tenantRepositoryMock.Object); var catalogManager = new CatalogManager(_inventoryManager, _tenantRepositoryMock.Object, _reportGeneratorMock.Object); catalogManager.AddProduct(sku, description); var product = _inventoryManager.GetProductBySku(Constants.Configuration.Acquirer, sku); Assert.AreEqual(product.Sku, sku); Assert.AreEqual(product.Description, description); }
/// <summary> /// Determines should the data event be processed. There are two /// conditions that an event must meet in order to be processed: /// * The ItemType for which event was raised must be of type /// <see cref="Product"/> or one of its derivatives /// * The Item being processed should be the live version of the product. /// As Sitefinity supports life-cycle of data items, several versions, /// such as draft, live, master, temp... may be created. We want to /// create items only once, however. /// * The ProviderName from which event was fired should be the default /// provider of the catalog module, which we are using as the master /// catalog. Changes on the regional providers should be isolated /// and hence we are not interested in them /// * The action for which event was fired must be Created or Deleted /// as we are not interested in updates or custom actions /// </summary> /// <param name="evt"> /// The instance of the <see cref="IDataEvent"/> type which represents /// the event to be examined. /// </param> /// <returns> /// True if all conditions were met and event should be processed; otherwise /// false. /// </returns> private bool ShouldProcess(IDataEvent evt) { if (!typeof(Product).IsAssignableFrom(evt.ItemType)) { return(false); } var lifecycleEvt = evt as ILifecycleEvent; if (lifecycleEvt != null && lifecycleEvt.Status != ContentLifecycleStatus.Live.ToString()) { return(false); } if (evt.ProviderName != CatalogManager.GetDefaultProviderName()) { return(false); } if (!(evt.Action == DataEventAction.Created || evt.Action == DataEventAction.Deleted)) { return(false); } return(true); }
/// <summary> /// Constructor. /// </summary> /// <param name="sfContent">The sf product variation.</param> public ProductVariationModel(ProductVariation sfContent) { if (sfContent != null) { Id = sfContent.Id; Sku = sfContent.Sku; AdditionalPrice = sfContent.AdditionalPrice; LastModified = sfContent.LastModified; Active = sfContent.IsActive; //GET ATTRIBUTE DETAILS if (!string.IsNullOrWhiteSpace(sfContent.Variant)) { // Variant is stored as an array of an object. Get array, select first (only) object, then pull property from that object. JToken variantData = JArray.Parse(sfContent.Variant).First; Guid attributeId = new Guid(variantData["AttributeValueId"].Value <string>()); //GET ATTRIBUTE VALUE FOR VARIANT var manager = CatalogManager.GetManager(); var attribute = manager.GetProductAttributeValue(attributeId); //STORE PROPERTY VALUES TO MODEL Title = attribute.Title; Description = attribute.Description; Ordinal = attribute.Ordinal; Visible = attribute.Visible; ParentId = attribute.Parent.Id; ParentTitle = attribute.Parent.Title; } // Store original content OriginalContent = sfContent; } }
/// <summary> /// Sends an email for each product in the given <paramref name="order"/>. /// </summary> /// /// <param name="order">The order.</param> public static void NotificationHandler(Order order) { var catalogManager = CatalogManager.GetManager(); foreach (OrderDetail item in order.Details) { Product product = catalogManager.GetProduct(item.ProductId); if (product == null || !product.DoesFieldExist("ConfirmationEmail")) { continue; } var body = product.GetValue <string>("ConfirmationEmail"); if (string.IsNullOrWhiteSpace(body)) { continue; } var configManager = ConfigManager.GetManager(); var configSection = configManager.GetSection <EcommerceConfig>(); string fromEmail = configSection.MerchantEmail; string[] toEmail = { fromEmail, order.Customer.CustomerEmail }; var subject = GetSubject(order, product); body = ApplyValuesToBodyTemplate(body, order, product); MailHelper.SendEmail(fromEmail, toEmail, subject, body); } }
public Game() { _packetManager = new PacketManager(); _clientManager = new GameClientManager(); _moderationManager = new ModerationManager(); _moderationManager.Init(); _itemDataManager = new ItemDataManager(); _itemDataManager.Init(); _catalogManager = new CatalogManager(); _catalogManager.Init(_itemDataManager); _televisionManager = new TelevisionManager(); _navigatorManager = new NavigatorManager(); _roomManager = new RoomManager(); _chatManager = new ChatManager(); _groupManager = new GroupManager(); _groupManager.Init(); _questManager = new QuestManager(); _achievementManager = new AchievementManager(); _talentTrackManager = new TalentTrackManager(); _landingViewManager = new LandingViewManager(); _gameDataManager = new GameDataManager(); _globalUpdater = new ServerStatusUpdater(); _globalUpdater.Init(); _botManager = new BotManager(); _botManager.Init(); _cacheManager = new CacheManager(); _rewardManager = new RewardManager(); _badgeManager = new BadgeManager(); _badgeManager.Init(); _permissionManager = new PermissionManager(); _permissionManager.Init(); _subscriptionManager = new SubscriptionManager(); _subscriptionManager.Init(); }
public ActionResult VisitedCategoryPage() { if (CatalogManager.CatalogContext == null || StorefrontContext.Current == null) { return(this.InfoMessage(InfoMessage.Error("This rendering cannot be shown without a valid catalog context."))); } var lastCategoryId = GetLastVisitedCategory(CommerceUserContext.Current.UserId); var currentCategory = GetCurrentCategory(); if (currentCategory == null) { return(new EmptyResult()); } if (!string.IsNullOrWhiteSpace(lastCategoryId) && lastCategoryId.Equals(currentCategory.Name)) { return(new EmptyResult()); } CatalogManager.VisitedCategoryPage(currentCategory.Name, currentCategory.Title); SetLastVisitedCategory(CommerceUserContext.Current.UserId, currentCategory.Name); return(new EmptyResult()); }
private NavigationViewModel GetNavigationViewModel(Category category) { var cacheKey = CreateCacheKey("Navigation", category, null); var navigationViewModel = this.GetFromCache <NavigationViewModel>(cacheKey); if (navigationViewModel != null) { return(navigationViewModel); } navigationViewModel = new NavigationViewModel(GetCategoryViewModel(category)); var childCategories = GetChildCategories(category); navigationViewModel.ChildCategories.AddRange(childCategories.Select(i => GetCategoryViewModel(CatalogManager.GetCategory(i)))); if (CatalogItemContext.Current != null) { if (CatalogItemContext.IsCategory) { navigationViewModel.ActiveCategoryID = CatalogItemContext.Current?.Item?.ID; } else { var categoryItem = CatalogManager.GetCategory(CatalogItemContext.Current.CategoryId); navigationViewModel.ActiveCategoryID = categoryItem?.InnerItem.ID; } } return(this.AddToCache(cacheKey, navigationViewModel)); }
public JsonResult Evaluate(int Id) { CatalogManager mgr = new CatalogManager(); var ext = mgr.evaluate("", true); return(Json(new { count = ext.Count, List = ext }, JsonRequestBehavior.AllowGet)); }
public ActionResult Navigation() { if (CatalogManager.CatalogContext == null) { return(this.InfoMessage(InfoMessage.Error("This rendering cannot be shown without a valid catalog context."))); } var item = RenderingContext.Current.Rendering.Item; var dataSource = item.IsDerived(Foundation.Commerce.Templates.Commerce.NavigationItem.Id) ? item?.TargetItem(Foundation.Commerce.Templates.Commerce.NavigationItem.Fields.CategoryDatasource) : null; if (dataSource == null) { return(this.InfoMessage(InfoMessage.Error(AlertTexts.InvalidDataSourceTemplateFriendlyMessage))); } var currentCategory = CatalogManager.GetCategory(dataSource); if (currentCategory == null) { return(this.InfoMessage(InfoMessage.Error(AlertTexts.InvalidDataSourceTemplateFriendlyMessage))); } var viewModel = GetNavigationViewModel(currentCategory); return(View(viewModel)); }
public UnitOfWork(LocalDbEntities context) { _context = context; ProductManager = new ProductManager(context); CatalogManager = new CatalogManager(context); ProductCatalogManager = new ProductCatalogManager(context); }
public ActionResult Delete(int Id) { CatalogManager catManager = new CatalogManager(); catManager.DeleteCatalog(Id); return(RedirectToAction("Index")); }
/// <summary> /// Creates a product in all the regional providers based on the /// product in the master catalog as defined by the master id and /// master type parameters. /// </summary> /// <param name="masterId"> /// Id of the product in the master catalog that is to be replicated. /// </param> /// <param name="masterType"> /// The type of the product in the master catalog that is to be replicated. /// </param> private void CreateProductAccrossRegions(Guid masterId, Type masterType) { var transactionName = "CreateProductsRegional"; var regionalProviders = this.GetRegionalCatalogProviders(); var masterProduct = this.GetMasterProduct(masterId, masterType); foreach (var regionalProvider in regionalProviders) { var manager = CatalogManager.GetManager(regionalProvider, transactionName); // make sure the master item wasn't already synced for some reason if (manager.GetProducts(masterType.FullName).Any(p => p.GetValue <string>("MasterId") == masterId.ToString())) { continue; } var regionalItem = manager.CreateItem(masterType) as Product; // associate the product in the regional catalog with the one // in the master catalog regionalItem.SetValue("MasterId", masterId.ToString()); // copy logic; incomplete, modify as necessary regionalItem.Title = masterProduct.Title; regionalItem.Price = masterProduct.Price; regionalItem.Weight = masterProduct.Weight; regionalItem.UrlName = masterProduct.UrlName; // ensure the URLs of the new product are correctly set up manager.Provider.RecompileItemUrls(regionalItem); } TransactionManager.CommitTransaction(transactionName); }
// // GET: /Catalog/ public ActionResult Index() { CatalogManager catManager = new CatalogManager(); List <Catalog> catalogs = catManager.GetCatalogs(); return(View(catalogs)); }
public static void Main(string[] args) { bool_0 = true; DateTime now = DateTime.Now; Output.InitializeStream(true, OutputLevel.DebugInformation); Output.WriteLine("Initializing BoomBang game environment..."); ConfigManager.Initialize(Constants.DataFileDirectory + @"\server-main.cfg"); Output.SetVerbosityLevel((OutputLevel)ConfigManager.GetValue("output.verbositylevel")); foreach (string str in args) { Output.WriteLine("Command line argument: " + str); Input.ProcessInput(str.Split(new char[] { ' ' })); } try { Output.WriteLine("Initializing MySQL manager..."); SqlDatabaseManager.Initialize(); Output.WriteLine("Setting up server listener on port " + ((int)ConfigManager.GetValue("net.bind.port")) + "..."); boomBangTcpListener_0 = new BoomBangTcpListener(new IPEndPoint(IPAddress.Any, (int)ConfigManager.GetValue("net.bind.port")), (int)ConfigManager.GetValue("net.backlog"), new OnNewConnectionCallback(SessionManager.HandleIncomingConnection)); using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { Output.WriteLine("Resetting database counters and statistics..."); smethod_0(client); Output.WriteLine("Initializing game components and workers..."); DataRouter.Initialize(); GlobalHandler.Initialize(); SessionManager.Initialize(); CharacterInfoLoader.Initialize(); UserCredentialsAuthenticator.Initialize(); RegisterManager.Initialize(); Class1.smethod_0(); LaptopHandler.Initialize(); CatalogManager.Initialize(client); FlowerPowerManager.Initialize(); NewsCacheManager.Initialize(client); Navigator.Initialize(client); SpaceManager.Initialize(client); SpaceInfoLoader.Initialize(); SpaceHandler.Initialize(); GameHandler.Initialize(); CrossdomainPolicy.Initialize(@"Data\crossdomain.xml"); WordFilterManager.Initialize(client); AdvertisementManager.Initialize(); ContestHandler.Initialize(); SilverCoinsWorker.Initialize(); ModerationBanManager.Initialize(client); } } catch (Exception exception) { HandleFatalError("Could not initialize BoomBang game environment: " + exception.Message + "\nStack trace: " + exception.StackTrace); return; } TimeSpan span = (TimeSpan)(DateTime.Now - now); Output.WriteLine("The server has initialized successfully (" + Math.Round(span.TotalSeconds, 2) + " seconds). Ready for connections.", OutputLevel.Notification); Output.WriteLine("Pulsa ENTER e introduce un comando. Ten una guía de comandos escribiendo HELP", OutputLevel.Notification); Console.Beep(); }
public ActionResult Create() { var catalogManager = new CatalogManager(); ViewBag.AllCatalogs = catalogManager.GetAllCatalogs(); return(View()); }
public PriceGraphForm(Item item, Store store) { InitializeComponent(); _item = item; _store = store; _catalogManager = new CatalogManager(); }
public OrderViewModelRepository(CommerceUserContext commerceUserContext, OrderManager orderManager, StorefrontContext storefrontContext, CatalogManager catalogManager) { CommerceUserContext = commerceUserContext; OrderManager = orderManager; StorefrontContext = storefrontContext; CatalogManager = catalogManager; }
internal static void AssignCustomerToRoles(UserManager userManager, RoleManager roleManager, CatalogManager catalogManager, Guid userId, Order order) { using (new ElevatedModeRegion(roleManager)) { bool associationsFound = false; foreach (OrderDetail detail in order.Details) { var product = catalogManager.GetProduct(detail.ProductId); if (product.AssociateBuyerWithRole != Guid.Empty) { var user = userManager.GetUser(userId); try { var role = roleManager.GetRole(product.AssociateBuyerWithRole); roleManager.AddUserToRole(user, role); associationsFound = true; } catch (ItemNotFoundException) { // skip over the role if it no longer exists } } } if (associationsFound) { roleManager.SaveChanges(); } } }
/// <summary> /// Initializes a new instance of the <see cref="SearchController"/> class. /// </summary> /// <param name="catalogManager">The catalog manager.</param> /// <param name="contactFactory">The contact factory.</param> public SearchController([NotNull] CatalogManager catalogManager, [NotNull] ContactFactory contactFactory) : base(contactFactory) { Assert.ArgumentNotNull(catalogManager, "catalogManager"); Assert.ArgumentNotNull(contactFactory, "contactFactory"); this.CatalogManager = catalogManager; }
public async Task <JsonNetResult> AjaxFinish(int courseId) { var subscriptionChangeResult = await CatalogManager.SetFinishStateAsync(courseId, UserId); return(subscriptionChangeResult.Succeeded ? JsonNet(subscriptionChangeResult.Value) : JsonNetError(subscriptionChangeResult.Errors)); }
public async Task <ActionResult> Home() { var catalogStatistic = await CatalogManager.GetCatalogStatisticAsync(UserSpecializations); var viewModel = new VM.HomeViewModel(Url, catalogStatistic); return(View(viewModel)); }
public async Task <ActionResult> AjaxDelete(int courseId) { var result = await CatalogManager.DeleteCourseFromLearningPlanAsync(UserId, courseId); return(result.Succeeded ? (ActionResult) new HttpStatusCodeResult(HttpStatusCode.NoContent) : JsonNetError(result.Errors)); }
public ActionResult DeleteConfirmed(int id) { var catalogManager = new CatalogManager(); Catalog catalog = catalogManager.GetCatalogById(id); catalogManager.DeleteAndSave(catalog); return(RedirectToAction("Index")); }
/// <summary> /// Gets a list of all Ecommerce catalog providers except /// the default one, which we use as the master catalog /// provider. /// </summary> /// <returns> /// The list of strings representing the names of all the /// catalog providers, except the default one. /// </returns> private List <string> GetRegionalCatalogProviders() { return(Config.Get <CatalogConfig>() .Providers .Keys .Where(k => !k.Equals(CatalogManager.GetDefaultProviderName())) .ToList()); }
private static void ImportFiles(UploadConfig config, CatalogManager catalogManager, List<ImportError> importErrors, ref int numberOfFailedRecords, ProductImportModel productImportModel, ref bool isFailedSet, Product product) { try { List<ProductFile> productFiles = DocumentsAndFilesImporter.ImportDocumentsAndGetProductDocuments(productImportModel, config); product.DocumentsAndFiles.AddRange(productFiles); catalogManager.SaveChanges(); ProductSynchronizer.UpdateProductDocumentsAndFilesLinks(product, DefaultProvider); } catch (Exception filesEx) { if (!isFailedSet) { isFailedSet = true; numberOfFailedRecords++; importErrors.Add(new ImportError { ErrorMessage = filesEx.Message, ErrorRow = productImportModel.CorrespondingRowData }); } } }
private static void ImportImages(UploadConfig config, CatalogManager catalogManager, List<ImportError> importErrors, ref int numberOfFailedRecords, ProductImportModel productImportModel, ref bool isFailedSet, Product product) { try { List<ProductImage> productImages = ImagesImporter.ImportImagesAndGetProductImages(productImportModel, config); product.Images.AddRange(productImages); catalogManager.SaveChanges(); ContentLinkGenerator.GenerateContentLinksForProductImages(product); } catch (Exception imageEx) { if (!isFailedSet) { isFailedSet = true; numberOfFailedRecords++; importErrors.Add(new ImportError { ErrorMessage = imageEx.Message, ErrorRow = productImportModel.CorrespondingRowData }); } } }
private void AddEventToCart(Event currentEvent) { CatalogManager catalog = new CatalogManager(); Product product = catalog.GetProduct(ProductId); HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("shoppingCartId"); OrdersManager orderm = new OrdersManager(); OptionsDetails optionDetails = new OptionsDetails(); // Check if shopping cart cookie exists in the current request. if (cookie == null) //if it does not exist... { CartOrder cartItem = orderm.CreateCartOrder(); //create a new cart order var shoppingcartid = cartItem.Id; // that id is equal to the cookie value HttpCookie Cookie = new HttpCookie("shoppingCartId"); //create a new shopping cart cookie DateTime now = DateTime.Now; // Set the cookie value. Cookie.Value = shoppingcartid.ToString(); // Set the cookie expiration date. Cookie.Expires = now.AddYears(1);// Add the cookie. HttpContext.Current.Response.Cookies.Add(Cookie); //give cart item currency of USD because it cannot be null cartItem.Currency = "USD"; //add the product to the cart orderm.AddToCart(cartItem, product, optionDetails, 1); //save all changes orderm.SaveChanges(); } else //if the cookie does exist { Guid guid = new Guid(cookie.Value.ToString()); //get the cookie value as the guid CartOrder cartItem = orderm.GetCartOrder(guid); //get the cart based on the cookie value orderm.AddToCart(cartItem, product, optionDetails, 1); // add the item to the cart orderm.SaveChanges(); //save changes } }
internal static Tuple<bool, IPaymentResponse> PlaceOrder(OrdersManager ordersManager, CatalogManager catalogManager, UserManager userManager, RoleManager roleManager, UserProfileManager userProfileManager, CheckoutState checkoutState, Guid cartOrderId) { CartOrder cartOrder = ordersManager.GetCartOrder(cartOrderId); cartOrder.Addresses.Clear(); cartOrder.Payments.Clear(); //set the default currency of the order string defaultCurrency = Config.Get<EcommerceConfig>().DefaultCurrency; cartOrder.Currency = defaultCurrency; // set the shipping address CartAddress shippingAddress = CartHelper.GetShippingAddressFromCheckoutState(ordersManager, checkoutState); cartOrder.Addresses.Add(shippingAddress); // set the billing address CartAddress billingAddress = CartHelper.GetBillingAddressFromCheckoutState(ordersManager, checkoutState); cartOrder.Addresses.Add(billingAddress); //Get the first payment method in the shop // set the payment CartPayment payment = CartHelper.GetCartPaymentFromCheckoutState(ordersManager, checkoutState); cartOrder.Payments.Add(payment); ordersManager.SaveChanges(); // Get current customer or create new one Customer customer = UserProfileHelper.GetCustomerInfoOrCreateOneIfDoesntExsist(userProfileManager,ordersManager, checkoutState); // Save the customer address CustomerAddressHelper.SaveCustomerAddressOfCurrentUser(checkoutState, customer); //Use the API to checkout IPaymentResponse paymentResponse = ordersManager.Checkout(cartOrderId, checkoutState, customer); // record the "success" state of the checkout checkoutState.IsPaymentSuccessful = paymentResponse.IsSuccess; Order order = ordersManager.GetOrder(cartOrderId); //Increment the order IncrementOrderNumber(ordersManager, order); // add the order to customer customer.Orders.Add(order); // Update the order order.Customer = customer; ordersManager.SaveChanges(); if (!paymentResponse.IsSuccess) { return new Tuple<bool, IPaymentResponse>(false, paymentResponse); } if (order.OrderStatus == OrderStatus.Paid) { UserProfileHelper.AssignCustomerToRoles(userManager, roleManager, catalogManager, SecurityManager.GetCurrentUserId(), order); EmailHelper.SendOrderPlacedEmailToClientAndMerchant(cartOrder, checkoutState, order.OrderNumber); } return new Tuple<bool, IPaymentResponse>(true, paymentResponse); }