Esempio n. 1
0
        public static DataAccessResponseType DeletePropertyValue(Account account, PropertyModel property, PropertyValueModel propertyValue)
        {
            var response = new DataAccessResponseType();

            #region Check if property value is currently in use on ANY documents for this account

            #region Get any relevant documents (Legacy)

            /*
             * //Get the DocumentDB Client
             * var client = Sahara.Core.Settings.Azure.DocumentDB.DocumentClients.AccountDocumentClient;
             * //var dbSelfLink = Sahara.Core.Settings.Azure.DocumentDB.AccountPartitionDatabaseSelfLink;
             * client.OpenAsync();
             *
             * string sqlQuery = "SELECT Top 1 * FROM Products p WHERE p.Properties." + property.PropertyName + " = '" + propertyValue.PropertyValueName + "'";
             *
             * //Build a collection Uri out of the known IDs
             * //(These helpers allow you to properly generate the following URI format for Document DB:
             * //"dbs/{xxx}/colls/{xxx}/docs/{xxx}"
             * Uri collectionUri = UriFactory.CreateDocumentCollectionUri(Sahara.Core.Settings.Azure.DocumentDB.AccountPartitionDatabaseId, account.DocumentPartition);
             * //Uri storedProcUri = UriFactory.CreateStoredProcedureUri(Sahara.Core.Settings.Azure.DocumentDB.AccountPartitionDatabaseId, account.DocumentPartition, "UpdateProduct");
             *
             * var document = client.CreateDocumentQuery<Document>(collectionUri.ToString(), sqlQuery).AsEnumerable().FirstOrDefault();
             */
            #endregion

            #endregion

            #region Get any relevant documents (from Search)

            //$filter=tags/any(t: t eq '345')
            string searchFilter = property.SearchFieldName + "/any(s: s eq '" + propertyValue.PropertyValueName + "')";

            var documentSearchResult = ProductSearchManager.SearchProducts(account.SearchPartition, account.ProductSearchIndex, "", searchFilter, "relevance", 0, 1);

            #endregion

            if (documentSearchResult.Count > 0)
            {
                return(new DataAccessResponseType
                {
                    isSuccess = false,
                    ErrorMessage = "Cannot delete a property value that is in use on a product. Please remove all associations before deleting."
                });
            }
            else
            {
                response.isSuccess = Sql.Statements.DeleteStatements.DeletePropertyValue(account.SqlPartition, account.SchemaName, propertyValue.PropertyValueID.ToString());
            }

            if (response.isSuccess)
            {
                //Clear Category Caches:
                Caching.InvalidateAllPropertyCachesForAccount(account.AccountNameKey);
            }

            return(response);
        }
        public MainWindowViewModel()
        {
            SearchCommand = new RelayCommand <string>(DoSearch);

            _productSearchManager = new ProductSearchManager();
            _productSearchManager.ResultsRecieved += ProductSearchManagerResultsRecieved;

            _productSearchRepository = new BestBuyProductRepository();

            ProductImage = BlankImage;
        }
        public MainWindowViewModel()
        {
            SearchCommand = new RelayCommand<string>(DoSearch);

            _productSearchManager = new ProductSearchManager();
            _productSearchManager.ResultsRecieved += ProductSearchManagerResultsRecieved;

            _productSearchRepository = new BestBuyProductRepository();

            ProductImage = BlankImage;
        }
        public void Only_the_most_recent_search_returns_results()
        {
            var    mockRepo            = MockRepository.GenerateMock <IProductSearchRepository <Product> >();
            string lastReturnedProduct = null;
            var    callbacks           = 0;

            mockRepo.Stub(x => x.Search("product1")).Do((Func <string, Product>) delegate
            {
                Thread.Sleep(1000);
                return(new Product("product1Url", "5m"));
            });

            mockRepo.Stub(x => x.Search("product2")).Do((Func <string, Product>) delegate
            {
                Thread.Sleep(200);
                return(new Product("product2Url", "5m"));
            });

            mockRepo.Stub(x => x.Search("product3")).Do((Func <string, Product>) delegate
            {
                Thread.Sleep(500);
                return(new Product("product3Url", "5m"));
            });

            var productSearchManager = new ProductSearchManager();

            productSearchManager.ResultsRecieved += (results) =>
            {
                callbacks++;
                lastReturnedProduct = results.Product.imageUrl;
            };

            productSearchManager.DoSearch("product1", mockRepo);
            productSearchManager.DoSearch("product2", mockRepo);
            productSearchManager.DoSearch("product3", mockRepo);

            Thread.Sleep(5000);

            Assert.AreEqual("product3Url", lastReturnedProduct);
            Assert.AreEqual(1, callbacks);
        }
        public void Only_the_most_recent_search_returns_results()
        {
            var mockRepo = MockRepository.GenerateMock<IProductSearchRepository<Product>>();
            string lastReturnedProduct = null;
            var callbacks = 0;

            mockRepo.Stub(x => x.Search("product1")).Do((Func<string, Product>) delegate
            {
                Thread.Sleep(1000);
                return new Product("product1Url", "5m");
            });

            mockRepo.Stub(x => x.Search("product2")).Do((Func<string, Product>)delegate
            {
                Thread.Sleep(200);
                return new Product("product2Url", "5m");
            });

            mockRepo.Stub(x => x.Search("product3")).Do((Func<string, Product>)delegate
            {
                Thread.Sleep(500);
                return new Product("product3Url", "5m");
            });

            var productSearchManager = new ProductSearchManager();
            productSearchManager.ResultsRecieved += (results) =>
                                                        {
                                                            callbacks++;
                                                            lastReturnedProduct = results.Product.imageUrl;
                                                        };

            productSearchManager.DoSearch("product1", mockRepo);
            productSearchManager.DoSearch("product2", mockRepo);
            productSearchManager.DoSearch("product3", mockRepo);

            Thread.Sleep(5000);

            Assert.AreEqual("product3Url", lastReturnedProduct);
            Assert.AreEqual(1, callbacks);
        }
        public string RenderHTML()
        {
            if (_Cache.ContainsKey(_productID))
            {
                return(_Cache[_productID]);
            }
            ProductQuery query = new ProductQuery();
            Product      pT    = Products.GetProduct(_productID);

            query.ProductNameFilter = pT.ProductName;
            query.PageSize          = Int32.MaxValue;
            query.ProductOrderBy    = ProductOrderBy.DisplayOrder;
            query.SortOrder         = SortOrder.Descending;
            query.PageSize          = int.MaxValue;
            query.HasPublished      = true;
            SearchResultDataSet <Product> ps = ProductSearchManager.Search(query);

            if (ps == null || ps.Records == null || ps.Records.Count == 0 || (ps.Records.Count == 1 && ps.Records[0].ProductID == _productID))
            {
                return("<div class=\"nopiInfo\"><span>没有相关产品信息!</span></div>");
            }
            string         nav      = GlobalSettings.RelativeWebRoot + "pages/view.aspx?product-product";
            List <Product> psList   = null;
            Product        p        = null;
            StringBuilder  sb       = new StringBuilder();
            int            curCount = ps.Records.Count;

            psList = ps.Records.GetRange(0, Math.Min(curCount, _Max));
            sb.AppendLine("<table cellpadding=\"0\" cellspacing=\"0\" class=\"" + _CssClass + "\">");
            string pId    = string.Empty;
            int    length = psList.Count;
            string pn     = string.Empty;

            for (int i = 0; i < psList.Count; i++)
            {
                p = psList[i];
                if (p.ProductID == _productID)
                {
                    continue;
                }
                if (i % _Columns == 0)
                {
                    sb.AppendLine("<tr>");
                }
                pId = GlobalSettings.Encrypt(p.ProductID.ToString());
                sb.AppendLine("<td>");
                sb.AppendLine("<div class=\"piThumbnail\">" +
                              "<a href=\"" + nav + "&ID=" + pId + "\" target=\"_blank\">" +
                              "<div style=\"background-image:url(" + p.GetDefaultImageUrl(100, 100) + ")\" title=\"" + HtmlHelper.RemoveHtml(p.ProductName) + "\" >" +
                              "</div>" +
                              "</a>" +
                              "</div>");
                pn = HtmlHelper.RemoveHtml(p.ProductName);
                sb.AppendLine("<div class=\"piProductName\" title='" + pn + "'>" + GlobalSettings.SubString(pn, 15) + "</div>");
                sb.AppendLine("<div class=\"piPrice\">" + GetPrice(p.ProductID) + "</div>");
                sb.AppendLine("</td>");

                if (i % _Columns == _Columns - 1)
                {
                    sb.AppendLine("</tr>");
                }
            }

            sb.AppendLine("</table>");
            if (!_Cache.ContainsKey(_productID))
            {
                lock (_lock)
                    if (!_Cache.ContainsKey(_productID))
                    {
                        if (_Cache.Count > maxCached)
                        {
                            _Cache.Clear();
                        }
                        _Cache.Add(_productID, sb.ToString());
                    }
            }
            return(sb.ToString());
        }
 public ProductController(ProductManager productManager, ProductSearchManager productSearchManager)
 {
     this.productManager       = productManager;
     this.productSearchManager = productSearchManager;
 }
        public static DataAccessResponseType ProvisionAccount(Account account)
        {
            var response = new DataAccessResponseType();

            #region Pre Provisioning Verification

            bool _documentPartitioning = true;        //<-- If false will skip provisioning DocumentDB resources for accounts
            bool _searchPartitioning   = true;        //<-- If false will skip provisioning Search resources for accounts
            bool _storagePartitioning  = true;        //<-- If false will skip provisioning Search resources for accounts
            bool _sqlPartitioning      = true;        //<-- If false will skip provisioning a SQL Location and SchemeName for accounts

            StoragePartition storagePartition = null; //<-- Chosen partition for this account
            SearchPartition  searchPartition  = null; //<-- Chosen partition for this account

            //Make sure account isn't already provisioned
            if (account.Provisioned)
            {
                response.isSuccess    = false;
                response.ErrorMessage = "Account is already provisioned!";

                return(response);
            }
            if (account.StripeSubscriptionID == null || account.StripeCustomerID == null)
            {
                response.isSuccess    = false;
                response.ErrorMessage = "This account has not been assigned a payment plan or a Stripe CustomerID";

                return(response);
            }

            //If Account object is passed in without users get all/initial user(s):
            if (account.Users == null)
            {
                account.Users = AccountUserManager.GetUsers(account.AccountID.ToString());
            }

            #region Ensure that there is a storage partition available and select next available spot

            if (_storagePartitioning)
            {
                var storagePartitions = StoragePartitioningManager.GetStoragePartitions();


                //Sort with lowest tenant count at the top:
                storagePartitions = storagePartitions.OrderBy(o => o.TenantCount).ToList();

                if (storagePartitions.Count > 0)
                {
                    if (storagePartitions[0].TenantCount >= Settings.Platform.Partitioning.MaximumTenantsPerStorageAccount)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "There are no storage partitions available for this account! Please create one before attempting to provision.";

                        //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                        AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                        return(response);
                    }
                    else
                    {
                        //Assign storage partition:
                        storagePartition = storagePartitions[0];
                    }
                }
                else
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "There are no storage partitions available on this platform! Cannot provision any accounts!";

                    //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                    AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                    return(response);
                }
            }



            #endregion

            #region Ensure that there is a search partition available and select next available spot

            if (_searchPartitioning)
            {
                //Get search plan type for this plan tier
                string searchPlan = account.PaymentPlan.SearchPlan;

                //Get list of search partitions available with this plan type
                var searchPartitions = SearchPartitioningManager.GetSearchPartitions(searchPlan);

                int maxTenantsAllowed = Int32.Parse((searchPlan.Substring(searchPlan.LastIndexOf("-") + 1)));

                /* MAx Tenatnts are now pulled from the SarchPlan name
                 *
                 * int maxTenantsAllowed = 0;
                 *
                 * if(searchPlan == "Basic")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerBasicSearchServiceShared;
                 * }
                 * else if (searchPlan == "Basic-Dedicated")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerBasicSearchServiceDedicated;
                 * }
                 * else if(searchPlan == "S1")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS1SearchServiceShared;
                 * }
                 * else if (searchPlan == "S1-Dedicated")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS1SearchServiceDedicated;
                 * }
                 * else if (searchPlan == "S2")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS2SearchServiceShared;
                 * }
                 * else if (searchPlan == "S2-Dedicated")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerS2SearchServiceDedicated;
                 * }
                 * else if(searchPlan == "Free")
                 * {
                 *  maxTenantsAllowed = Settings.Platform.Partitioning.MaximumTenantsPerFreeSearchService;
                 * }
                 */

                //Sort with lowest tenant count at the top:
                searchPartitions = searchPartitions.OrderBy(o => o.TenantCount).ToList();

                if (searchPartitions.Count > 0)
                {
                    if (searchPartitions[0].TenantCount >= maxTenantsAllowed)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "There are no '" + searchPlan + "' search partitions available for this account! Please create one before attempting to provision.";

                        //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                        AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                        return(response);
                    }
                    else
                    {
                        //Assign storage partition:
                        searchPartition = searchPartitions[0];
                    }
                }
                else
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "There are no '" + searchPlan + "' search partitions available on this platform! Cannot provision any accounts!";

                    //Reset account to inactive so you can restart partitioning sequence after partition hopper has additional partitions added
                    AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), false);

                    return(response);
                }
            }



            #endregion

            #endregion

            #region Account Partitioning

            #region Document Database Partitioning (REMOVED)

            if (_documentPartitioning)
            {
                //Connect to the document client & get the database selfLink
                //var client = Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient;

                //Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient.OpenAsync().ConfigureAwait(false);
                //Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient.OpenAsync();

                //var dataBaseSelfLink = Sahara.Core.Settings.Azure.DocumentDB.AccountPartitionDatabaseSelfLink;

                //STEP 1: Get or create the next available document partition for the 'Free' tier
                var partitioningResult = DocumentPartitioningManager.CreateDocumentCollectionAccountPartition(account.AccountNameKey, Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient, Sahara.Core.Settings.Azure.DocumentDB.AccountPartitionDatabaseId);

                if (partitioningResult.isSuccess == true)
                {
                    DocumentCollection nextAvailablePartitionCollection = (DocumentCollection)partitioningResult.ResponseObject;

                    #region STEP 4: Add Account Settings Document for this account on the collection

                    var       accountSettingsDocumentCreated = false;
                    Exception accountSettingsException       = null;

                    try
                    {
                        var accountSettingsDocument = new AccountSettingsDocumentModel {
                            Id = "AccountSettings"
                        };

                        accountSettingsDocument.ContactSettings             = new ContactSettingsModel();
                        accountSettingsDocument.ContactSettings.ContactInfo = new ContactInfoModel();
                        accountSettingsDocument.SalesSettings = new SalesSettingsModel();

                        //Default LeadLabels
                        accountSettingsDocument.SalesSettings.LeadLabels = new List <string>();
                        accountSettingsDocument.SalesSettings.LeadLabels.Add("New");
                        accountSettingsDocument.SalesSettings.LeadLabels.Add("Archive");
                        accountSettingsDocument.SalesSettings.LeadLabels.Add("Deleted");

                        accountSettingsDocument.Theme = "Light";                                   //<-- Default Theme
                        accountSettingsDocument.SalesSettings.ButtonCopy      = "I'm interested!"; //<-- Default Theme
                        accountSettingsDocument.SalesSettings.DescriptionCopy = "Fill out our contact form and a member of our team will contact you directly.";



                        Sahara.Core.Settings.Azure.DocumentDbClients.AccountDocumentClient.CreateDocumentAsync(nextAvailablePartitionCollection.SelfLink, accountSettingsDocument).ConfigureAwait(false);

                        accountSettingsDocumentCreated = true;
                    }
                    #region Manage Exception & Create Manual Instructions

                    catch (DocumentClientException de)
                    {
                        accountSettingsException = de.GetBaseException();
                    }
                    catch (Exception e)
                    {
                        accountSettingsException = e;
                    }

                    if (!accountSettingsDocumentCreated)
                    {
                        #region Log Exception

                        if (accountSettingsException != null)
                        {
                            PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                                accountSettingsException,
                                "creating an account settings document into a partition during account provisioning",
                                System.Reflection.MethodBase.GetCurrentMethod(),
                                account.AccountID.ToString(),
                                account.AccountName
                                );
                        }


                        #endregion

                        #region Manual Instructions

                        //Not successfull, All tasks within 'GetNextAvailableDocumentPartition' must be run manually
                        PlatformLogManager.LogActivity(
                            CategoryType.ManualTask,
                            ActivityType.ManualTask_DocumentDB,
                            "AccountSettingsDocumentModel file creation failed during account provisioning",
                            "Please create the 'AccountSettingsDocumentModel' document for '" + account.AccountName + "' within the '" + nextAvailablePartitionCollection.Id + "' collection manually.",
                            account.AccountID.ToString(),
                            account.AccountName,
                            null,
                            null,
                            null,
                            null,
                            System.Reflection.MethodBase.GetCurrentMethod().ToString()
                            );

                        #endregion
                    }

                    #endregion

                    #endregion
                }
                else
                {
                    #region Manual Instructions

                    //Not successfull, All tasks within 'GetNextAvailableDocumentPartition' must be run manually
                    PlatformLogManager.LogActivity(
                        CategoryType.ManualTask,
                        ActivityType.ManualTask_Other,
                        "Document partitioning failed during account provisioning",
                        "Please run all tasks under 'DocumentPartitioningManager.GetNextAvailableDocumentPartition('Free', client, dataBaseSelfLink)' as Well as 'if (partitioningResult.isSuccess == true)' manually. This may include creating a new DocumentPartition, updating account DocumentPartitionId and creating an AccountPropertiesDocument for this account into the new partition.",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        System.Reflection.MethodBase.GetCurrentMethod().ToString()
                        );

                    #endregion
                }

                #region Depricated DocumentDB Code

                /*
                 * try
                 * {
                 *  DocumentClient client = Sahara.Core.Settings.Azure.DocumentDB.DocumentClients.AccountDocumentClient;
                 *  client.OpenAsync(); //<-- By default, the first request will have a higher latency because it has to fetch the address routing table. In order to avoid this startup latency on the first request, you should call OpenAsync() once during initialization as follows.
                 *
                 *
                 *  //Generate Account Database
                 *  Database accountDatabase = client.CreateDatabaseAsync(new Database { Id = account.AccountID.ToString() }).Result;
                 *
                 *
                 *  //Generate "AccountProperties" Collection on the database
                 *  DocumentCollection accountPropertiesCollection = client.CreateDocumentCollectionAsync(accountDatabase.SelfLink, new DocumentCollection { Id = "AccountProperties" }).Result;
                 *
                 *
                 *  //Generate "SelfLinkReferences" Document within AccountProperties" collection
                 *  Document selfLinkReferencesDocument = client.CreateDocumentAsync(accountPropertiesCollection.SelfLink, new SelfLinkReferencesDocumentModel { Id = "SelfLinkReferences" }).Result;
                 *
                 *
                 *  //Store all the SelfLinks
                 *  var documentUpdateResults = Sql.Statements.UpdateStatements.UpdateDocumentDatabaseLinks(account.AccountID.ToString(), accountDatabase.SelfLink, accountPropertiesCollection.SelfLink, selfLinkReferencesDocument.SelfLink);
                 *  if (documentUpdateResults)
                 *  {
                 *
                 *  }
                 *  else
                 *  {
                 *
                 *      var errorMessage = "DocumentDB Selflink insertion into the '" + account.AccountName + "' account has failed";
                 *      var errorDetails = "AccountID: '" + account.AccountID + "' Error: 'DocumentDB resources have been provisioned, but an error occured when updating database columns for the account'";
                 *
                 *      //Log Errors
                 *      PlatformLogManager.LogActivity(
                 *              CategoryType.Error,
                 *              ActivityType.Error_Other,
                 *              errorMessage,
                 *              errorDetails,
                 *              account.AccountID.ToString(),
                 *              account.AccountName
                 *          );
                 *
                 *      return new DataAccessResponseType { isSuccess = false, ErrorMessage = errorMessage };
                 *  }
                 * }
                 * catch (Exception e)
                 * {
                 #region Handle Exception
                 *
                 *  //Log exception and email platform admins
                 *  PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                 *      e,
                 *      "attempting to partition DocumentDB resources for the '" + account.AccountName + "' account during provisioning.",
                 *      System.Reflection.MethodBase.GetCurrentMethod(),
                 *      account.AccountID.ToString(),
                 *      account.AccountName
                 *  );
                 *
                 #endregion
                 * }
                 */

                #endregion
            }

            #endregion

            #region Storage Partitioning

            if (_storagePartitioning)
            {
                /* No longer need to set anything up (Back to document db)
                 *
                 * //Create setings JSON doc in storage (DocumentDB is now OFF)
                 * var accountSettingsDocument = new AccountSettingsDocumentModel { Id = "AccountSettings" };
                 *
                 * accountSettingsDocument.ContactSettings = new ContactSettingsModel();
                 * accountSettingsDocument.ContactSettings.ContactInfo = new ContactInfoModel();
                 * accountSettingsDocument.SalesSettings = new SalesSettingsModel();
                 *
                 * //Default LeadLabels
                 * accountSettingsDocument.SalesSettings.LeadLabels = new List<string>();
                 * accountSettingsDocument.SalesSettings.LeadLabels.Add("New");
                 * accountSettingsDocument.SalesSettings.LeadLabels.Add("Archive");
                 * accountSettingsDocument.SalesSettings.LeadLabels.Add("Deleted");
                 *
                 * accountSettingsDocument.Theme = "Light"; //<-- Default Theme
                 * accountSettingsDocument.SalesSettings.ButtonCopy = "I'm interested!"; //<-- Default Theme
                 * accountSettingsDocument.SalesSettings.DescriptionCopy = "Fill out our contact form and a member of our team will contact you directly.";
                 *
                 * //Save to designated storage account
                 * CloudStorageAccount storageAccount;
                 * StorageCredentials storageCredentials = new StorageCredentials(storagePartition.Name, storagePartition.Key);
                 * storageAccount = new CloudStorageAccount(storageCredentials, false);
                 * CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                 *
                 * //Create and set retry policy
                 * IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromMilliseconds(400), 6);
                 * blobClient.DefaultRequestOptions.RetryPolicy = exponentialRetryPolicy;
                 *
                 * //Creat/Connect to the Blob Container for this account
                 * blobClient.GetContainerReference(account.AccountNameKey).CreateIfNotExists(BlobContainerPublicAccessType.Blob); //<-- Create and make public
                 *
                 *
                 * CloudBlobContainer blobContainer = blobClient.GetContainerReference(account.AccountNameKey);
                 *
                 * //Get reference to the text blob or create if not exists.
                 * CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference("settings/" + "accountSettings.json");
                 *
                 * blockBlob.UploadText(JsonConvert.SerializeObject(accountSettingsDocument));
                 *
                 * //Save to storage
                 * //Convert final BMP to byteArray
                 * //Byte[] finalByteArray;
                 *
                 * //finalByteArray = outStream.ToArray();
                 *
                 * //blockBlob.UploadFromByteArray(finalByteArray, 0, finalByteArray.Length);
                 *
                 */
            }

            #endregion

            #region SQL Partitioning

            if (_sqlPartitioning)
            {
                try
                {
                    // 1. Get and assign the next available database partition for this account to be provisioned into:
                    var getAndAssignPartitionResponse = SqlPartitioningManager.GetAndAssignNextAvailableAccountSqlPartition(account.AccountID.ToString());

                    if (getAndAssignPartitionResponse.isSuccess)
                    {
                        string DatabasePartitionName = getAndAssignPartitionResponse.SuccessMessage;

                        // 2. Run creation scripts to provision accounts schema to the selected partition:
                        var generateAccountSchemaResponse = AccountProvisioning.GenerateAccountSchema(account.AccountID.ToString(), DatabasePartitionName);

                        if (generateAccountSchemaResponse.isSuccess)
                        {
                            generateAccountSchemaResponse.SuccessMessage = DatabasePartitionName; //<-- Return the name of the database partition name
                        }
                        else
                        {
                            return(generateAccountSchemaResponse);
                        }
                    }
                    else
                    {
                        return(getAndAssignPartitionResponse);
                    }
                }
                catch (Exception e)
                {
                    #region Handle Exception

                    //Log exception and email platform admins
                    PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                        e,
                        "attempting to partition SQL for the '" + account.AccountName + "' account during provisioning.",
                        System.Reflection.MethodBase.GetCurrentMethod(),
                        account.AccountID.ToString(),
                        account.AccountName
                        );

                    #endregion
                }
            }



            #endregion

            #region Search Partitioning

            if (_searchPartitioning)
            {
                //Create an Product Search Index for this account on the selected search partition ---------------------
                var searchIndexCreated = ProductSearchManager.CreateProductSearchIndex(account.AccountNameKey, searchPartition.Name, searchPartition.Key);
            }

            #endregion

            #endregion

            #region Post Partitioning Tasks

            // 1. Mark the Account as Provisioned, Active and assign a ProvisioningDate:
            var result = Sql.Statements.UpdateStatements.UpdateProvisiongStatus(account.AccountID.ToString(), true, true, storagePartition.Name, searchPartition.Name);


            if (result)
            {
                // 1. Create a platform user account SO we can log into the account for management purposes:
                AccountUserManager.CreateAccountUser(account.AccountID.ToString(), "platformadmin@[Config_PlatformEmail]", "Platform", "Admin", "[Config_PlatformPassword_AzureKeyVault]", Settings.Accounts.Users.Authorization.Roles.PlatformAdmin, true, null, true);

                // 2. Invalidated/Update the cache for this account
                AccountManager.UpdateAccountDetailCache(account.AccountNameKey);

                // 3. Email the creator with sucessful provisioning message and login info:

                /*
                 * EmailManager.Send(
                 *      account.Users[0].Email, //<-- Will only have the initial user
                 *      Settings.Endpoints.Emails.FromProvisioning,
                 *      Settings.Copy.EmailMessages.ProvisioningComplete.FromName,
                 *      Settings.Copy.EmailMessages.ProvisioningComplete.Subject,
                 *      String.Format(Settings.Copy.EmailMessages.ProvisioningComplete.Body, account.AccountNameKey),
                 *      true
                 *  );*/

                // 4. Send an alert to the platform admin(s):
                EmailManager.Send(
                    Settings.Endpoints.Emails.PlatformEmailAddresses,
                    Settings.Endpoints.Emails.FromProvisioning,
                    "Provisioning " + Settings.Application.Name,
                    "Account Provisioned",
                    "<b>'" + account.AccountName + "'</b> has just been provisioned.",
                    true
                    );

                // 5. Log Successfull Provisioning Activity
                PlatformLogManager.LogActivity(CategoryType.Account,
                                               ActivityType.Account_Provisioned,
                                               "Provisioning of '" + account.AccountName + "' has completed",
                                               "AccountID: '" + account.AccountID + "'",
                                               account.AccountID.ToString(), account.AccountName);

                //Register subdomains
                try
                {
                    var cloudFlareResult = CloudFlareManager.RegisterSubdomains(account.AccountNameKey);

                    if (cloudFlareResult.isSuccess == false)
                    {
                        //Log exception and email platform admins
                        PlatformExceptionsHelper.LogErrorAndAlertAdmins(
                            cloudFlareResult.ErrorMessage,
                            "attempting to add cloudflare subdomains for the '" + account.AccountName + "' account during provisioning.",
                            System.Reflection.MethodBase.GetCurrentMethod(),
                            account.AccountID.ToString(),
                            account.AccountName
                            );
                    }
                }
                catch (Exception e)
                {
                    //Log exception and email platform admins
                    PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                        e,
                        "attempting to register cloudflare subdomains for the '" + account.AccountName + "' account during provisioning.",
                        System.Reflection.MethodBase.GetCurrentMethod(),
                        account.AccountID.ToString(),
                        account.AccountName
                        );
                }

                return(new DataAccessResponseType {
                    isSuccess = true
                });
            }
            else
            {
                var errorMessage = "Account has been fully provisioned, but an error occured when setting the Account table to Active and assigning a provisioning date";

                PlatformLogManager.LogActivity(CategoryType.Error,
                                               ActivityType.Error_Other,
                                               "Provisioning of '" + account.AccountName + "' has failed",
                                               errorMessage,
                                               account.AccountID.ToString(), account.AccountName);

                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = errorMessage
                });
            }



            #endregion
        }
    void BindData()
    {
        ProductQuery query = this.Query;

        lnkGrid.PostBackUrl = Request.RawUrl;
        lnkList.PostBackUrl = Request.RawUrl;
        lnkGrid.Attributes.Add("rel", "grid");
        lnkList.Attributes.Add("rel", "list");

        #region -Adapt Show-
        string s = Request.QueryString["s"];
        if (!string.IsNullOrEmpty(s))
        {
            switch (s)
            {
            case "grid":
                lnkGrid.CssClass   = "showByGrid showBy showByGridActive";
                lnkList.CssClass   = "showByList showBy";
                cpProduct.PageSize = 10;
                break;

            case "list":
                lnkList.CssClass   = "showByList showBy showByListActive";
                lnkGrid.CssClass   = "showByGrid showBy";
                cpProduct.PageSize = 50;
                break;
            }
        }
        else
        {
            cpProduct.PageSize = 10;
            s = "grid";
            lnkGrid.CssClass = "showByGrid showBy showByGridActive";
            lnkList.CssClass = "showByList showBy";
        }
        #endregion

        #region -BindData-
        string         sortBy    = Request.QueryString["sortby"];
        ProductOrderBy orderBy   = ProductOrderBy.DisplayOrder;
        SortOrder      sortOrder = SortOrder.Descending;
        if (!string.IsNullOrEmpty(sortBy))
        {
            try
            {
                ddlSortBy.Items.FindByValue(sortBy).Selected = true;
            }
            catch { ddlSortBy.SelectedIndex = 0; }
            GetData(out orderBy, out sortOrder, sortBy);
        }
        query.ProductOrderBy = orderBy;
        query.SortOrder      = sortOrder;
        query.PageSize       = int.MaxValue;
        query.HasPublished   = true;
        List <Product> prods = null;
        if (!IsSearch)
        {
            prods = Products.GetProducts(query).Records;
        }
        else
        {
            if (string.IsNullOrEmpty(query.ProductNameFilter))
            {
                prods = Products.GetProducts(query).Records;
            }
            else
            {
                SearchResultDataSet <Product> _pros = ProductSearchManager.Search(query);
                prods                 = _pros.Records;
                pnlSearch.Visible     = true;
                ltSearchDuration.Text = "搜索用时:" + _pros.SearchDuration.ToString() + "秒。";
            }
        }
        if (prods == null || prods.Count == 0)
        {
            msgBox.ShowMsg("没有符合条件的产品存在!", System.Drawing.Color.Gray);
            return;
        }
        msgBox.HideMsg();
        bool islogin = Context.User.Identity.IsAuthenticated;
        if (orderBy == ProductOrderBy.Price)
        {
            prods.Sort(new SortProductByPrice(sortOrder,
                                              (islogin ? Profile.AccountInfo.UserID : 0),
                                              islogin
                                              ));
        }

        if (s == "grid")
        {
            dlProduct2.Visible      = false;
            dlProduct.Visible       = true;
            cpProduct.DataSource    = prods;
            cpProduct.BindToControl = dlProduct;
            dlProduct.DataSource    = cpProduct.DataSourcePaged;
            dlProduct.DataBind();
        }
        else
        {
            dlProduct.Visible       = false;
            dlProduct2.Visible      = true;
            cpProduct.DataSource    = prods;
            cpProduct.BindToControl = dlProduct2;
            dlProduct2.DataSource   = cpProduct.DataSourcePaged;
            dlProduct2.DataBind();
        }
        #endregion
    }
