示例#1
0
        public static SubsubsubcategoryModel DataReader_to_SubsubsubcategoryModel(SqlDataReader reader)
        {
            SubsubsubcategoryModel subsubsubcategory = new SubsubsubcategoryModel();

            subsubsubcategory.SubsubsubcategoryID      = (Guid)reader["SubsubsubcategoryID"];
            subsubsubcategory.SubsubcategoryID         = (Guid)reader["SubsubcategoryID"];
            subsubsubcategory.SubcategoryID            = (Guid)reader["SubcategoryID"];
            subsubsubcategory.CategoryID               = (Guid)reader["CategoryID"];
            subsubsubcategory.SubsubsubcategoryName    = (String)reader["SubsubsubcategoryName"];
            subsubsubcategory.SubsubsubcategoryNameKey = (String)reader["SubsubsubcategoryNameKey"];
            subsubsubcategory.Description              = (String)reader["Description"];

            subsubsubcategory.OrderID     = (int)reader["OrderID"];
            subsubsubcategory.Visible     = (bool)reader["Visible"];
            subsubsubcategory.CreatedDate = (DateTime)reader["CreatedDate"];

            subsubsubcategory.Category = new CategoryParentModel
            {
                CategoryID         = (Guid)reader["CategoryID"],
                CategoryName       = (String)reader["CategoryName"],
                CategoryNameKey    = (String)reader["CategoryNameKey"],
                FullyQualifiedName = (String)reader["CategoryNameKey"],
                LocationPath       = "/"
            };

            subsubsubcategory.Subcategory = new SubcategoryParentModel
            {
                SubcategoryID      = (Guid)reader["SubcategoryID"],
                SubcategoryName    = (String)reader["SubcategoryName"],
                SubcategoryNameKey = (String)reader["SubcategoryNameKey"],
                FullyQualifiedName = subsubsubcategory.Category.CategoryNameKey + "/" + (String)reader["SubcategoryNameKey"],
                LocationPath       = subsubsubcategory.Category.CategoryNameKey
            };

            subsubsubcategory.Subsubcategory = new SubsubcategoryParentModel
            {
                SubsubcategoryID      = (Guid)reader["SubsubcategoryID"],
                SubsubcategoryName    = (String)reader["SubsubcategoryName"],
                SubsubcategoryNameKey = (String)reader["SubsubcategoryNameKey"],
                FullyQualifiedName    = subsubsubcategory.Category.CategoryNameKey + "/" + subsubsubcategory.Subcategory.SubcategoryNameKey + "/" + (String)reader["SubsubcategoryName"],
                LocationPath          = subsubsubcategory.Category.CategoryNameKey + "/" + subsubsubcategory.Subcategory.SubcategoryNameKey
            };

            subsubsubcategory.LocationPath       = subsubsubcategory.Category.CategoryNameKey + "/" + subsubsubcategory.Subcategory.SubcategoryNameKey + "/" + subsubsubcategory.Subsubcategory.SubsubcategoryNameKey;
            subsubsubcategory.FullyQualifiedName = subsubsubcategory.LocationPath + "/" + subsubsubcategory.SubsubsubcategoryNameKey;

            return(subsubsubcategory);
        }
        internal static SubsubsubcategoryModel SelectSubsubsubcategoryById(string sqlPartition, string schemaId, string subsubsubcategoryId)
        {
            SubsubsubcategoryModel subsubsubcategory = null;

            StringBuilder SqlStatement = new StringBuilder();

            SqlStatement.Append("SELECT TOP 1 ");
            SqlStatement.Append("subsubsub.SubsubsubcategoryID, subsubsub.SubsubsubcategoryName, subsubsub.SubsubsubcategoryNameKey, subsubsub.Visible, subsubsub.OrderID, subsubsub.CreatedDate, subsubsub.Description, subsub.SubsubcategoryID, subsub.SubsubcategoryName, subsub.SubsubcategoryNameKey, sub.SubcategoryID, sub.SubcategoryName, sub.SubcategoryNameKey , cat.CategoryID, cat.CategoryName, cat.CategoryNameKey ");

            SqlStatement.Append("FROM ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".Subsubsubcategory subsubsub ");

            SqlStatement.Append("Inner Join ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".Subsubcategory subsub ");
            SqlStatement.Append("ON subsub.SubsubcategoryID = subsubsub.SubsubcategoryID ");

            SqlStatement.Append("Inner Join ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".Subcategory sub ");
            SqlStatement.Append("ON sub.SubcategoryID = subsub.SubcategoryID ");
            SqlStatement.Append("Join ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".Category cat ");
            SqlStatement.Append("ON cat.CategoryID = sub.CategoryID ");
            SqlStatement.Append("WHERE SubsubsubcategoryID = '");
            SqlStatement.Append(subsubsubcategoryId);
            SqlStatement.Append("'");

            //SqlCommand sqlCommand = new SqlCommand(SqlStatement.ToString(), Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(sqlPartition));
            SqlCommand sqlCommand = Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(sqlPartition).CreateCommand();

            sqlCommand.CommandText = SqlStatement.ToString();

            sqlCommand.Connection.OpenWithRetry();
            SqlDataReader reader = sqlCommand.ExecuteReaderWithRetry();

            while (reader.Read())
            {
                subsubsubcategory = Transforms.Transforms.DataReader_to_SubsubsubcategoryModel(reader);
            }

            sqlCommand.Connection.Close();

            return(subsubsubcategory);
        }
示例#3
0
        public static SubsubsubcategoryDetailsJson Subsubsubcategory(string accountNameKey, SubsubsubcategoryModel subsubsubcategoryIn, bool includeItems, bool includeHidden)
        {
            var subsubsubcategoryObjectOut = new SubsubsubcategoryDetailsJson();

            subsubsubcategoryObjectOut.subsubsubcategory = new Models.Json.Categorization.SubsubsubcategoryJson();

            #region include parent objects

            subsubsubcategoryObjectOut.category = new CategorizationParentItemJson
            {
                name               = subsubsubcategoryIn.Category.CategoryName,
                nameKey            = subsubsubcategoryIn.Category.CategoryNameKey,
                fullyQualifiedName = subsubsubcategoryIn.Category.FullyQualifiedName
            };

            subsubsubcategoryObjectOut.subcategory = new CategorizationParentItemJson
            {
                name               = subsubsubcategoryIn.Subcategory.SubcategoryName,
                nameKey            = subsubsubcategoryIn.Subcategory.SubcategoryNameKey,
                fullyQualifiedName = subsubsubcategoryIn.Subcategory.FullyQualifiedName
            };

            subsubsubcategoryObjectOut.subsubcategory = new CategorizationParentItemJson
            {
                name               = subsubsubcategoryIn.Subsubcategory.SubsubcategoryName,
                nameKey            = subsubsubcategoryIn.Subsubcategory.SubsubcategoryNameKey,
                fullyQualifiedName = subsubsubcategoryIn.Subsubcategory.FullyQualifiedName
            };

            #endregion

            #region Build out product list

            if (includeItems)
            {
                var account = Common.GetAccountObject(accountNameKey);

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

                subsubsubcategoryObjectOut.subsubsubcategory.items = Dynamics.Products.TransformDynamicProductsListForJson(productResults.Results);
            }

            #endregion

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

            //Get images for this category
            subsubsubcategoryObjectOut.subsubsubcategory.images = Dynamics.Images.BuildDynamicImagesListForJson(accountNameKey, "subsubsubcategory", subsubsubcategoryIn.SubsubsubcategoryID.ToString(), false);

            //subcategoryObjectOut.subcategory.id = subcategoryIn.SubcategoryID.ToString();
            subsubsubcategoryObjectOut.subsubsubcategory.name               = subsubsubcategoryIn.SubsubsubcategoryName;
            subsubsubcategoryObjectOut.subsubsubcategory.nameKey            = subsubsubcategoryIn.SubsubsubcategoryNameKey;
            subsubsubcategoryObjectOut.subsubsubcategory.fullyQualifiedName = subsubsubcategoryIn.FullyQualifiedName;
            subsubsubcategoryObjectOut.subsubsubcategory.description        = subsubsubcategoryIn.Description;

            return(subsubsubcategoryObjectOut);
        }
        internal static DataAccessResponseType InsertSubsubsubcategory(string sqlPartition, string schemaId, SubsubsubcategoryModel subsubsubcategory, int maxAllowed)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            StringBuilder SqlStatement = new StringBuilder();

            //SQL Statements =============================================================

            //Check Row Count ===========================================================
            //SqlStatement.Append("DECLARE @ObjectCount INT ");
            SqlStatement.Append("SET @ObjectCount = (SELECT COUNT(*) ");
            SqlStatement.Append("FROM ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".Subsubsubcategory WHERE SubsubcategoryID='");
            SqlStatement.Append(subsubsubcategory.SubsubcategoryID);
            SqlStatement.Append("') ");
            SqlStatement.Append("IF @ObjectCount < '");
            SqlStatement.Append(maxAllowed);
            SqlStatement.Append("' ");
            SqlStatement.Append("BEGIN ");

            //GET MaxOrderBy =============================================================
            //If the highest OrderBy is '0' we insert next as '0' (Alphabetical order) otherwise we +1 the OrderID so the newest categegorization item
            SqlStatement.Append("DECLARE @MaxOrderBy INT ");
            SqlStatement.Append("SET @MaxOrderBy = (SELECT MAX(OrderID) FROM ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".Subsubsubcategory WHERE SubsubcategoryID='");
            SqlStatement.Append(subsubsubcategory.SubsubcategoryID);
            SqlStatement.Append("') ");
            SqlStatement.Append("IF(@MaxOrderBy > 0) ");
            SqlStatement.Append("BEGIN ");
            SqlStatement.Append("SET @MaxOrderBy = @MaxOrderBy + 1 ");
            SqlStatement.Append("END ");

            SqlStatement.Append("IF(@MaxOrderBy IS NULL) ");
            SqlStatement.Append("BEGIN ");
            SqlStatement.Append("SET @MaxOrderBy = 0 ");
            SqlStatement.Append("END ");

            //INSERT =============================================================
            SqlStatement.Append("INSERT INTO  ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".Subsubsubcategory (");

            //SqlStatement.Append("CategoryID,");
            //SqlStatement.Append("SubcategoryID,");
            SqlStatement.Append("SubsubcategoryID,");
            SqlStatement.Append("SubsubsubcategoryID,");
            SqlStatement.Append("SubsubsubcategoryName,");
            SqlStatement.Append("SubsubsubcategoryNameKey,");
            SqlStatement.Append("CreatedDate, ");
            SqlStatement.Append("OrderID, ");
            SqlStatement.Append("Visible");

            SqlStatement.Append(") VALUES (");

            //Using parameterized queries to protect against injection
            //SqlStatement.Append("@CategoryID, ");
            //SqlStatement.Append("@SubcategoryID, ");
            SqlStatement.Append("@SubsubcategoryID, ");
            SqlStatement.Append("@SubsubsubcategoryID, ");
            SqlStatement.Append("@SubsubsubcategoryName, ");
            SqlStatement.Append("@SubsubsubcategoryNameKey, ");
            SqlStatement.Append("@CreatedDate, ");
            SqlStatement.Append("@MaxOrderBy, ");
            SqlStatement.Append("@Visible");

            SqlStatement.Append(")");

            //CLOSE: Check Row Count ===========================================================
            SqlStatement.Append(" END");

            //SqlCommand sqlCommand = new SqlCommand(SqlStatement.ToString(), Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(sqlPartition));
            SqlCommand sqlCommand = Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(sqlPartition).CreateCommand();

            sqlCommand.CommandText = SqlStatement.ToString();



            //Using parameterized queries to protect against injection
            //sqlCommand.Parameters.Add("@CategoryID", SqlDbType.UniqueIdentifier);
            //sqlCommand.Parameters.Add("@SubcategoryID", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@SubsubcategoryID", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@SubsubsubcategoryID", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@SubsubsubcategoryName", SqlDbType.NVarChar);
            sqlCommand.Parameters.Add("@SubsubsubcategoryNameKey", SqlDbType.Text);
            sqlCommand.Parameters.Add("@CreatedDate", SqlDbType.DateTime);
            //sqlCommand.Parameters.Add("@OrderID", SqlDbType.Int);
            sqlCommand.Parameters.Add("@Visible", SqlDbType.Bit);

            //Assign values
            //sqlCommand.Parameters["@CategoryID"].Value = subsubcategory.CategoryID;
            //sqlCommand.Parameters["@SubcategoryID"].Value = subsubcategory.SubcategoryID;
            sqlCommand.Parameters["@SubsubcategoryID"].Value         = subsubsubcategory.SubsubcategoryID;
            sqlCommand.Parameters["@SubsubsubcategoryID"].Value      = subsubsubcategory.SubsubsubcategoryID;
            sqlCommand.Parameters["@SubsubsubcategoryName"].Value    = subsubsubcategory.SubsubsubcategoryName;
            sqlCommand.Parameters["@SubsubsubcategoryNameKey"].Value = subsubsubcategory.SubsubsubcategoryNameKey;
            sqlCommand.Parameters["@CreatedDate"].Value = DateTime.UtcNow;
            //sqlCommand.Parameters["@OrderID"].Value = subsubsubcategory.OrderID;
            sqlCommand.Parameters["@Visible"].Value = subsubsubcategory.Visible;

            // Add output parameters
            SqlParameter objectCount = sqlCommand.Parameters.Add("@ObjectCount", SqlDbType.Int);

            objectCount.Direction = ParameterDirection.Output;

            int insertAccountResult = 0;

            sqlCommand.Connection.OpenWithRetry();

            try
            {
                insertAccountResult = sqlCommand.ExecuteNonQueryWithRetry(); // returns Int indicating number of rows affected
                if (insertAccountResult > 0)
                {
                    response.isSuccess = true;
                }
                else
                {
                    if ((int)objectCount.Value >= maxAllowed)
                    {
                        return(new DataAccessResponseType
                        {
                            isSuccess = false,
                            ErrorMessage = "Your plan does not allow for more than " + maxAllowed + " categories per set. Please upgrade to increase your limits."
                                           //ErrorMessage = "You have reached the maximum amount of subsubsubcategories for this subsubcateory. Please upgrade your plan or contact support to increase your limits."
                        });
                    }
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to insert a application subsubsubcategory into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
                return(response);
            }

            sqlCommand.Connection.Close();

            return(response);
        }
        public JsonNetResult Subsubcategory(string categoryNameKey, string subcategoryNameKey, string subsubcategoryNameKey, string subsubsubcategoryNameKey, 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);
            }

            SubsubsubcategoryModel       subsubsubcategory = null;
            SubsubsubcategoryDetailsJson subsubsubcategoryDetailsObjectJson = null;

            string localCacheKey = accountNameKey + ":subsubsubcategory:" + categoryNameKey + ":" + subcategoryNameKey + ":" + subsubcategoryNameKey + ":" + subsubsubcategoryNameKey + ":includeHidden:" + includeHidden + "includeProducts:" + includeItems;


            #region (Plan A) Get json from local cache

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

            #endregion

            if (subsubsubcategoryDetailsObjectJson == 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)
                    {
                        subsubsubcategoryDetailsObjectJson = JsonConvert.DeserializeObject <SubsubsubcategoryDetailsJson>(redisApiValue);
                        executionType = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (subsubsubcategoryDetailsObjectJson == 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 = categoryNameKey + "/" + subcategoryNameKey + "/" + subsubcategoryNameKey + "/" + subsubsubcategoryNameKey + ":public";

                        if (includeHidden == true)
                        {
                            hashMainField = categoryNameKey + "/" + subcategoryNameKey + "/" + subsubcategoryNameKey + "/" + subsubsubcategoryNameKey + ":private";
                        }

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

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

                    #endregion

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

                        var applicationCategorizationServiceClient = new ApplicationCategorizationService.ApplicationCategorizationServiceClient();

                        try
                        {
                            applicationCategorizationServiceClient.Open();

                            subsubsubcategory = applicationCategorizationServiceClient.GetSubsubsubcategoryByNames(accountNameKey, categoryNameKey, subcategoryNameKey, subsubcategoryNameKey, subsubsubcategoryNameKey, 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 (subsubsubcategoryDetailsObjectJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, subsubsubcategoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (subsubsubcategory != null)
                {
                    //Transform categories into JSON and cache BOTH locally AND into redis
                    subsubsubcategoryDetailsObjectJson = Transforms.Json.CategorizationTransforms.Subsubsubcategory(accountNameKey, subsubsubcategory, includeItems, includeHidden);
                    HttpRuntime.Cache.Insert(localCacheKey, subsubsubcategoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(subsubsubcategoryDetailsObjectJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

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

            //Add execution data
            stopWatch.Stop();
            subsubsubcategoryDetailsObjectJson.executionType = executionType.ToString();
            subsubsubcategoryDetailsObjectJson.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 = subsubsubcategoryDetailsObjectJson;

            return(jsonNetResult);
        }