예제 #1
0
        public static CategoryDetailsJson Category(string accountNameKey, CategoryModel categoryIn, bool includeItems, bool includeHidden)
        {
            var categoryObjectOut = new CategoryDetailsJson();

            categoryObjectOut.category = new Models.Json.Categorization.CategoryJson();
            categoryObjectOut.category.subcategories = new List <CategorizationListItemJson>();


            #region Build out subcategorization list

            foreach (SubcategoryListModel subcategoryModel in categoryIn.Subcategories)
            {
                var subcategoryListItem = new CategorizationListItemJson
                {
                    //id = subcategoryModel.SubcategoryID.ToString(),
                    name               = subcategoryModel.SubcategoryName,
                    nameKey            = subcategoryModel.SubcategoryNameKey,
                    fullyQualifiedName = subcategoryModel.FullyQualifiedName
                };

                //Get listing images for each subcategory in the list
                subcategoryListItem.images = Dynamics.Images.BuildDynamicImagesListForJson(accountNameKey, "subcategory", subcategoryModel.SubcategoryID.ToString(), true);

                categoryObjectOut.category.subcategories.Add(subcategoryListItem);
            }

            #endregion


            #region Build out product list

            if (includeItems && categoryIn.Subcategories.Count == 0)
            {
                var account = Common.GetAccountObject(accountNameKey);

                //Search products
                string filter         = "(categoryNameKey eq '" + categoryIn.CategoryNameKey + "')";
                var    productResults = DataAccess.Search.SearchProducts(account, null, filter, "orderId asc", 0, 1000, false, null, includeHidden);

                categoryObjectOut.category.items = Dynamics.Products.TransformDynamicProductsListForJson(productResults.Results);
            }

            #endregion

            //categoryObjectOut.count = categoryObjectOut.categories.Count;

            //Get images for this category
            categoryObjectOut.category.images = Dynamics.Images.BuildDynamicImagesListForJson(accountNameKey, "category", categoryIn.CategoryID.ToString(), false);

            //categoryObjectOut.category.id = categoryIn.CategoryID.ToString();
            categoryObjectOut.category.name               = categoryIn.CategoryName;
            categoryObjectOut.category.nameKey            = categoryIn.CategoryNameKey;
            categoryObjectOut.category.fullyQualifiedName = categoryIn.FullyQualifiedName;
            categoryObjectOut.category.description        = categoryIn.Description;
            return(categoryObjectOut);
        }
예제 #2
0
        public JsonNetResult Category(string nameKey, bool includeHidden = false, bool includeItems = false)
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            CategoryModel       category = null;
            CategoryDetailsJson categoryDetailsObjectJson = null;

            string localCacheKey = accountNameKey + ":category:" + nameKey + ":includeHidden:" + includeHidden + "includeProducts:" + includeItems;


            #region (Plan A) Get json from local cache

            try
            {
                categoryDetailsObjectJson = (CategoryDetailsJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (categoryDetailsObjectJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        categoryDetailsObjectJson = JsonConvert.DeserializeObject <CategoryDetailsJson>(redisApiValue);
                        executionType             = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (categoryDetailsObjectJson == null)
                {
                    #region (Plan C) Get category data from Redis Cache and rebuild

                    try
                    {
                        //IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                        string hashMainKey   = accountNameKey + ":categories";
                        string hashMainField = nameKey + ":public";

                        if (includeHidden == true)
                        {
                            hashMainField = nameKey + ":private";
                        }

                        try
                        {
                            var redisValue = cache.HashGet(hashMainKey, hashMainField);

                            if (redisValue.HasValue)
                            {
                                category      = JsonConvert.DeserializeObject <ApplicationCategorizationService.CategoryModel>(redisValue);
                                executionType = ExecutionType.redis_main;
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        var error = e.Message;
                        //TODO: Log: error message for Redis call
                    }

                    #endregion

                    if (category == null)
                    {
                        #region (Plan D) Get data from WCF

                        var applicationCategorizationServiceClient = new ApplicationCategorizationService.ApplicationCategorizationServiceClient();

                        try
                        {
                            applicationCategorizationServiceClient.Open();

                            category = applicationCategorizationServiceClient.GetCategoryByName(accountNameKey, nameKey, includeHidden, Common.SharedClientKey);

                            executionType = ExecutionType.wcf;

                            WCFManager.CloseConnection(applicationCategorizationServiceClient);
                        }
                        catch (Exception e)
                        {
                            #region Manage Exception

                            string exceptionMessage = e.Message.ToString();

                            var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                            string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                            // Abort the connection & manage the exception
                            WCFManager.CloseConnection(applicationCategorizationServiceClient, exceptionMessage, currentMethodString);

                            #endregion
                        }

                        #endregion
                    }
                }

                #region Transform into json object, add images & cache locally or locally and radisAPI layer

                if (categoryDetailsObjectJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, categoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (category != null)
                {
                    //Transform categories into JSON and cache BOTH locally AND into redis
                    categoryDetailsObjectJson = Transforms.Json.CategorizationTransforms.Category(accountNameKey, category, includeItems, includeHidden);
                    HttpRuntime.Cache.Insert(localCacheKey, categoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(categoryDetailsObjectJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

            if (categoryDetailsObjectJson == null)
            {
                //return empty
                return(new JsonNetResult());
            }

            //Add execution data
            stopWatch.Stop();
            categoryDetailsObjectJson.executionType = executionType.ToString();
            categoryDetailsObjectJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = categoryDetailsObjectJson;

            return(jsonNetResult);
        }