Esempio n. 10
0
        public static DataAccessResponseType CreateProperty(Account account, string propertyTypeNameKey, string propertyName)
        {
            //TO DO: Always clear/update caches AND update counts!

            var response = new DataAccessResponseType();

            #region Validate Property Name:

            ValidationResponseType propertyNameValidationResponse = ValidationManager.IsValidPropertyName(propertyName);
            if (!propertyNameValidationResponse.isValid)
            {
                response.isSuccess    = false;
                response.ErrorMessage = propertyNameValidationResponse.validationMessage;
                response.ErrorMessages.Add(propertyNameValidationResponse.validationMessage);

                return(response);
            }

            #endregion

            var property = new PropertyModel
            {
                PropertyTypeNameKey = propertyTypeNameKey,
                PropertyID          = Guid.NewGuid(),
                PropertyName        = propertyName,
                PropertyNameKey     = Sahara.Core.Common.Methods.PropertyNames.ConvertToPropertyNameKey(propertyName),
                SearchFieldName     = Sahara.Core.Common.Methods.PropertyNames.ConvertToPropertyNameKey(propertyName, true),
                Facetable           = false,
                Sortable            = false,
                Listing             = false,
                Details             = true
            };

            #region Check if this name already exists

            var propertyExists = GetProperty(account, property.PropertyNameKey);

            if (propertyExists != null)
            {
                response.isSuccess    = false;
                response.ErrorMessage = "A property with that name already exists.";

                return(response);
            }

            #endregion



            response = Sql.Statements.InsertStatements.InsertProperty(account.SqlPartition, account.SchemaName, property);

            var searchUpdateResponse = new DataAccessResponseType();

            if (response.isSuccess)
            {
                //Clear Category Caches:
                Caching.InvalidateAllPropertyCachesForAccount(account.AccountNameKey);

                //Update Search Index Fields
                searchUpdateResponse = ProductSearchManager.AddProductPropertyToSearchIndexFields(account.SearchPartition, account.ProductSearchIndex, property.SearchFieldName, propertyTypeNameKey);
            }

            if (!searchUpdateResponse.isSuccess)
            {
                #region Rollback and send Error

                //Delete the property
                Sql.Statements.DeleteStatements.DeleteProperty(account.SqlPartition, account.SchemaName, property.PropertyID.ToString());

                //Return the error
                return(searchUpdateResponse);

                #endregion
            }

            //Clear Caches & Send Response:
            Caching.InvalidateAllPropertyCachesForAccount(account.AccountNameKey);
            response.SuccessMessage = property.PropertyID.ToString(); //<--Returned for logging purposes

            return(response);
        }