public async Task <ActionResult> Restaurants(DealSortOrder sortBy = DealSortOrder.City, string sortOrder = "asc") { try { LiveIdAuthResult liveIdAuthResult = HttpContext.Items["liveauthstate"] as LiveIdAuthResult; AuthorizeUserResult userResult = await AuthorizeUser(liveIdAuthResult); if (!userResult.Authorized) { return(userResult.Result); } if (liveIdAuthResult != null) { ViewBag.ProfileName = liveIdAuthResult.ProfileName; ViewBag.SignOutHtmlLink = liveIdAuthResult.SignOutHtmlLink; } string state = (HttpContext.Items["state"] as string) ?? "wa"; if (state == "wa") { ViewBag.wa = "selected"; } else if (state == "az") { ViewBag.az = "selected"; } if (state == "ma") { ViewBag.ma = "selected"; } string revIpHeader = HttpContext.Request.Headers["X-FD-RevIP"]; Task <List <Deal> > dealTask = DealService.GetDeals(state); UserModel userModel = new UserModel(User.Identity as ClaimsIdentity); string secureToken = HttpContext.Items["backendtoken"] as string; Task <string> earnedAmountTask = CommerceService.GetTotalEarnedAmount(userModel, secureToken); string earnedAmount = await earnedAmountTask; List <Deal> deals = await dealTask; SortDealsBy(deals, sortBy, sortOrder); AccountsPageModel pageModel = new AccountsPageModel { LocalDeals = deals, SelectedState = state, EarnTotal = earnedAmount, SortBy = Enum.GetName(sortBy.GetType(), sortBy), SortOrder = sortOrder, Page = "restaurants", UserId = userModel.UserId }; return(View("~/offers/earn/views/account/restaurants.cshtml", pageModel)); } catch (Exception e) { } return(HandleServerError()); }
public MembershipService(ScheduledEventDateDefinition supported) { this.supported = supported; cs = Service.Get<CommerceService>(); if (IsPurchaseFunnelAvailable() && cs != null) { Service.Get<EventDispatcher>().AddListener<CommerceServiceEvents.PurchaseVerified>(PurchaseWasVerified); Service.Get<EventDispatcher>().AddListener<CommerceServiceErrors.PurchaseVerifiedError>(PurchaseWasVerifiedError); Service.Get<EventDispatcher>().AddListener<CommerceServiceEvents.UnexpectedPurchase>(UnexpectedPurchaseEvent); Service.Get<EventDispatcher>().AddListener<CommerceServiceEvents.ProductsLoaded>(ProducstWereLoadedVerified); Service.Get<EventDispatcher>().AddListener<CommerceServiceErrors.ProductsLoadedError>(ProducstWereLoadedError); Service.Get<EventDispatcher>().AddListener<CommerceServiceEvents.BillingEnabled>(BillingEnabled); Service.Get<EventDispatcher>().AddListener<CommerceServiceErrors.BillingEnabledError>(BillingEnabledError); Service.Get<EventDispatcher>().AddListener<CommerceServiceEvents.RestoreVerified>(RestoreWasVerified); Service.Get<EventDispatcher>().AddListener<CommerceServiceErrors.RestoreVerifiedError>(RestoreWasVerifiedError); Service.Get<EventDispatcher>().AddListener<NetworkErrors.InvalidSubscriptionError>(onInvalidSubscriptionError); Service.Get<EventDispatcher>().AddListener<IAPServiceErrors.MembershipGrantError>(onMembershipGrantError); if (cs.CommerceProcessor.IsBillingSupported()) { LoadProducts(); } } overrideSimCountryCode = new DevCacheableType<string>("cp.OverrideSimCountryCode", ""); overrideSimCarrierName = new DevCacheableType<string>("cp.OverrideSimCarrierName", ""); MembershipFunnelName = "membership_offer"; }
public void CommerceService_Constructor_Basic() { CommerceService cs = new CommerceService(); Assert.IsNotNull(cs.ItemsDatabaseBuilder); Assert.IsNotNull(cs.ItemsDB); }
public void CommerceService_GetItems_ByID_AllValid() { CommerceService cs = new CommerceService(); // Create the collection of items List <int> ids = new List <int>(cs.ItemsDB.Keys.Take(200)); var sw = new Stopwatch(); sw.Start(); var items = cs.GetItems(ids); sw.Stop(); Console.WriteLine("To retrieve details {0} items using a valid IDs, it took {1}ms", ids.Count, sw.ElapsedMilliseconds); Assert.IsNotNull(items); foreach (var item in items) { var itemFromDb = cs.ItemsDB.FirstOrDefault(i => i.Key == item.Key); Assert.IsNotNull(itemFromDb); Assert.AreEqual(itemFromDb.Key, item.Value.ID); Assert.AreEqual(itemFromDb.Value.ID, item.Value.ID); Assert.AreEqual(itemFromDb.Value.Name, item.Value.Name); Assert.AreEqual(itemFromDb.Value.Rarity, item.Value.Rarity); Assert.AreEqual(itemFromDb.Value.Level, item.Value.LevelRequirement); } }
public void CommerceService_ReloadDatabase_Basic() { CommerceService cs = new CommerceService(); cs.ItemsDB.Clear(); cs.ReloadDatabase(); Assert.IsNotNull(cs.ItemsDB); Assert.IsTrue(cs.ItemsDB.Count > 0); }
protected override IEnumerator setup() { GcsAccessTokenService gcsAccessTokenService = new GcsAccessTokenService(ConfigHelper.GetEnvironmentProperty <string>("GcsServiceAccountName"), new GcsP12AssetFileLoader(ConfigHelper.GetEnvironmentProperty <string>("GcsServiceAccountFile"))); Service.Set((IGcsAccessTokenService)gcsAccessTokenService); string cdnUrl = ContentHelper.GetCdnUrl(); string cpipeMappingFilename = ContentHelper.GetCpipeMappingFilename(); CPipeManifestService cpipeManifestService = new CPipeManifestService(cdnUrl, cpipeMappingFilename, gcsAccessTokenService); Service.Set((ICPipeManifestService)cpipeManifestService); base.gameObject.AddComponent <KeyChainManager>(); GameSettings gameSettings = new GameSettings(); Service.Set(gameSettings); ContentManifest definition = ContentManifestUtility.FromDefinitionFile("Configuration/embedded_content_manifest"); Service.Set(new Content(definition)); Localizer localizer = Localizer.Instance; Service.Set(localizer); NullCPSwrveService cpSwrveService = new NullCPSwrveService(); Service.Set((ICPSwrveService)cpSwrveService); NetworkServicesConfig networkConfig = NetworkController.GenerateNetworkServiceConfig(TestEnvironment); Service.Set((INetworkServicesManager) new NetworkServicesManager(this, networkConfig, offlineMode: false)); CommerceService commerceService = new CommerceService(); commerceService.Setup(); Service.Set(commerceService); Service.Set(new MembershipService(null)); ConnectionManager connectionManager = base.gameObject.AddComponent <ConnectionManager>(); Service.Set(connectionManager); Service.Set(new SessionManager()); Service.Set(new MixLoginCreateService()); Service.Set((CPDataEntityCollection) new CPDataEntityCollectionImpl()); LocalPlayerData localPlayerData = new LocalPlayerData { name = "TestPlayer", tutorialData = new List <sbyte>() }; PlayerId playerId = localPlayerData.id = new PlayerId { id = "999999999999999", type = PlayerId.PlayerIdType.SESSION_ID }; Service.Get <CPDataEntityCollection>().ResetLocalPlayerHandle(); PlayerDataEntityFactory.AddLocalPlayerProfileDataComponents(Service.Get <CPDataEntityCollection>(), localPlayerData); LoginController loginController = new LoginController(); Service.Set(loginController); loginController.SetNetworkConfig(networkConfig); IntegrationTestEx.FailIf(Service.Get <MixLoginCreateService>().NetworkConfigIsNotSet); yield return(null); }
public void CommerceService_DoesItemExist_True() { CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); Assert.IsTrue(cs.DoesItemExist(VALID_ITEM_NAME, Data.Enums.ItemRarity.Basic, 0)); sw.Stop(); Console.WriteLine("To search for a valid name, it took {0}ms", sw.ElapsedMilliseconds); }
public void CommerceService_DoesItemExist_False() { // For this test, we'll also time how long it takes to check CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); Assert.IsFalse(cs.DoesItemExist(INVALID_ITEM_NAME, Data.Enums.ItemRarity.Basic, 0)); sw.Stop(); Console.WriteLine("To search for an invalid name, it took {0}ms", sw.ElapsedMilliseconds); }
public void CommerceService_GetItemID_Invalid() { CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); var id = cs.GetItemID(INVALID_ITEM_NAME, Data.Enums.ItemRarity.Basic, 0); sw.Stop(); Console.WriteLine("To search for an ID using an invalid name, it took {0}ms", sw.ElapsedMilliseconds); Assert.AreEqual(-1, id); }
public void CommerceService_GetItem_ByNameRarityLevel_Invalid() { CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); var item = cs.GetItem(INVALID_ITEM_NAME, Data.Enums.ItemRarity.Basic, 0); sw.Stop(); Console.WriteLine("To retrieve details of an item using a invalid name, it took {0}ms", sw.ElapsedMilliseconds); Assert.IsNull(item); }
public void CommerceService_GetItem_ByID_Invalid() { CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); var item = cs.GetItem(-1); sw.Stop(); Console.WriteLine("To retrieve details of an item using a invalid ID, it took {0}ms", sw.ElapsedMilliseconds); Assert.IsNull(item); }
public void CommerceService_GetItemPrices_Single_Invalid() { CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); var prices = cs.GetItemPrices(-1); sw.Stop(); Console.WriteLine("{0}ms", sw.ElapsedMilliseconds); Assert.IsNull(prices); }
public void CommerceService_ReloadDatabase_PerfCheck() { // For this test, we'll time how long it takes to load CommerceService cs = new CommerceService(); cs.ItemsDB.Clear(); var sw = new Stopwatch(); sw.Start(); cs.ReloadDatabase(); sw.Stop(); Console.WriteLine("To load {0} item names, it took {1}ms", cs.ItemsDB.Count, sw.ElapsedMilliseconds); }
private void Start() { cs = Service.Get <CommerceService>(); if (cs != null) { Service.Get <EventDispatcher>().AddListener <CommerceServiceEvents.BillingEnabled>(BillingWasEnabled); Service.Get <EventDispatcher>().AddListener <CommerceServiceErrors.BillingEnabledError>(BillingWasEnabledError); Service.Get <EventDispatcher>().AddListener <CommerceServiceEvents.PurchaseVerified>(PurchaseWasVerified); Service.Get <EventDispatcher>().AddListener <CommerceServiceErrors.PurchaseVerifiedError>(PurchaseWasVerifiedError); Service.Get <EventDispatcher>().AddListener <CommerceServiceEvents.UnexpectedPurchase>(UnexpectedPurchaseEvent); Service.Get <EventDispatcher>().AddListener <CommerceServiceEvents.ProductsLoaded>(ProducstWereLoadedVerified); Service.Get <EventDispatcher>().AddListener <CommerceServiceErrors.ProductsLoadedError>(ProducstWereLoadedError); Service.Get <EventDispatcher>().AddListener <CommerceServiceEvents.RestoreVerified>(RestoreWasVerified); Service.Get <EventDispatcher>().AddListener <CommerceServiceErrors.RestoreVerifiedError>(RestoreWasVerifiedError); } }
public async Task <ActionResult> Index() { try { LiveIdAuthResult liveIdAuthResult = HttpContext.Items["liveauthstate"] as LiveIdAuthResult; AuthorizeUserResult userResult = await AuthorizeUser(liveIdAuthResult); if (!userResult.Authorized) { return(userResult.Result); } if (liveIdAuthResult != null) { ViewBag.ProfileName = liveIdAuthResult.ProfileName; ViewBag.SignOutHtmlLink = liveIdAuthResult.SignOutHtmlLink; } string state = (HttpContext.Items["state"] as string) ?? "wa"; Task <List <Deal> > dealTask = DealService.GetDeals(state); UserModel userModel = new UserModel(User.Identity as ClaimsIdentity); string secureToken = HttpContext.Items["backendtoken"] as string; Task <string> earnedAmountTask = CommerceService.GetTotalEarnedAmount(userModel, secureToken); string earnedAmount = await earnedAmountTask; List <Deal> deals = await dealTask; List <Deal> topDeals = DealService.GetTopDeals(state); if (deals != null) { AccountsPageModel model = new AccountsPageModel { LocalDeals = deals, TopDeals = topDeals, EarnTotal = earnedAmount, UserId = userModel.UserId, Page = "places to earn" }; return(View("~/offers/earn/views/account/places.cshtml", model)); } } catch (Exception e) { } return(HandleServerError()); }
public void CommerceService_GetItem_ByID_Valid() { CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); var item = cs.GetItem(VALID_ITEM_NAME_ID); sw.Stop(); Console.WriteLine("To retrieve details of an item using a valid ID, it took {0}ms", sw.ElapsedMilliseconds); Assert.IsNotNull(item); Assert.AreEqual(VALID_ITEM_NAME_ID, item.ID); Assert.AreEqual(VALID_ITEM_NAME, item.Name); // TODO: check more }
public IHttpActionResult Get(Guid id) { if (Guid.Empty == id) { return(BadRequest()); } try { return(Ok(CommerceService.Get(id))); } catch (Exception ex) { Logger.Error($"Error in {nameof(CartsController)} in method {nameof(Get)}", ex); return(InternalServerError()); } }
public async Task <ActionResult> Referrals() { try { LiveIdAuthResult liveIdAuthResult = HttpContext.Items["liveauthstate"] as LiveIdAuthResult; AuthorizeUserResult userResult = await AuthorizeUser(liveIdAuthResult); if (!userResult.Authorized) { return(userResult.Result); } if (liveIdAuthResult != null) { ViewBag.ProfileName = liveIdAuthResult.ProfileName; ViewBag.SignOutHtmlLink = liveIdAuthResult.SignOutHtmlLink; } UserModel userModel = new UserModel(User.Identity as ClaimsIdentity); string secureToken = HttpContext.Items["backendtoken"] as string; Task <string> earnedAmountTask = CommerceService.GetTotalEarnedAmount(userModel, secureToken); Task <string> referralCodeTask = CommerceService.LoadReferralCode(userModel, secureToken); Task <List <ReferralCodeReportDataContract> > referralReportTask = CommerceService.LoadReferralReport(userModel, secureToken); string earnedAmount = await earnedAmountTask; string referralCode = await referralCodeTask; List <ReferralCodeReportDataContract> referralReport = await referralReportTask; AccountsPageModel pageModel = new AccountsPageModel { EarnTotal = earnedAmount, ReferralReport = referralReport, ReferralCode = referralCode, Page = "referrals", UserId = userModel.UserId }; return(View("~/offers/earn/views/account/referrals.cshtml", pageModel)); } catch (Exception e) { } return(HandleServerError()); }
public async Task <ActionResult> GiftCards() { try { LiveIdAuthResult liveIdAuthResult = HttpContext.Items["liveauthstate"] as LiveIdAuthResult; AuthorizeUserResult userResult = await AuthorizeUser(liveIdAuthResult); if (!userResult.Authorized) { return(userResult.Result); } if (liveIdAuthResult != null) { ViewBag.ProfileName = liveIdAuthResult.ProfileName; ViewBag.SignOutHtmlLink = liveIdAuthResult.SignOutHtmlLink; } string state = (HttpContext.Items["state"] as string) ?? "wa"; string revIpHeader = HttpContext.Request.Headers["X-FD-RevIP"]; UserModel userModel = new UserModel(User.Identity as ClaimsIdentity); string secureToken = HttpContext.Items["backendtoken"] as string; Task <string> earnedAmountTask = CommerceService.GetTotalEarnedAmount(userModel, secureToken); User userInfo = await UserService.GetUserInfo(secureToken); string earnedAmount = await earnedAmountTask; if (userInfo != null) { AccountsPageModel pageModel = new AccountsPageModel { UserInfo = userInfo, EarnTotal = earnedAmount, UserId = userModel.UserId, Page = "GiftCards" }; return(View("~/offers/earn/views/account/giftcards.cshtml", pageModel)); } } catch (Exception e) { } return(HandleServerError()); }
public async Task <ActionResult> Settings() { try { LiveIdAuthResult liveIdAuthResult = HttpContext.Items["liveauthstate"] as LiveIdAuthResult; AuthorizeUserResult userResult = await AuthorizeUser(liveIdAuthResult); if (!userResult.Authorized) { return(userResult.Result); } if (liveIdAuthResult != null) { ViewBag.ProfileName = liveIdAuthResult.ProfileName; ViewBag.SignOutHtmlLink = liveIdAuthResult.SignOutHtmlLink; } UserModel userModel = new UserModel(User.Identity as ClaimsIdentity); string secureToken = HttpContext.Items["backendtoken"] as string; Task <V2GetCardsResponse> getCardsResponseTask = CommerceService.GetRegisteredCards(secureToken); Task <string> earnedAmountTask = CommerceService.GetTotalEarnedAmount(userModel, secureToken); User userInfo = await UserService.GetUserInfo(secureToken); string earnedAmount = await earnedAmountTask; V2GetCardsResponse getCardsResponse = await getCardsResponseTask; AccountsPageModel pageModel = new AccountsPageModel { EarnTotal = earnedAmount, Cards = getCardsResponse.Cards, UserInfo = userInfo, Page = "settings", UserId = userModel.UserId }; return(View("~/offers/earn/views/account/settings.cshtml", pageModel)); } catch (Exception e) { } return(HandleServerError()); }
public void CommerceService_Constructor_NoDatabaseFile() { string renamedFilename = "renamedDB.json"; File.Move(ItemsDatabaseBuilder.NAMES_DATABASE_FILENAME, renamedFilename); try { CommerceService cs = new CommerceService(); Assert.IsNotNull(cs.ItemsDatabaseBuilder); Assert.IsNotNull(cs.ItemsDB); } finally { File.Move(renamedFilename, ItemsDatabaseBuilder.NAMES_DATABASE_FILENAME); } }
public void CommerceService_GetItemPrices_Single_Valid() { CommerceService cs = new CommerceService(); var sw = new Stopwatch(); sw.Start(); var prices = cs.GetItemPrices(VALID_ITEM_NAME_ID); sw.Stop(); Console.WriteLine("{0}ms", sw.ElapsedMilliseconds); Assert.IsNotNull(prices); Assert.IsTrue(prices.BuyOrderQuantity > 0); Assert.IsTrue(prices.HighestBuyOrder > 0); Assert.IsTrue(prices.LowestSellListing > 0); Assert.IsTrue(prices.SellOrderQuantity > 0); }
public void CommerceService_Constructor_NoDatabaseFile() { string renamedFilename = "renamedDB.json"; File.Move(Paths.LocalizationFolder + "\\ItemDatabase.json", renamedFilename); try { CommerceService cs = new CommerceService(); Assert.IsNotNull(cs.ItemsDatabaseBuilder); Assert.IsNotNull(cs.ItemsDB); } finally { File.Move(renamedFilename, Paths.LocalizationFolder + "\\ItemDatabase.json"); } }
public void CommerceService_ReloadDatabase_NoDatabaseFile() { CommerceService cs = new CommerceService(); cs.ItemsDB.Clear(); string renamedFilename = "renamedDB.json"; File.Move(Paths.LocalizationFolder + "\\ItemDatabase.json", renamedFilename); try { cs.ReloadDatabase(); Assert.IsNotNull(cs.ItemsDB); } finally { File.Move(renamedFilename, Paths.LocalizationFolder + "\\ItemDatabase.json"); } }
public void CommerceService_ReloadDatabase_NoDatabaseFile() { CommerceService cs = new CommerceService(); cs.ItemsDB.Clear(); string renamedFilename = "renamedDB.json"; File.Move(ItemsDatabaseBuilder.NAMES_DATABASE_FILENAME, renamedFilename); try { cs.ReloadDatabase(); Assert.IsNotNull(cs.ItemsDB); } finally { File.Move(renamedFilename, ItemsDatabaseBuilder.NAMES_DATABASE_FILENAME); } }
private void LoadSearchResults() { if (!this.Performed) { return; } var pageSize = this.Context == null ? 20 : this.Context["paginate.page_size"].ToInt(20); var skip = this.Context == null ? 0 : this.Context["paginate.current_offset"].ToInt(); var terms = this.Terms; //this.Context["current_query"] as string; var type = this.Context == null ? "product" : this.Context["current_type"] as string; var siteContext = SiteContext.Current; var service = new CommerceService(); var searchQuery = new BrowseQuery() { Skip = skip, Take = pageSize, Search = terms}; var response = Task.Run(() => service.SearchAsync<object>(siteContext, searchQuery)).Result; this.Results = response; this.Performed = false; }
public override IEnumerator PerformFirstPass() { CommerceService commerceService = new CommerceService(); commerceService.Setup(); Dictionary <int, ScheduledEventDateDefinition> dictionary = Service.Get <IGameData>().Get <Dictionary <int, ScheduledEventDateDefinition> >(); ScheduledEventDateDefinition value = null; dictionary.TryGetValue(SupportWindow.Id, out value); Service.Set(commerceService); Service.Set(new MembershipService(value)); if (Service.Get <GameSettings>().FirstSession) { Service.Get <MembershipService>().AccountFunnelName = "account_creation"; } else { Service.Get <MembershipService>().AccountFunnelName = "login"; } yield break; }
public void CommerceService_GetItemPrices_Multiple_Valid() { CommerceService cs = new CommerceService(); // Create the collection of items List <int> ids = new List <int>(cs.ItemsDB.Keys.Take(100)); var sw = new Stopwatch(); sw.Start(); var prices = cs.GetItemPrices(ids); sw.Stop(); Console.WriteLine("To retrieve prices of {0} items using valid IDs, it took {1}ms", ids.Count, sw.ElapsedMilliseconds); Assert.IsNotNull(prices); foreach (var itemPrices in prices) { Assert.IsTrue(ids.Contains(itemPrices.Key)); } }
public void CommerceService_Constructor_InvalidDatabaseFile() { string renamedFilename = "renamedDB.json"; string itemDbJson = Path.Combine(Paths.LocalizationFolder, "en", "ItemDatabase.json"); File.Move(itemDbJson, renamedFilename); File.WriteAllText(itemDbJson, "invalid file"); try { CommerceService cs = new CommerceService(); Assert.IsNotNull(cs.ItemsDatabaseBuilder); Assert.IsNotNull(cs.ItemsDB); } finally { File.Delete(itemDbJson); File.Move(renamedFilename, itemDbJson); } }
public async Task <ActionResult> Index(bool debug = false, string step = "step1") { try { LiveIdAuthResult liveIdAuthResult = HttpContext.Items["liveauthstate"] as LiveIdAuthResult; ViewBag.CurrentStep = step; if (!User.Identity.IsAuthenticated) { return(HandleUnauthenticatedUser(liveIdAuthResult)); } UserModel userModel = new UserModel(User.Identity as ClaimsIdentity); ViewBag.UserId = userModel.UserId; string secureToken = HttpContext.Items["backendtoken"] as string; bool status = await CommerceService.IsUserRegisteredWithCardLink(userModel, secureToken); if (liveIdAuthResult != null) { ViewBag.ProfileName = liveIdAuthResult.ProfileName; ViewBag.SignOutHtmlLink = liveIdAuthResult.SignOutHtmlLink; } if (debug) { return(View("~/offers/earn/views/enroll/enroll.cshtml")); } if (status) { return(HandleRegisteredUser()); } return(View("~/offers/earn/views/enroll/enroll.cshtml")); } catch { return(HandleServerError()); } }
public IHttpActionResult Add([FromBody] Product product, Guid id) { if (Guid.Empty == id) { return(BadRequest()); } if (product == null) { return(BadRequest()); } try { CommerceService.Add(product, id); return(Ok()); } catch (Exception ex) { Logger.Error($"Error in {nameof(CartsController)} in method {nameof(Add)}", ex); return(InternalServerError()); } }
public CartHelper(CommerceService service) { _commerceService = service; }
public override async Task Invoke(IOwinContext context) { var customerService = new CustomerService(); var commerceService = new CommerceService(); var ctx = SiteContext.Current; ctx.LoginProviders = GetExternalLoginProviders(context).ToArray(); // Need to load language for all files, since translations are used within css and js // the order of execution is very important when initializing context // 1st: initialize some sort of context, especially get a list of all shops first // other methods will rely on that to be performance efficient // 2nd: find current shop from url, which context with shops will be used for ctx.Shops = await commerceService.GetShopsAsync(); // Get current language var language = this.GetLanguage(context).ToSpecificLangCode(); ctx.Language = language; var shop = this.GetStore(context, language); if (shop == null) { using (var reader = new System.IO.StreamReader(HttpContext.Current.Server.MapPath("~/App_data/Help/nostore.html"))) { var content = await reader.ReadToEndAsync(); await context.Response.WriteAsync(content); } } else { var currency = GetStoreCurrency(context, shop); shop.Currency = currency; ctx.Shop = shop; ctx.Themes = await commerceService.GetThemesAsync(SiteContext.Current); // if language is not set, set it to default shop language if (String.IsNullOrEmpty(ctx.Language)) { language = shop.DefaultLanguage; if (String.IsNullOrEmpty(language)) { throw new HttpException(404, "Store language not found"); } CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(language); ctx.Language = language; } if (!this.IsResourceFile()) // only load settings for resource files, no need for other contents { // save info to the cookies context.Response.Cookies.Append(StoreCookie, shop.StoreId, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }); context.Response.Cookies.Append(LanguageCookie, ctx.Language, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }); context.Response.Cookies.Append(CurrencyCookie, shop.Currency, new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }); if (context.Authentication.User != null && context.Authentication.User.Identity.IsAuthenticated) { ctx.Customer = await customerService.GetCustomerAsync( context.Authentication.User.Identity.Name, shop.StoreId); if (ctx.Customer == null) { context.Authentication.SignOut(); } else { ctx.CustomerId = ctx.Customer.Id; } } if (ctx.Customer == null) { var cookie = context.Request.Cookies[AnonymousCookie]; if (string.IsNullOrEmpty(cookie)) { cookie = Guid.NewGuid().ToString(); var cookieOptions = new CookieOptions { Expires = DateTime.UtcNow.AddDays(30) }; context.Response.Cookies.Append(AnonymousCookie, cookie, cookieOptions); } ctx.CustomerId = cookie; } // TODO: detect if shop exists, user has access // TODO: store anonymous customer id in cookie and update and merge cart once customer is logged in ctx.Linklists = await commerceService.GetListsAsync(SiteContext.Current); ctx.PageTitle = ctx.Shop.Name; ctx.Collections = await commerceService.GetCollectionsAsync(SiteContext.Current); ctx.Pages = new PageCollection(); ctx.Forms = commerceService.GetForms(); var cart = await commerceService.GetCartAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId); if (cart == null) { var dtoCart = new ApiClient.DataContracts.Cart.ShoppingCart { CreatedBy = ctx.CustomerId, CreatedDate = DateTime.UtcNow, Currency = shop.Currency, CustomerId = ctx.CustomerId, CustomerName = ctx.Customer != null ? ctx.Customer.Name : null, LanguageCode = ctx.Language, Name = "default", StoreId = shop.StoreId }; await commerceService.CreateCartAsync(dtoCart); cart = await commerceService.GetCartAsync(SiteContext.Current.StoreId, SiteContext.Current.CustomerId); } ctx.Cart = cart; if (context.Authentication.User.Identity.IsAuthenticated) { var anonymousCookie = context.Request.Cookies[AnonymousCookie]; if (anonymousCookie != null) { var anonymousCart = await commerceService.GetCartAsync(ctx.StoreId, anonymousCookie); if (anonymousCart != null) { ctx.Cart = await commerceService.MergeCartsAsync(anonymousCart); } } context.Response.Cookies.Delete(AnonymousCookie); } ctx.PriceLists = await commerceService.GetPriceListsAsync(ctx.Shop.Catalog, shop.Currency, new TagQuery()); ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context)); // update theme files await commerceService.UpdateThemeCacheAsync(SiteContext.Current); ctx.Blogs = commerceService.GetBlogs(SiteContext.Current); } else { ctx.Theme = commerceService.GetTheme(SiteContext.Current, this.ResolveTheme(shop, context)); } ctx.Settings = commerceService.GetSettings( ctx.Theme.ToString(), context.Request.Path.HasValue && context.Request.Path.Value.Contains(".scss") ? "''" : null); ctx.CountryOptionTags = commerceService.GetCountryTags(); if (ctx.Shop.Currency.Equals("GBP", StringComparison.OrdinalIgnoreCase) || ctx.Shop.Currency.Equals("USD", StringComparison.OrdinalIgnoreCase)) { ctx.Shop.MoneyFormat = commerceService.CurrencyDictionary[ctx.Shop.Currency] + "{{ amount }}"; } else { ctx.Shop.MoneyFormat = "{{ amount }} " + commerceService.CurrencyDictionary[ctx.Shop.Currency]; } context.Set("vc_sitecontext", ctx); await this.Next.Invoke(context); } }
public static string T(string input, params object[] variables) { var service = new CommerceService(); var context = SiteContext.Current; var locs = service.GetLocale(context); var defaultLocs = service.GetLocale(context, true); if (locs == null && defaultLocs == null) { return input; } string retVal; // first get a template string if (variables != null && variables.Length > 0) { var dictionary = variables.Where(x => (x is Tuple<string, object>)) .Select(x => x as Tuple<string, object>) .ToDictionary(x => x.Item1, x => x.Item2); string template; if (dictionary.ContainsKey("count") && dictionary["count"] != null) // execute special count routing { var count = dictionary["count"].ToInt(); JToken templateToken; switch (count) { case 1: templateToken = locs.GetValue(defaultLocs, input + ".one"); break; case 0: templateToken = locs.GetValue(defaultLocs, input + ".zero", null); break; case 2: templateToken = locs.GetValue(defaultLocs, input + ".two", null); break; default: templateToken = locs.GetValue(defaultLocs, input + ".other"); break; } if (templateToken == null) { templateToken = locs.GetValue(defaultLocs, input + ".other"); template = templateToken != null ? templateToken.ToString() : String.Empty; } else { template = templateToken.ToString(); } } else { template = locs.GetValue(defaultLocs, input); } var templateEngine = Template.Parse(template); retVal = templateEngine.Render(Hash.FromDictionary(dictionary)); } else { retVal = locs.GetValue(defaultLocs, input); } return retVal; }
public void LoadSlice(int from, int? to) { var pageSize = to == null ? 50 : to - from; var tags = this.Context["current_tags"] as string[]; var filters = new Dictionary<string, string[]>(); if (tags != null && tags.Any()) { var tagsArray = tags.Select(t => t.Split(new[] { '_' })).Select(x => new Tuple<string, string>(x[0], x[1])); foreach (var tagsGroup in tagsArray.GroupBy(x => x.Item1)) { filters.Add(tagsGroup.Key, tagsGroup.Select(g => g.Item2).ToArray()); } } var service = new CommerceService(); var context = SiteContext.Current; var sortProperty = String.Empty; var sortDirection = "ascending"; var sort = string.IsNullOrEmpty(this.SortBy) ? this.DefaultSortBy : this.SortBy; if (sort.Equals("manual")) { sortProperty = "position"; } else if (sort.Equals("best-selling")) { sortProperty = "position"; } else { var sortArray = sort.Split(new[] { '-' }); if (sortArray.Length > 1) { sortProperty = sortArray[0]; sortDirection = sortArray[1]; } } var searchQuery = new BrowseQuery() { SortProperty = sortProperty, SortDirection = sortDirection, Filters = filters, Skip = from, Take = pageSize.Value, Outline = this.BuildSearchOutline() }; var response = Task.Run(() => service.SearchAsync<Product>(context, searchQuery, this, responseGroups: ItemResponseGroups.ItemSmall | ItemResponseGroups.Variations)).Result; // populate tags with facets returned if (response.Facets != null && response.Facets.Any()) { var values = response.Facets.SelectMany(f => f.Values.Select(v => v.AsWebModel(f.Field))); this.Tags = new TagCollection(values); } this.Products = response; }