コード例 #1
0
        //------------ Destroy Data ------

        internal static DataAccessResponseType DestroySqlSchemaAndTables(Account account)
        {
            var response = new DataAccessResponseType();

            try
            {
                return(Sql.Statements.StoredProcedures.DestroySchema(account.SchemaName, account.SqlPartition));
            }
            catch (Exception e)
            {
                response.isSuccess    = false;
                response.ErrorMessage = e.Message;

                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to destroy SQL schema and tables for : " + account.AccountName,
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                PlatformLogManager.LogActivity(CategoryType.Error, ActivityType.Error_Exception, "Error destroying schema for: '" + account.AccountName + "' on: ' " + account.SqlPartition + "'", "AccountID: '" + account.AccountID + "' AccountNameKey: '" + account.AccountNameKey + "' Error: '" + e.Message + "'", account.AccountID.ToString(), account.AccountName);
            }

            return(response);
        }
コード例 #2
0
        internal static DataAccessResponseType AssignPartition(string accountID, string sqlPartitionName)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            try
            {
                if (Sql.Statements.UpdateStatements.UpdateSqlPartition(accountID, sqlPartitionName))
                {
                    response.isSuccess = true;

                    return(response);
                }
                else
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "An error occurred while updating the SqlPartition name, or the AccountID does not exist.";

                    return(response);
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to assign partition: " + sqlPartitionName + " to account: " + accountID,
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;

                return(response);
            }
        }
コード例 #3
0
        public static DataAccessResponseType AuthenticateUser(string email, string password)
        {
            var response = new DataAccessResponseType();

            //Verifiy all prameters
            if (string.IsNullOrEmpty(email))
            {
                response.ErrorMessages.Add("Please include an email.");
            }
            if (string.IsNullOrEmpty(password))
            {
                response.ErrorMessages.Add("Please include a password.");
            }

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                response.isSuccess    = false;
                response.ErrorMessage = "Not all parameters contain a value!";
                return(response);
            }


            try
            {
                //Get user with 'Login' info (username + password)
                response = PlatformUserManager.GetUserWithLogin(email, password);

                if (response.isSuccess)
                {
                    var user = (PlatformUserIdentity)response.ResponseObject; //<-- ResponseObject can be converted to PlatformUser by consuming application

                    //Validate that the user is active
                    if (!user.Active)
                    {
                        response.isSuccess = false;
                        response.ErrorMessages.Add("This user is not active.");
                    }


                    return(response);
                }
                else
                {
                    return(response);
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to authenticate platform user with email: " + email,
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = e.Message
                });
            }
        }
        private static bool StoreReminderEmailForCardExpiration(string accountID, string accountName, DateTime CardExirationDate, int daysTillExpiration)
        {
            var cardExirationReminderEmailLog = new CardExpirationEmailRemindersLogTableEntity(accountID, accountName, CardExirationDate, daysTillExpiration);

            TableOperation operation = TableOperation.Insert((cardExirationReminderEmailLog as TableEntity));

            try
            {
                cardExirationReminderEmailLog.cloudTable.Execute(operation);
                return(true);
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to store reminder email for card expiration to table storage",
                    System.Reflection.MethodBase.GetCurrentMethod(),
                    accountID,
                    accountName
                    );

                return(false);
            }
        }
コード例 #5
0
        public static DataAccessResponseType ClearStripeWebhooksLog()
        {
            var response = new DataAccessResponseType();

            try
            {
                int amountOfDays = Sahara.Core.Settings.Platform.GarbageCollection.StripeWebhookEventLogDaysToPurge;

                CloudTableClient cloudTableClient = Sahara.Core.Settings.Azure.Storage.StorageConnections.PlatformStorage.CreateCloudTableClient();

                //Create and set retry policy
                //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4);
                IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 3);
                cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy;

                CloudTable cloudTable = cloudTableClient.GetTableReference("stripewebhookeventslog");

                cloudTable.CreateIfNotExists();

                TableQuery <TableEntity> query = new TableQuery <TableEntity>()
                                                 .Where(TableQuery.GenerateFilterConditionForDate("DateTimeUTC", QueryComparisons.LessThanOrEqual, DateTimeOffset.UtcNow.AddDays(amountOfDays * -1)));

                var stripeWebhooks = cloudTable.ExecuteQuery(query);

                int count = stripeWebhooks.Count();

                foreach (var log in stripeWebhooks)
                {
                    cloudTable.Execute(TableOperation.Delete(log));
                }

                if (count > 0)
                {
                    //Log Garbage Collection
                    PlatformLogManager.LogActivity(
                        CategoryType.GarbageCollection,
                        ActivityType.GarbageCollection_StripeEventLog,
                        "Purged " + count.ToString("#,##0") + " item(s) from the stripe webhook events logs",
                        count.ToString("#,##0") + " stripe webhook event(s) past " + amountOfDays + " days have been purged"
                        );
                }

                response.isSuccess = true;
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to clear stripe webhooks log",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            return(response);
        }
コード例 #6
0
        internal static DataAccessResponseType DestroySchema(string schemaName, string databasePartitionName)
        {
            var response = new DataAccessResponseType();

            //SqlCommand sqlCommand = new SqlCommand("DestroySchema", Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(databasePartitionName));
            SqlCommand sqlCommand = Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(databasePartitionName).CreateCommand();

            sqlCommand.CommandText = "DestroySchema";


            try
            {
                sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

                sqlCommand.Parameters.Add(new SqlParameter("@SchemaName", schemaName));
                sqlCommand.Parameters.Add(new SqlParameter("@WorkTest", 'w'));

                sqlCommand.Connection.OpenWithRetry();

                sqlCommand.ExecuteNonQueryWithRetry();

                sqlCommand.Connection.Close();

                response.isSuccess      = true;
                response.SuccessMessage = "Schema '" + schemaName + "', and all associated object have been destroyed on '" + databasePartitionName + "'";
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to destroy for: " + schemaName,
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                PlatformLogManager.LogActivity(
                    CategoryType.ManualTask,
                    ActivityType.ManualTask_SQL,
                    "Stored Procedure 'DestroySchema' Failed on the '" + databasePartitionName + "' partition for schema '" + schemaName + "'",
                    sqlCommand.ToString(),
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    System.Reflection.MethodBase.GetCurrentMethod().ToString()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            return(response);
        }
コード例 #7
0
        public static DataAccessResponseType DeprovisionClosedAccounts()
        {
            var response = new DataAccessResponseType();

            try
            {
                // 1. Get list of AccountID's that are past their AccountEndDate and have ClosueApproved set to TRUE. These accounts are ready for deprovisioning:
                var accountsToDeprovision = Sql.Statements.SelectStatements.SelectClosedAccountsToDeprovision();
                if (accountsToDeprovision.Count > 0)
                {
                    foreach (string accountID in accountsToDeprovision)
                    {
                        // Get the Account
                        //var account = AccountManager.GetAccountByID(accountID, false);
                        var account = AccountManager.GetAccount(accountID, false, AccountManager.AccountIdentificationType.AccountID);

                        // Delete the account, associated user(s) and all data for each account ID the open up each data partition for future accounts:
                        var deprovisioningResponse = DeprovisioningManager.DeprovisionAccount(account);

                        // Log Custodian Activity
                        //PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_Scheduled_Task,
                        //account.AccountName + " has been deprovisioned. (" + account.AccountID + ") ",
                        //"Check deprovisioning log for details.", account.AccountID.ToString(), account.AccountName);
                    }

                    response.isSuccess      = true;
                    response.SuccessMessage = "Closed account(s) have been deprovisioned, see deprovisioning log for details.";
                }
                else
                {
                    // No accounts to deprovision...
                    response.isSuccess      = true;
                    response.SuccessMessage = "No accounts found for deprovisioning.";

                    // Log (Commented out to make custodian less noisy)
                    //PlatformLogManager.LogActivity(CustodianLogActivity.ScheduledTask, ""No accounts found for deprovisioning.");
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to deprovision closed accounts",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            return(response);
        }
コード例 #8
0
        public static bool ClearAllAssocitedCaches(string userId, string noificationType)
        {
            try
            {
                //ConnectionMultiplexer con = ConnectionMultiplexer.Connect(Sahara.Core.Settings.Azure.Redis.RedisConnections.AccountManager_RedisConfiguration);
                //IDatabase cache = con.GetDatabase();

                //IDatabase cache = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.AccountManager_Multiplexer.GetDatabase();
                IDatabase cache = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.RedisMultiplexer.GetDatabase();

                string userKey = UserHash.Key(userId);

                /*
                 * string allNotificationsUnread = UserHash.Fields.Notifications(NotificationStatus.Unread.ToString());
                 * string allNotificationsRead = UserHash.Fields.Notifications(NotificationStatus.Read.ToString());
                 * string allNotificationsExpiredUnread = UserHash.Fields.Notifications(NotificationStatus.ExpiredUnread.ToString());
                 * string allNotificationsExpiredRead = UserHash.Fields.Notifications(NotificationStatus.ExpiredRead.ToString());
                 * */

                string unreadNotificationsField        = UserHash.Fields.Notifications(noificationType, NotificationStatus.Unread.ToString());
                string readNotificationsField          = UserHash.Fields.Notifications(noificationType, NotificationStatus.Read.ToString());
                string expiredUnreadNotificationsField = UserHash.Fields.Notifications(noificationType, NotificationStatus.ExpiredUnread.ToString());
                string expiredReadNotificationsField   = UserHash.Fields.Notifications(noificationType, NotificationStatus.ExpiredRead.ToString());

                try
                {
                    cache.HashDelete(userKey, unreadNotificationsField, CommandFlags.FireAndForget);
                    cache.HashDelete(userKey, readNotificationsField, CommandFlags.FireAndForget);
                    cache.HashDelete(userKey, expiredUnreadNotificationsField, CommandFlags.FireAndForget);
                    cache.HashDelete(userKey, expiredReadNotificationsField, CommandFlags.FireAndForget);
                }
                catch
                {
                }


                //con.Close();

                return(true);
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to clear all notification caches for: " + userId,
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                return(false);
            }
        }
コード例 #9
0
        public static DataAccessResponseType ClearIntermediaryStorage()
        {
            var response = new DataAccessResponseType();

            var daysAgo = (Sahara.Core.Settings.Platform.GarbageCollection.IntermediaryStorageContainerDaysToPurge * -1);

            try
            {
                //Clients that wish to save source files to intermediary blob storage mush use the following date format to name the container for custodial garbage collection to take place.
                var date          = DateTime.UtcNow.AddDays(daysAgo);
                var containerName = date.ToShortDateString().Replace("/", "-");

                //Delete Storage Containers on Intermediary Labeled from "X" days ago
                CloudBlobClient blobClient = Sahara.Core.Settings.Azure.Storage.StorageConnections.IntermediateStorage.CreateCloudBlobClient();

                //Create and set retry policy
                IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromMilliseconds(500), 8);
                blobClient.DefaultRequestOptions.RetryPolicy = exponentialRetryPolicy;


                if (blobClient.GetContainerReference(containerName).Exists())
                {
                    blobClient.GetContainerReference(containerName).DeleteIfExists();

                    //Log Garbage Collection
                    PlatformLogManager.LogActivity(
                        CategoryType.GarbageCollection,
                        ActivityType.GarbageCollection_IntermediaryStorage,
                        "Purged the '" + containerName + "' intermediary storage container",
                        "An intermediary storage container older than " + Sahara.Core.Settings.Platform.GarbageCollection.IntermediaryStorageContainerDaysToPurge + " days has been purged"
                        );
                }


                response.isSuccess = true;
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to purge intermediary data past " + Sahara.Core.Settings.Platform.GarbageCollection.IntermediaryStorageContainerDaysToPurge + " days old",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            return(response);
        }
コード例 #10
0
        /// <summary>
        /// Gets the next available partition to assign an account to, return partition name in SuccessMessage
        /// </summary>
        /// <returns></returns>
        public static DataAccessResponseType GetAndAssignNextAvailableAccountSqlPartition(string accountID)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            // 1. Get the next partition name:
            string nextPartitionName = SqlPartitioning.GetNextAvailablePartition();

            if (nextPartitionName == String.Empty)
            {
                // 1a. All partitions are full, or none exist. Create a new or initial partition:

                try
                {
                    nextPartitionName = SqlPartitioning.InitializeNewDatabasePartition();
                }
                catch (Exception e)
                {
                    //Log exception and email platform admins
                    PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                        e,
                        "attempting to get and assign next available partition for: " + accountID,
                        System.Reflection.MethodBase.GetCurrentMethod()
                        );

                    response.isSuccess    = false;
                    response.ErrorMessage = e.Message;

                    return(response);
                }

                if (nextPartitionName == String.Empty)
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "Unable to create a new database partition.";

                    return(response);
                }
            }

            //2. Assign the partition to the account:
            var assignPartitionRespone = SqlPartitioning.AssignPartition(accountID, nextPartitionName);

            assignPartitionRespone.SuccessMessage = nextPartitionName; //<--Return name of partition in SuccessMessage

            return(assignPartitionRespone);
        }
コード例 #11
0
        internal static DataAccessResponseType GenerateAccountSchema(string accountID, string databaseName)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            response.isSuccess = false;

            var SqlInitialization = new Initialization();

            try
            {
                /*======================================
                 *    GENERATE SCHEMA & SEED DATA
                 * ========================================*/

                //Run Schema for Account:
                //FYI: .sql Files must be saved as ANSI
                //FYI: .sql Files must be set as "Embedded Resource" & "CopyAlways" in Properties
                //Sql.Statements.InitializationStatements.RunSqlScript("Account_Data_Create.sql", Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(databaseName).ConnectionString, Sahara.Core.Common.SchemaNames.GuidToSchemaName(accountID));
                SqlInitialization.InitializeAccountProvision(Sahara.Core.Common.Methods.SchemaNames.AccountIdToSchemaName(accountID), Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(databaseName).ConnectionString);


                response.isSuccess = true;
            }
            catch (Exception e)
            {
                response.isSuccess    = false;
                response.ErrorMessage = e.Message;

                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to provision account: " + accountID + " into database: " + databaseName,
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );
            }


            return(response);
        }
コード例 #12
0
        /* NOTIFICATIONS OFF
         * public static DataAccessResponseType ProcessSendNotificationToBulkAccounts(string message, string messageType, double expirationDays, bool accountOwnersOnly, string columnName, string columnValue)
         * {
         *  var response = new DataAccessResponseType();
         *  var userIds = new List<string>();
         *
         *  try
         *  {
         *      if (String.IsNullOrEmpty(columnName) && String.IsNullOrEmpty(columnName))
         *      {
         *          //Get list of all userIds from provisioned accounts
         *          userIds = AccountManager.GetUserIDsFromAllProvisionedAccounts(accountOwnersOnly);
         *      }
         *      else
         *      {
         *          //Get a subset of userIds from provisioned accounts based on columnName/Value:
         *          userIds = AccountManager.GetUserIDsFromProvisionedAccountsByFilter(accountOwnersOnly, columnName, columnValue);
         *      }
         *
         *
         *      //Convert messageType to correct Enum:
         *
         *      // string to enum
         *      NotificationType _convertedMesageType = (NotificationType)Enum.Parse(typeof(NotificationType), messageType);
         *
         *      //Convert URL encoded characters back
         *      message = message.Replace("%2C", ",");
         *
         *      foreach (string userId in userIds)
         *      {
         *          try
         *          {
         *              NotificationsManager.SendNotificationToUser(_convertedMesageType, userId, message, expirationDays);
         *          }
         *          catch(Exception e)
         *          {
         *              //Log exception and email platform admins
         *              PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
         *                  e,
         *                  "attempting to process and send notification to bulk accounts: '" + message + "'",
         *                  System.Reflection.MethodBase.GetCurrentMethod()
         *              );
         *          }
         *      }
         *
         *      response.isSuccess = true;
         *      return response;
         *  }
         *  catch (Exception e)
         *  {
         *      //Log exception and email platform admins
         *      PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
         *          e,
         *          "attempting to process and send notification to bulk accounts: '" + message + "'",
         *          System.Reflection.MethodBase.GetCurrentMethod()
         *      );
         *
         *      response.isSuccess = false;
         *      response.ErrorMessage = e.Message;
         *      return response;
         *  }
         *
         *
         *
         * }
         */


        public static DataAccessResponseType ProcessSendEmailToBulkAccounts(string fromEmail, string fromName, string emailSubject, string emailMessage, bool accountOwnersOnly, bool isImportant, string columnName, string columnValue)
        {
            var response = new DataAccessResponseType();
            var emails   = new List <string>();


            //Get all email addresses for users in provisioned accounts
            try
            {
                if (String.IsNullOrEmpty(columnName) && String.IsNullOrEmpty(columnName))
                {
                    //Get list of all provisioned account ids
                    emails = AccountManager.GetUserEmailsFromAllProvisionedAccounts(accountOwnersOnly);
                }
                else
                {
                    //Get a subset of user emails based on the filterString:
                    emails = AccountManager.GetUserEmailsFromProvisionedAccountsByFilter(accountOwnersOnly, columnName, columnValue);
                }

                EmailManager.Send(emails, fromEmail, fromName, emailSubject, emailMessage, true, isImportant);

                response.isSuccess = true;
                return(response);
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to process and send emails to bulk accounts",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
                return(response);
            }
        }
コード例 #13
0
        /* REVISIT FOR PURGE --
         * internal static bool ClearStripeWebhookEventsLog(int amountOfDays)
         * {
         *
         *  CloudTableClient cloudTableClient = Sahara.Core.Settings.Azure.Storage.StorageConnections.PlatformStorage.CreateCloudTableClient();
         *
         *  //Create and set retry policy
         *  //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4);
         *  IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 3);
         *  cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy;
         *
         *  CloudTable cloudTable = cloudTableClient.GetTableReference(StripeWebhookEventsLogTableName);
         *
         *  cloudTable.CreateIfNotExists();
         *
         *  TableQuery<TableEntity> query = new TableQuery<TableEntity>()
         *      .Where(TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.LessThanOrEqual, DateTimeOffset.UtcNow.AddDays(amountOfDays).Date));
         *
         *  var stripeWebhookEventsLog = cloudTable.ExecuteQuery(query);
         *
         *  foreach (var log in stripeWebhookEventsLog)
         *  {
         *      cloudTable.Execute(TableOperation.Delete(log));
         *  }
         *
         *
         *  PlatformLogManager.LogActivity(
         *      CategoryType.StripeEvent,
         *      ActivityType.StripeEvent_IdempotentLogPurged,
         *      "Purge initiated for logs older than " + Math.Abs(amountOfDays) + " days. Resulted in " + stripeWebhookEventsLog.Count() + " purged items.",
         *      stripeWebhookEventsLog.Count() + " logs purged from events over " + Math.Abs(amountOfDays) + " days ago."
         *      );
         *
         *  return true;
         * }*/


        internal static bool LogWebhookEvent(string eventId)
        {
            var stripeWebhookEventsLog = new StripeWebhookEventsLogTableEntity(eventId);

            TableOperation operation = TableOperation.Insert((stripeWebhookEventsLog as TableEntity));

            try
            {
                stripeWebhookEventsLog.cloudTable.Execute(operation);
                return(true);
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to store stripe webhook event log for idempotency purposes",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                return(false);
            }
        }
コード例 #14
0
        public static DataAccessResponseType ClearCreditCardExpirationRemindersLog()
        {
            var response = new DataAccessResponseType();

            try
            {
                //Clear the CreditCardExpirationRemindersLog log for records older than X days
                response.isSuccess = CardExpirationReminderEmailsLogManager.ClearReminderEmailsLog(Sahara.Core.Settings.Platform.GarbageCollection.CreditCardExpirationReminderEmailsLogDaysToPurge);
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to clear credit card expiration reminders log",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            return(response);
        }
コード例 #15
0
        public static DataAccessResponseType CreatePaymentPlan(PaymentPlan paymentPlan)
        {
            var response      = new DataAccessResponseType();
            var stripeManager = new StripeManager();
            var frequencies   = GetPaymentFrequencies();

            #region Validate Input

            //Validate Plan Name
            var validationResponse = ValidationManager.IsValidPaymentPlanName(paymentPlan.PaymentPlanName);

            if (!validationResponse.isValid)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = validationResponse.validationMessage
                });
            }


            if (paymentPlan.MaxCategorizationsPerSet > 80)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Categories cannot be grouped in amounts greater than 80 per set"
                });
            }

            if (paymentPlan.MaxProductsPerSet > 300)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Products cannot be grouped in amounts greater than 300 per set"
                });
            }

            if (paymentPlan.MaxProperties > 160)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 160 properties on an account"
                });
            }

            if (paymentPlan.MaxValuesPerProperty > 60)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 60 values per property on an account"
                });
            }

            if (paymentPlan.MaxTags > 5000)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 5000 tags on an account"
                });
            }

            if (paymentPlan.MaxUsers > 300)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 300 users on an account"
                });
            }

            if (paymentPlan.MaxImageGroups > 60)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 60 image groups on an account"
                });
            }

            if (paymentPlan.MaxImageFormats > 240)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 240 image formats on an account"
                });
            }

            if (paymentPlan.MaxImageGalleries > 30)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 30 image galleries on an account"
                });
            }

            if (paymentPlan.MaxImagesPerGallery > 50)
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot have more than 50 images per gallery on an account"
                });
            }

            #endregion

            #region 1. STRIPE transaction (if applicable)

            if (paymentPlan.MonthlyRate != 0)
            {
                //Add to stripe first, if fails, respond with error and stop the process.
                foreach (PaymentFrequency frequency in frequencies)
                {
                    // We ignore any payment plans that have no cost and or frequencies that are set to 0
                    // Stripe is only used to manage plans that have a cost associated to it above 0.0
                    if (frequency.PaymentFrequencyMonths != 0)
                    {
                        //Create the new Stripe plan ID
                        var id = Sahara.Core.Common.Methods.Billing.GenerateStripePlanID(paymentPlan.PaymentPlanName, frequency.IntervalCount, frequency.Interval);

                        //Check if plan exists in Stripe, return an error if it does
                        if (stripeManager.PlanExists(id).isSuccess)
                        {
                            return(new DataAccessResponseType {
                                isSuccess = false, ErrorMessage = "Plan variant exists on Stripe. Operation aborted."
                            });
                        }

                        //Create the rest of the new Stripe plan
                        var name   = Sahara.Core.Common.Methods.Billing.GenerateStripePlanName(paymentPlan.PaymentPlanName, frequency.PaymentFrequencyName);
                        var amount = Sahara.Core.Common.Methods.Billing.GenerateStripePlanAmountInCents(paymentPlan.MonthlyRate, frequency.PaymentFrequencyMonths, frequency.PriceBreak);

                        try
                        {
                            stripeManager.CreatePlan(
                                id,
                                name,
                                amount,
                                frequency.Interval,
                                frequency.IntervalCount
                                );
                        }
                        catch (Exception e)
                        {
                            //Log exception and email platform admins
                            PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                                e,
                                "attempting to create a payment plan on Stripe",
                                System.Reflection.MethodBase.GetCurrentMethod()
                                );

                            return(new DataAccessResponseType {
                                isSuccess = false, ErrorMessage = "An error occurred while attempting to add a plan varient to Stripe. Operation aborted."
                            });
                        }
                    }
                }
            }
            else
            {
            }

            #endregion

            #region 2. SQL Transaction

            try
            {
                response.isSuccess = Sql.Statements.InsertStatements.InsertPaymentPlan(paymentPlan.PaymentPlanName, paymentPlan.Visible, paymentPlan.MonthlyRate, paymentPlan.MaxUsers,
                                                                                       paymentPlan.MaxCategorizationsPerSet, paymentPlan.MaxProductsPerSet, paymentPlan.MaxProperties, paymentPlan.MaxValuesPerProperty, paymentPlan.MaxTags, paymentPlan.AllowSalesLeads,
                                                                                       paymentPlan.MonthlySupportHours, paymentPlan.AllowLocationData, paymentPlan.AllowCustomOrdering, paymentPlan.AllowThemes, paymentPlan.AllowImageEnhancements, paymentPlan.MaxImageGroups, paymentPlan.MaxImageFormats, paymentPlan.MaxImageGalleries, paymentPlan.MaxImagesPerGallery).isSuccess;
                //Clear the cache and return results:
                PaymentPlanCaching.InvalidateAllCaches();
                return(response);
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to insert a payment plan into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "Stripe transaction was successful, but there was an issue while attempting to add plan to the database. Operation aborted. " + e.Message
                });
            }

            #endregion
        }
コード例 #16
0
        public static DataAccessResponseType AuthenticateUser(string accountName, string email, string password)
        {
            var response = new DataAccessResponseType();


            #region Refactoring Notes

            /*
             * In scenarios where users are only one to an account we make the account name the "UserName"
             * We can then look up the email address associated with the account (or vice versa depending on if it's an email or username login scenario)
             * This lookup data can be cached in Redis
             *
             */

            #endregion


            //Verifiy all prameters
            if (string.IsNullOrEmpty(accountName))
            {
                response.ErrorMessages.Add("Please include an account name.");
            }
            if (string.IsNullOrEmpty(email))
            {
                response.ErrorMessages.Add("Please include an email.");
            }
            if (string.IsNullOrEmpty(password))
            {
                response.ErrorMessages.Add("Please include a password.");
            }

            if (string.IsNullOrEmpty(accountName) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                response.isSuccess    = false;
                response.ErrorMessage = "Not all parameters contain a value!";
                return(response);
            }



            try
            {
                //Get the account associated with the attempted login
                //var account = AccountManager.GetAccountByNameKey(Sahara.Core.Common.AccountNames.ConvertToAccountNameKey(login.AccountName), false);
                var account = AccountManager.GetAccount(accountName, false, AccountManager.AccountIdentificationType.AccountName);


                if (account == null)
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "This account does not exist.";
                    response.ErrorMessages.Add("This account does not exist.");
                    return(response);
                }

                //Deny access if account is marked for closure/deprovisioning
                if (String.IsNullOrEmpty(account.PaymentPlanName))
                {
                    response.isSuccess    = false;
                    response.ErrorMessage = "This account is closed.";
                    response.ErrorMessages.Add("This account is closed.");
                    return(response);
                }

                //Derive UserName from Email + AccountID
                string globalUniqueUserName = Sahara.Core.Common.Methods.AccountUserNames.GenerateGlobalUniqueUserName(email, account.AccountID.ToString());

                //Get user with 'Login' info (username + password)
                response = AccountUserManager.GetUserWithLogin(globalUniqueUserName, password);

                if (response.isSuccess)
                {
                    var user = (AccountUserIdentity)response.ResponseObject; //<-- ResponseObject can be converted to AccountUser by consuming application

                    //Add the Account object to the user:
                    //user.Account = account;

                    if (!account.Provisioned)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "Account is not yet provisioned.";
                        response.ErrorMessages.Add("Account is not yet provisioned. Please try again after you get notice that provisioning is complete.");
                    }
                    if (!account.Active && account.Activated)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "This account is no longer active.";
                        response.ErrorMessages.Add("This account is no longer active.");
                    }


                    //Validate that the user is active
                    if (!user.Active)
                    {
                        response.isSuccess    = false;
                        response.ErrorMessage = "This user is not currently active.";
                        response.ErrorMessages.Add("This user is not currently active.");
                    }


                    return(response);
                }
                else
                {
                    return(response);
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to authenticate: " + email + " on: " + accountName,
                    System.Reflection.MethodBase.GetCurrentMethod(),
                    null,
                    accountName
                    );



                var exceptionResponse = new DataAccessResponseType();

                exceptionResponse.isSuccess    = false;
                exceptionResponse.ErrorMessage = e.Message;

                return(exceptionResponse);
            }
        }
コード例 #17
0
        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
        }
コード例 #18
0
        public DataAccessResponseType InsertNewAccount(RegisterNewAccountModel newAccountModel, Guid newAccountID)
        {
            var response = new DataAccessResponseType {
                isSuccess = false
            };

            StringBuilder SqlStatement = new StringBuilder();

            //TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Pacific SA Standard Time");

            //newAccountModel.Provisioned = false;

            //SQL Statement =============================================================
            SqlStatement.Append("INSERT INTO Accounts (");

            SqlStatement.Append("AccountID,");
            SqlStatement.Append("AccountName,");
            SqlStatement.Append("AccountNameKey,");
            SqlStatement.Append("PhoneNumber,");
            SqlStatement.Append("CreatedDate");

            SqlStatement.Append(") VALUES (");

            //Using parameterized queries to protect against injection
            SqlStatement.Append("@AccountID, ");
            SqlStatement.Append("@AccountName, ");
            SqlStatement.Append("@AccountNameKey, ");
            SqlStatement.Append("@PhoneNumber, ");
            SqlStatement.Append("@CreatedDate");

            SqlStatement.Append(")");

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

            sqlCommand.CommandText = SqlStatement.ToString();



            //Using parameterized queries to protect against injection
            sqlCommand.Parameters.Add("@AccountID", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@AccountName", SqlDbType.NVarChar);
            sqlCommand.Parameters.Add("@AccountNameKey", SqlDbType.NVarChar);
            sqlCommand.Parameters.Add("@PhoneNumber", SqlDbType.NVarChar);
            sqlCommand.Parameters.Add("@CreatedDate", SqlDbType.DateTime);



            sqlCommand.Parameters["@AccountID"].Value      = newAccountID;
            sqlCommand.Parameters["@AccountName"].Value    = newAccountModel.AccountName;
            sqlCommand.Parameters["@AccountNameKey"].Value = Sahara.Core.Common.Methods.AccountNames.ConvertToAccountNameKey(newAccountModel.AccountName);
            sqlCommand.Parameters["@PhoneNumber"].Value    = newAccountModel.PhoneNumber;
            sqlCommand.Parameters["@CreatedDate"].Value    = DateTime.UtcNow; // TimeZoneInfo.ConvertTime(DateTime.Now, timeZoneInfo); //DateTime.Now;

            int insertAccountResult = 0;

            sqlCommand.Connection.OpenWithRetry();

            try
            {
                insertAccountResult = sqlCommand.ExecuteNonQueryWithRetry(); // returns Int indicating number of rows affected
            }
            catch (Exception e)
            {
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "inserting a new account into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod(),
                    newAccountID.ToString(),
                    newAccountModel.AccountName);



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

            sqlCommand.Connection.Close();


            if (insertAccountResult == 1)
            {
                response.isSuccess = true;
            }
            else
            {
                response.ErrorMessage = "SQL result was malformed, check data integrity";
            }

            return(response);
        }
コード例 #19
0
        internal static DataAccessResponseType InsertImageGroup(string sqlPartition, string schemaId, ImageFormatGroupModel imageGroup)//, int maxAllowed) //<-- Removed, now checked above AFTER removing non custom types
        {
            DataAccessResponseType response = new DataAccessResponseType();

            StringBuilder SqlStatement = new StringBuilder();


            //newAccountModel.Provisioned = false;

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

            //Check Row Count ===========================================================
            //SqlStatement.Append("DECLARE @ObjectCount INT ");

            /*
             * SqlStatement.Append("SET @ObjectCount = (SELECT COUNT(*) ");
             * SqlStatement.Append("FROM ");
             * SqlStatement.Append(schemaId);
             * SqlStatement.Append(".ImageGroup) ");
             * SqlStatement.Append("IF @ObjectCount < '");
             * SqlStatement.Append(maxAllowed);
             * SqlStatement.Append("' ");
             * SqlStatement.Append("BEGIN ");
             */

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

            SqlStatement.Append("ImageGroupTypeNameKey,");
            SqlStatement.Append("ImageGroupID,");
            SqlStatement.Append("ImageGroupName,");
            SqlStatement.Append("ImageGroupNameKey, ");
            SqlStatement.Append("CreatedDate");

            SqlStatement.Append(") VALUES (");

            //Using parameterized queries to protect against injection
            SqlStatement.Append("@ImageGroupTypeNameKey, ");
            SqlStatement.Append("@ImageGroupID, ");
            SqlStatement.Append("@ImageGroupName, ");
            SqlStatement.Append("@ImageGroupNameKey, ");
            SqlStatement.Append("@CreatedDate");

            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("@ImageGroupTypeNameKey", SqlDbType.Text);
            sqlCommand.Parameters.Add("@ImageGroupID", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@ImageGroupName", SqlDbType.Text);
            sqlCommand.Parameters.Add("@ImageGroupNameKey", SqlDbType.Text);
            sqlCommand.Parameters.Add("@CreatedDate", SqlDbType.DateTime);

            //Assign values
            sqlCommand.Parameters["@ImageGroupTypeNameKey"].Value = imageGroup.ImageFormatGroupTypeNameKey;
            sqlCommand.Parameters["@ImageGroupID"].Value          = imageGroup.ImageFormatGroupID;
            sqlCommand.Parameters["@ImageGroupName"].Value        = imageGroup.ImageFormatGroupName;
            sqlCommand.Parameters["@ImageGroupNameKey"].Value     = imageGroup.ImageFormatGroupNameKey;
            sqlCommand.Parameters["@CreatedDate"].Value           = DateTime.UtcNow;


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

            int insertResult = 0;

            sqlCommand.Connection.OpenWithRetry();

            try
            {
                insertResult = sqlCommand.ExecuteNonQueryWithRetry(); // returns Int indicating number of rows affected
                if (insertResult > 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 + " image groups. Please upgrade to increase your limits."
                     *      //ErrorMessage = "You have reached the maximum amount of categories for your account. 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 an image group into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

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

            sqlCommand.Connection.Close();

            return(response);
        }
コード例 #20
0
        /*
         *  Yearly plans wth IntervalCount of 1 are the maximum available on Stripe, If weeks are required, some refactoring of business logic will be needed as all UI's and parts of CoreServices use the PaymentFrequencyMonths integer to calculate plan costs and discounts.
         *  PaymentPlans have a MonthlyRate property that is used to calculate against 'Frequencies'. If week-based intervals are required, some refactoring will need to occur.
         *  When a new plan is created (or generated by platform initialization) the associated Stripe PlanId's are generated via the Sahara.Core.Common.Methods.PaymentPlans class. Concatinating 'IntervalCount' + 'Interval' with lowered casing and replacing white spaces with "-" (for each plan/frequency variation).
         */

        #endregion

        #region Get

        #region Lists

        public static List <PaymentPlan> GetPaymentPlans(bool includeHiddenPlans, bool orderByRateAsc, bool useCachedVersion = true)
        {
            try
            {
                List <PaymentPlan> paymentPlansCache = null;
                //IDatabase cache = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.AccountManager_Multiplexer.GetDatabase();
                IDatabase cache          = Sahara.Core.Settings.Azure.Redis.RedisMultiplexers.RedisMultiplexer.GetDatabase();
                string    redisHashField = PaymentPlansHash.Fields.PaymentPlansList(includeHiddenPlans, orderByRateAsc);

                if (useCachedVersion)
                {
                    try
                    {
                        var redisValue = cache.HashGet(PaymentPlansHash.Key, redisHashField);
                        if (redisValue.HasValue)
                        {
                            paymentPlansCache = JsonConvert.DeserializeObject <List <PaymentPlan> >(redisValue);
                        }
                    }
                    catch
                    {
                    }
                }

                if (paymentPlansCache == null)
                {
                    var paymentPlans = Sql.Statements.SelectStatements.SelectPaymentPlans(includeHiddenPlans, orderByRateAsc);

                    //Assign alternate rates:
                    foreach (var paymentPlan in paymentPlans)
                    {
                        paymentPlan.AlternateRates = Internal.AlternateRates.AssignAlternateRates(paymentPlan.MonthlyRate);
                        //paymentPlan.StripeVarients = Internal.AlternateRates.AssignStripeVarients(paymentPlan);
                    }

                    try
                    {
                        //Store into redis cache & return:
                        cache.HashSet(PaymentPlansHash.Key, redisHashField, JsonConvert.SerializeObject(paymentPlans), When.Always, CommandFlags.FireAndForget);
                        //con.Close();
                    }
                    catch
                    {
                    }

                    return(paymentPlans);
                }
                else
                {
                    return(paymentPlansCache);
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to get payment plans",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                //Potential caching error, retry without cache
                var paymentPlans = Sql.Statements.SelectStatements.SelectPaymentPlans(includeHiddenPlans, orderByRateAsc);

                //Assign alternate rates:
                foreach (var paymentPlan in paymentPlans)
                {
                    paymentPlan.AlternateRates = Internal.AlternateRates.AssignAlternateRates(paymentPlan.MonthlyRate);
                }

                return(paymentPlans);
            }
        }
コード例 #21
0
        public static DataAccessResponseType InsertPropertySwatch(string sqlPartition, string schemaId, PropertySwatchModel propertySwatch)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            StringBuilder SqlStatement = new StringBuilder();


            //newAccountModel.Provisioned = false;

            //SQL Statement =============================================================
            SqlStatement.Append("INSERT INTO  ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".PropertySwatch (");

            SqlStatement.Append("PropertyID,");
            SqlStatement.Append("PropertySwatchID,");
            SqlStatement.Append("PropertySwatchImage,");
            SqlStatement.Append("PropertySwatchImageMedium,");
            SqlStatement.Append("PropertySwatchImageSmall,");
            SqlStatement.Append("PropertySwatchLabel,");
            SqlStatement.Append("PropertySwatchNameKey,");
            SqlStatement.Append("CreatedDate, ");
            SqlStatement.Append("Visible");

            SqlStatement.Append(") VALUES (");

            //Using parameterized queries to protect against injection
            SqlStatement.Append("@PropertyID, ");
            SqlStatement.Append("@PropertySwatchID, ");
            SqlStatement.Append("@PropertySwatchImage, ");
            SqlStatement.Append("@PropertySwatchImageMedium, ");
            SqlStatement.Append("@PropertySwatchImageSmall, ");
            SqlStatement.Append("@PropertySwatchLabel, ");
            SqlStatement.Append("@PropertySwatchNameKey, ");
            SqlStatement.Append("@CreatedDate, ");
            SqlStatement.Append("@Visible");

            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();



            //Using parameterized queries to protect against injection
            sqlCommand.Parameters.Add("@PropertyID", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@PropertySwatchID", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@PropertySwatchImage", SqlDbType.Text);
            sqlCommand.Parameters.Add("@PropertySwatchImageMedium", SqlDbType.Text);
            sqlCommand.Parameters.Add("@PropertySwatchImageSmall", SqlDbType.Text);
            sqlCommand.Parameters.Add("@PropertySwatchLabel", SqlDbType.Text);
            sqlCommand.Parameters.Add("@PropertySwatchNameKey", SqlDbType.Text);
            sqlCommand.Parameters.Add("@CreatedDate", SqlDbType.DateTime);
            sqlCommand.Parameters.Add("@Visible", SqlDbType.Bit);

            //Assign values
            sqlCommand.Parameters["@PropertyID"].Value                = propertySwatch.PropertyID;
            sqlCommand.Parameters["@PropertySwatchID"].Value          = propertySwatch.PropertySwatchID;
            sqlCommand.Parameters["@PropertySwatchImage"].Value       = propertySwatch.PropertySwatchImage;
            sqlCommand.Parameters["@PropertySwatchImageMedium"].Value = propertySwatch.PropertySwatchImageMedium;
            sqlCommand.Parameters["@PropertySwatchImageSmall"].Value  = propertySwatch.PropertySwatchImageSmall;
            sqlCommand.Parameters["@PropertySwatchLabel"].Value       = propertySwatch.PropertySwatchLabel;
            sqlCommand.Parameters["@PropertySwatchNameKey"].Value     = propertySwatch.PropertySwatchNameKey;
            sqlCommand.Parameters["@CreatedDate"].Value               = DateTime.UtcNow;
            sqlCommand.Parameters["@Visible"].Value = propertySwatch.Visible;

            int insertAccountResult = 0;

            sqlCommand.Connection.OpenWithRetry();

            try
            {
                insertAccountResult = sqlCommand.ExecuteNonQueryWithRetry(); // returns Int indicating number of rows affected
                if (insertAccountResult > 0)
                {
                    response.isSuccess = true;
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to insert a property value into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

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

            sqlCommand.Connection.Close();

            return(response);
        }
コード例 #22
0
        internal static DataAccessResponseType InsertApiKey(string sqlPartition, string schemaId, ApiKeyModel key)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            StringBuilder SqlStatement = new StringBuilder();

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


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

            SqlStatement.Append("ApiKey,");
            SqlStatement.Append("Name,");
            SqlStatement.Append("Description,");
            SqlStatement.Append("CreatedDate");

            SqlStatement.Append(") VALUES (");

            //Using parameterized queries to protect against injection
            SqlStatement.Append("@ApiKey, ");
            SqlStatement.Append("@Name, ");
            SqlStatement.Append("@Description, ");
            SqlStatement.Append("@CreatedDate");

            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("@ApiKey", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@Name", SqlDbType.Text);
            sqlCommand.Parameters.Add("@Description", SqlDbType.Text);
            sqlCommand.Parameters.Add("@CreatedDate", SqlDbType.DateTime);

            //Assign values
            sqlCommand.Parameters["@ApiKey"].Value      = key.ApiKey;
            sqlCommand.Parameters["@Name"].Value        = key.Name;
            sqlCommand.Parameters["@Description"].Value = key.Description;
            sqlCommand.Parameters["@CreatedDate"].Value = DateTime.UtcNow;


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

            int insertResult = 0;

            sqlCommand.Connection.OpenWithRetry();

            try
            {
                insertResult = sqlCommand.ExecuteNonQueryWithRetry(); // returns Int indicating number of rows affected
                if (insertResult > 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 + " image groups. Please upgrade to increase your limits."
                     *      //ErrorMessage = "You have reached the maximum amount of categories for your account. 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 new api key into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

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

            sqlCommand.Connection.Close();

            return(response);
        }
コード例 #23
0
        public static DataAccessResponseType SendCreditCardExpirationReminders()
        {
            var response = new DataAccessResponseType();

            try
            {
                foreach (int daysTillExpiration in Sahara.Core.Settings.Platform.Custodian.Dunning.ReminderDaysTillCardExpiration)
                {
                    var timeLeftDescription = string.Empty;

                    // 1. Get list of AccountID's that have a credit card within the window of time for this expiration reminder:
                    var accountsToRemind = Sql.Statements.SelectStatements.SelectAccountIDsForCreditCardExpirationReminders(daysTillExpiration);

                    if (accountsToRemind.Count > 0)
                    {
                        foreach (string accountID in accountsToRemind)
                        {
                            //Check email reminders log to see if this reminder epiration has already been sent to the account:
                            bool emailReminderSent = CardExpirationReminderEmailsLogManager.HasEmailBeenSent(accountID, daysTillExpiration);

                            if (!emailReminderSent)
                            {
                                //Get the account
                                //var account = AccountManager.GetAccountByID(accountID, false);
                                var account = AccountManager.GetAccount(accountID);

                                #region Generate Time Left Description

                                if (daysTillExpiration < 0)
                                {
                                    // description not used
                                }
                                else if (daysTillExpiration > 0 && daysTillExpiration <= 1)
                                {
                                    timeLeftDescription = "in about a day";
                                }
                                else if (daysTillExpiration > 1 && daysTillExpiration <= 2)
                                {
                                    timeLeftDescription = "in a couple of days";
                                }
                                else if (daysTillExpiration > 2 && daysTillExpiration <= 3)
                                {
                                    timeLeftDescription = "in a few days";
                                }
                                else if (daysTillExpiration > 3 && daysTillExpiration <= 5)
                                {
                                    timeLeftDescription = "this week";
                                }
                                else if (daysTillExpiration > 5 && daysTillExpiration <= 12)
                                {
                                    timeLeftDescription = "next week";
                                }
                                else if (daysTillExpiration > 12 && daysTillExpiration <= 15)
                                {
                                    timeLeftDescription = "in a couple of weeks";
                                }
                                else if (daysTillExpiration > 15 && daysTillExpiration <= 30)
                                {
                                    timeLeftDescription = "this month";
                                }
                                else if (daysTillExpiration > 30 && daysTillExpiration <= 62)
                                {
                                    timeLeftDescription = "next month";
                                }
                                else if (daysTillExpiration > 62 && daysTillExpiration <= 92)
                                {
                                    timeLeftDescription = "in a couple of months";
                                }
                                else if (daysTillExpiration > 92 && daysTillExpiration <= 180)
                                {
                                    timeLeftDescription = "in a few months";
                                }
                                else
                                {
                                    timeLeftDescription = "soon";
                                }

                                #endregion

                                if (daysTillExpiration < 0)
                                {
                                    //After the expiration occurs we send a more alarming message from ALERTS
                                    AccountManager.SendEmailToAccount(
                                        accountID,
                                        Settings.Endpoints.Emails.FromAlerts,
                                        Settings.Copy.EmailMessages.CreditCardExpirationMessage.FromName,
                                        Settings.Copy.EmailMessages.CreditCardExpirationMessage.Subject,
                                        String.Format(Settings.Copy.EmailMessages.CreditCardExpirationMessage.Body, account.AccountName, account.AccountNameKey),
                                        true,
                                        true
                                        );

                                    //We also send platform admins an email
                                    EmailManager.Send(
                                        Sahara.Core.Settings.Endpoints.Emails.PlatformEmailAddresses,
                                        Sahara.Core.Settings.Endpoints.Emails.FromPlatform,
                                        "Account Credit Card Expired",
                                        "An accounts credit card has expired!",
                                        "The <b>" + account.AccountName + "</b> account has an expired credit card. Please reach out to them manually to avoid potential billing issues.",
                                        true,
                                        true
                                        );
                                }
                                else
                                {
                                    //If time remains we send a friendly reminder from REMINDERS
                                    AccountManager.SendEmailToAccount(
                                        accountID,
                                        Settings.Endpoints.Emails.FromReminders,
                                        Settings.Copy.EmailMessages.CreditCardExpirationReminder.FromName,
                                        Settings.Copy.EmailMessages.CreditCardExpirationReminder.Subject,
                                        String.Format(Settings.Copy.EmailMessages.CreditCardExpirationReminder.Body, account.AccountName, timeLeftDescription, account.AccountNameKey),
                                        true,
                                        true
                                        );
                                }



                                //Log activity

                                /*
                                 * PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_CardExpirationReminder_EmailSent,
                                 *  account.AccountName +
                                 *  " (" + account.AccountID.ToString() +
                                 *  ") was sent a " + daysTillExpiration + " day credit card expiration reminder.",
                                 *  "",account.AccountID.ToString(), account.AccountName);*/
                            }
                        }

                        response.isSuccess = true;
                    }
                    else
                    {
                        // No accounts to email...
                        response.isSuccess      = true;
                        response.SuccessMessage = "No accounts to remind for ";
                    }
                }

                response.isSuccess = true;
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to send credit card expiration reminders",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            return(response);
        }
コード例 #24
0
        public static bool CreateProductSearchIndex(string accountNamekey, string searchPartitionName, string searchPartitionKey)
        {
            bool result = false;

            try
            {
                //SearchServiceClient searchServiceClient = Settings.Azure.Search.AccountsSearchServiceClient;
                SearchServiceClient searchServiceClient = new SearchServiceClient(searchPartitionName, new SearchCredentials(searchPartitionKey));

                //Create the Data Source (Removed - now updated manually)  ----------------------------
                #region (Removed - now updated manually)

                /*
                 * DataSource datasource = new DataSource
                 * {
                 *  Name = Common.Methods.Strings.ConvertDocumentCollectionNameToSearchDataSourceName(documentPartitionId),
                 *  Type = "documentdb",
                 *  Container = new DataContainer
                 *  {
                 *      Name = documentPartitionId,
                 *      Query = "SELECT p.id, p.AccountID, p.AccountNameKey, p.DocumentType, p.Name, p.NameKey, p.LocationPath, p.FullyQualifiedName, p.Visible, p.Tags, p.IndexedProperties, p._ts FROM Products p WHERE p._ts > @HighWaterMark AND p.DocumentType = 'Product'"
                 *  },
                 *  DataChangeDetectionPolicy = new HighWaterMarkChangeDetectionPolicy { HighWaterMarkColumnName = "_ts" },
                 *  DataDeletionDetectionPolicy = new SoftDeleteColumnDeletionDetectionPolicy { SoftDeleteColumnName = "isDeleted", SoftDeleteMarkerValue = "true" },
                 *  Credentials = new DataSourceCredentials
                 *  {
                 *      ConnectionString = "AccountEndpoint=" + Settings.Azure.DocumentDB.ReadOnlyAccountName + ";AccountKey=" + Settings.Azure.DocumentDB.ReadOnlyAccountKey + ";Database=" + Settings.Azure.DocumentDB.AccountPartitionDatabaseId
                 *  }
                 *
                 * };
                 *
                 * var datasourceCreated = searchServiceClient.DataSources.Create(datasource);
                 */
                #endregion


                //Create Index -----------------------------------
                Microsoft.Azure.Search.Models.Index index = new Microsoft.Azure.Search.Models.Index
                {
                    Name = accountNamekey // + "-products"
                };

                index.Fields = new List <Field>();

                index.Fields.Add(new Field {
                    Name = "id", Type = Microsoft.Azure.Search.Models.DataType.String, IsKey = true, IsFilterable = true
                });

                //index.Fields.Add(new Field { Name = "AccountID", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, });
                //index.Fields.Add(new Field { Name = "AccountNameKey", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true });

                //index.Fields.Add(new Field { Name = "DocumentType", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true });
                index.Fields.Add(new Field {
                    Name = "name", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });
                index.Fields.Add(new Field {
                    Name = "nameKey", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true
                });

                index.Fields.Add(new Field {
                    Name = "locationPath", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true
                });

                index.Fields.Add(new Field {
                    Name = "fullyQualifiedName", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });

                index.Fields.Add(new Field {
                    Name = "categoryName", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });
                index.Fields.Add(new Field {
                    Name = "categoryNameKey", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });

                index.Fields.Add(new Field {
                    Name = "subcategoryName", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });
                index.Fields.Add(new Field {
                    Name = "subcategoryNameKey", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });

                index.Fields.Add(new Field {
                    Name = "subsubcategoryName", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });
                index.Fields.Add(new Field {
                    Name = "subsubcategoryNameKey", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });

                index.Fields.Add(new Field {
                    Name = "subsubsubcategoryName", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });
                index.Fields.Add(new Field {
                    Name = "subsubsubcategoryNameKey", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = true, IsSortable = true, IsSearchable = true
                });

                index.Fields.Add(new Field {
                    Name = "dateCreated", Type = Microsoft.Azure.Search.Models.DataType.DateTimeOffset, IsFilterable = true, IsSortable = true, IsFacetable = true, IsSearchable = false
                });                                                                                                                                                                                                   //<-- Dates cannot be searchable

                index.Fields.Add(new Field {
                    Name = "visible", Type = Microsoft.Azure.Search.Models.DataType.Boolean, IsFilterable = true
                });

                index.Fields.Add(new Field {
                    Name = "orderId", Type = Microsoft.Azure.Search.Models.DataType.Int32, IsSortable = true, IsFacetable = false, IsSearchable = false, IsFilterable = false
                });

                index.Fields.Add(new Field {
                    Name = "tags", Type = Microsoft.Azure.Search.Models.DataType.Collection(Microsoft.Azure.Search.Models.DataType.String), IsFilterable = true, IsSearchable = true, IsFacetable = true
                });

                // -- Depricated in favor of new property creaions as needed
                //index.Fields.Add(new Field { Name = "Properties", Type = Microsoft.Azure.Search.Models.DataType.Collection(Microsoft.Azure.Search.Models.DataType.String), IsFilterable = true, IsSearchable = true }); //<-- PropertyName:PropertyValue

                // -- Depricated in favor of brnging in images after search results are created
                //index.Fields.Add(new Field { Name = "thumbnails", Type = Microsoft.Azure.Search.Models.DataType.Collection(Microsoft.Azure.Search.Models.DataType.String), IsFilterable = false, IsSearchable = false }); //<-- ThumbnailName:URL
                //index.Fields.Add(new Field { Name = "images", Type = Microsoft.Azure.Search.Models.DataType.Collection(Microsoft.Azure.Search.Models.DataType.String), IsFilterable = false, IsSearchable = false }); //<-- ThumbnailName:URL

                var indexResult = searchServiceClient.Indexes.Create(index);

                //Create Indexer (Removed - now updated manually) ---------------------------------
                #region (Removed - now updated manually)

                /*
                 * Indexer indexer = new Indexer
                 * {
                 *  Name = containerShortName + "-indexer",
                 *
                 *  Schedule = new IndexingSchedule
                 *  {
                 *      Interval = new TimeSpan(0, 5, 0),
                 *      StartTime = DateTime.UtcNow
                 *  },
                 *  DataSourceName = datasource.Name,
                 *  //Description = "",
                 *  TargetIndexName = index.Name
                 *  //Parameters = new IndexingParameters
                 *  //{
                 *
                 *  //},
                 * };
                 *
                 * searchServiceClient.Indexers.Create(indexer);
                 */
                #endregion

                if (indexResult != null)
                {
                    result = true;
                }
            }
            catch (Exception e)
            {
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to create product search index for '" + accountNamekey + "'",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                PlatformLogManager.LogActivity(
                    CategoryType.ManualTask,
                    ActivityType.ManualTask_Search,
                    "Product search index creation failed for '" + accountNamekey + "'",
                    "You may need to manually create product search index for '" + accountNamekey + "'",
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    System.Reflection.MethodBase.GetCurrentMethod().ToString()
                    );
            }

            return(result);
        }
コード例 #25
0
        public static DataAccessResponseType DeletePaymentPlan(string paymentPlanName)
        {
            var stripeManager = new StripeManager();
            var paymentPlan   = GetPaymentPlan(paymentPlanName);
            var frequencies   = GetPaymentFrequencies();

            #region Validate Plan Deletion

            if (paymentPlanName.ToLower() == "unprovisioned")
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot delete the unprovisioned plan."
                });
            }

            if (paymentPlanName.ToLower().Contains("trial") || paymentPlanName.ToLower().Contains("free"))
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot delete the Free or Trial plans."
                });
            }

            //Check if any accounts belong to the plan on SQL before deleting
            if (Sql.Statements.SelectStatements.AccountsWithPlanExists(paymentPlanName))
            {
                return(new DataAccessResponseType {
                    isSuccess = false, ErrorMessage = "You cannot delete a plan that has accounts associated to it."
                });
            }

            #endregion


            #region 1. Delete each plan/frequency varient on Stripe (if applicable)

            if (paymentPlan.MonthlyRate != 0)
            {
                //If paid account, delete each varient (only paid accounts are on Stripe)
                foreach (var frequency in frequencies)
                {
                    if (frequency.PaymentFrequencyMonths != 0)
                    {
                        try
                        {
                            stripeManager.DeletePlan(Common.Methods.Billing.GenerateStripePlanID(paymentPlan.PaymentPlanName, frequency.IntervalCount, frequency.Interval));
                        }
                        catch (Exception e)
                        {
                            //Log exception and email platform admins
                            PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                                e,
                                "attempting to delete a payment plan on Stripe",
                                System.Reflection.MethodBase.GetCurrentMethod()
                                );
                        }
                    }
                }
            }

            #endregion

            #region 2. Delete the plan on SQL

            try
            {
                var isSuccess = Sql.Statements.DeleteStatements.DeletePlan(paymentPlanName);

                //Clear the cache and return results:
                PaymentPlanCaching.InvalidateAllCaches();
                return(new DataAccessResponseType {
                    isSuccess = isSuccess
                });
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to delete a payment plan in SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                return(new DataAccessResponseType
                {
                    isSuccess = false,
                    ErrorMessage = "An error occured while attempting to delete the plan on the databse. " + e.Message,
                });
            }

            #endregion
        }
コード例 #26
0
        public static DataAccessResponseType RegisterNewAccount(RegisterNewAccountModel model)
        {
            //trim the name of whitespaces (start & end):
            model.AccountName = model.AccountName.Trim();

            #region Refactoring notes

            /*
             *
             *  With some refactoring you can start them directly with a chosen payment plan by passing a planid parameter to the Registration site (and ultimatly into this method) along with C.C. info
             *
             *  This method will then check for a MonthlyRate > 0 and attempt to process the C.C.
             *  note: You would only add a Credit Card capture form to the Registration site if a plan with a MonthlyRate above 0 is selected -->
             *
             *
             *
             *  -- Adding a new "AllowRegistration" bool to the PaymentPlan object will allow for validation of selected plans coming in from users on this method for scenarios where users can choose a plan while signing up to avoid passing in ID's for plans such as "Unlimited" which must be approved by a Platform Admin
             *
             */

            #endregion

            var response = new DataAccessResponseType {
                isSuccess = true
            };

            try
            {
                #region Validate Account Info
                //Validate Registration Data:

                #region Refactoring notes

                /*
                 *
                 *
                 *  -- Adding a new "AllowRegistration" bool to the PaymentPlan object will allow for validation of selected plans coming in from users on AccountRegistrationManager for scenarios where users can choose a plan while signing up to avoid passing in ID's for plans such as "Unlimited" which must be approved by a Platform Admin
                 *
                 *              > response.ErrorMessages.Add("Not a valid payment plan for public registration");
                 *
                 */

                #endregion


                #region Validate Password(s) Match
                if (model.Password != model.ConfirmPassword)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add("Password and password confirmation do not match");
                }
                #endregion

                #region Validate Account Name:

                ValidationResponseType accountNameValidationResponse = ValidationManager.IsValidAccountName(model.AccountName);
                if (!accountNameValidationResponse.isValid)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add(accountNameValidationResponse.validationMessage);

                    //return response;
                }

                #endregion

                #region Validate User Name

                ValidationResponseType firstNameValidationResponse = ValidationManager.IsValidFirstName(model.FirstName);
                if (!firstNameValidationResponse.isValid)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add(firstNameValidationResponse.validationMessage);

                    //return response;
                }

                ValidationResponseType lastNameValidationResponse = ValidationManager.IsValidLastName(model.LastName);
                if (!lastNameValidationResponse.isValid)
                {
                    response.isSuccess = false;

                    response.ErrorMessages.Add(lastNameValidationResponse.validationMessage);

                    //return response;
                }

                #endregion


                #region Validate Email Unique (Optional)

                /*
                 * var userValidation = AccountUserManager.GetUserIdentity(model.Email);
                 * if (userValidation != null)
                 * {
                 *  response.isSuccess = false;
                 *  response.ErrorMessages.Add("Another account is associated with that email address, please provide another");
                 * }
                 */

                #endregion


                //If validation(s) fails, return the response:
                if (response.isSuccess == false)
                {
                    //Log Platform Activity
                    string errors = string.Empty;

                    foreach (string error in response.ErrorMessages)
                    {
                        errors += error + "|";
                    }

                    PlatformLogManager.LogActivity(CategoryType.Registration,
                                                   ActivityType.Registration_Failed,
                                                   String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                   String.Format("Errors:{0}", errors
                                                                 ));

                    //Return the response
                    response.ErrorMessage = "Could not register this account";
                    return(response);
                }

                #endregion


                // Generate AccountID ====================================
                Guid accountId = Guid.NewGuid();

                #region Register Initial AccountUser (AKA: AccountOwner)


                #region Validate & Create Account Owner User

                // Further validations and account owner creation:

                var registerUserResponse = AccountUserManager.RegisterAccountOwner(
                    model.FirstName,
                    model.LastName,
                    accountId.ToString(),
                    model.AccountName,
                    model.Email,
                    model.Password
                    );

                #endregion

                if (!registerUserResponse.isSuccess)
                {
                    //Log Platform Activity
                    string errors = string.Empty;

                    foreach (string error in registerUserResponse.ErrorMessages)
                    {
                        errors += error + "|";
                    }

                    PlatformLogManager.LogActivity(CategoryType.Registration,
                                                   ActivityType.Registration_Failed,
                                                   String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                   String.Format("Errors:{0}", errors
                                                                 ));

                    //Return the response
                    response.isSuccess    = false;
                    response.ErrorMessage = registerUserResponse.ErrorMessage;

                    response.ErrorMessages = registerUserResponse.ErrorMessages;

                    return(response);
                }

                //Get user back from result
                var user = (AccountUserIdentity)registerUserResponse.ResponseObject;

                #endregion

                #region Create Account

                try
                {
                    // Create Accounts =============================================================

                    InsertStatements insertStatements = new InsertStatements();
                    var insertResult = insertStatements.InsertNewAccount(model, accountId);

                    if (insertResult.isSuccess)
                    {
                        // (Optional) for certain scenrios
                        //Add user to account, make them the owner, and assign them as SuperAdmin role:
                        //AccountManager.AddUserToAccount(user.Id, AccountID.ToString(), true); // <-- Only for certain scenarios

                        response.isSuccess      = true;
                        response.SuccessMessage = Sahara.Core.Settings.Copy.PlatformMessages.AccountRegistration.SuccessMessage;

                        var origin = "";
                        if (model.Origin != null)
                        {
                            origin = "<br/><br/><b>Origin:</b> " + model.Origin;
                        }

                        var name  = "<br/><br/><b>Name:</b> " + model.FirstName + " " + model.LastName;
                        var email = "<br/><br/><b>Email:</b> " + model.Email;

                        var phone = "";
                        if (model.PhoneNumber != null)
                        {
                            phone = "<br/><br/><b>Phone:</b> " + model.PhoneNumber;
                        }

                        try
                        {
                            //Send an alert to the platform admin(s):
                            EmailManager.Send(
                                Settings.Endpoints.Emails.PlatformEmailAddresses,
                                Settings.Endpoints.Emails.FromRegistration,
                                "Registration",
                                "New Registrant",
                                "A new account named <b>'" + model.AccountName + "'</b> has just been registered." + name + email + phone + origin,
                                true
                                );
                        }
                        catch
                        {
                        }

                        //Log The Activity ------------ :
                        //PlatformLogManager.LogActivity(CategoryType.Registration,
                        //ActivityType.Registration_Succeeded,
                        //String.Format("Registration completed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                        //String.Format("Name:'{0}', Email:'{1}', Origin:{2}", model.AccountName, model.Email, model.Origin));

                        PlatformLogManager.LogActivity(CategoryType.Account,
                                                       ActivityType.Account_Registered,
                                                       String.Format("Registration completed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                       String.Format("Name:'{0}', Email:'{1}', Origin:{2}", model.AccountName, model.Email, model.Origin),
                                                       accountId.ToString(),
                                                       model.AccountName,
                                                       null,
                                                       null,
                                                       null,
                                                       null,
                                                       model.Origin);


                        return(response);
                    }
                    else
                    {
                        #region Error Handling
                        string error = insertResult.ErrorMessage;

                        AccountUser outUser = null;

                        //rollback user creation:
                        AccountUserManager.DeleteUser(user.Id, false, out outUser);

                        //Log The Activity ------------ :
                        PlatformLogManager.LogActivity(CategoryType.Registration,
                                                       ActivityType.Registration_Failed,
                                                       String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                                       String.Format("Error:{0}", error));

                        //PlatformLogManager.LogActivity(ErrorLogActivity.PlatformError,
                        //String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                        //String.Format("Error:{0}", error));


                        response.isSuccess    = false;
                        response.ErrorMessage = error;

                        response.ErrorMessages.Add(error);

                        return(response);

                        #endregion
                    }
                }
                catch (Exception e)
                {
                    #region Error Handling
                    string error = String.Empty;

                    AccountUser outUser = null;

                    //rollback user creation:
                    AccountUserManager.DeleteUser(user.Id, false, out outUser);

                    try
                    {
                        error = e.Message;
                    }
                    catch
                    {
                        error = "An error occured";
                    }

                    //rollback user:
                    //To Do: AccountUserManager.DeleteUser(model.Email);

                    string errorDetails = String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin);

                    //Log The Error(s) ------------ :
                    PlatformLogManager.LogActivity(CategoryType.Registration,
                                                   ActivityType.Registration_Error,
                                                   errorDetails,
                                                   String.Format("Error:{0}", error));



                    PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                        e,
                        "registering a new account for " + model.AccountName + " / " + model.Email + " / " + model.FirstName + " " + model.LastName + " from: " + model.Origin,
                        System.Reflection.MethodBase.GetCurrentMethod());


                    response.isSuccess    = false;
                    response.ErrorMessage = error;

                    response.ErrorMessages.Add(error);

                    return(response);

                    #endregion
                }



                #endregion
            }
            catch (Exception e)
            {
                //Log The Error(s) ------------ :
                PlatformLogManager.LogActivity(CategoryType.Registration,
                                               ActivityType.Registration_Error,
                                               String.Format("Registration failed for: '{0}' by: {1} from: {2}", model.AccountName, model.Email, model.Origin),
                                               String.Format("Error:{0}", e.Message));



                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "registering a new account for " + model.AccountName + " / " + model.Email + " / " + model.FirstName + " " + model.LastName + " from: " + model.Origin,
                    System.Reflection.MethodBase.GetCurrentMethod());



                response.isSuccess    = false;
                response.ErrorMessage = "An error occured when creating the account";

                response.ErrorMessages.Add(e.Message);

                try
                {
                    response.ErrorMessages.Add(e.InnerException.InnerException.Message);
                }
                catch
                {
                }

                return(response);
            }
        }
コード例 #27
0
        public static DataAccessResponseType DeprovisionAccount(Account account)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            if (account.AccountID == Guid.Empty)
            {
                response.isSuccess    = false;
                response.ErrorMessage = "No account to deprovision";
                return(response);
            }

            try
            {
                // 0. Get Account Users:
                account.Users = AccountUserManager.GetUsers(account.AccountID.ToString());



                #region LOG ACTIVITY (Deprovisioning Started)


                if (account.Provisioned)
                {
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Deprovisioning_Started,
                        "Deprovisioning of '" + account.AccountName + "' has started",
                        "AccountID: '" + account.AccountID +
                        "' SqlPartition: '" + account.SqlPartition +
                        "' DocumentPartition: '" + account.DocumentPartition +
                        "' StripeCustomerID: '" + account.StripeCustomerID +
                        "'"
                        );
                }
                else if (!account.Provisioned)
                {
                    //Account has not been provisioned, only delete the account and user objects, This will be a simple purge and not a full deprovisioning
                    PlatformLogManager.LogActivity(CategoryType.Account, ActivityType.Account_Purge_Started, "Purging of unprovisioned account '" + account.AccountName + "' has started", "AccountID: '" + account.AccountID + "' Account Owner: '" + account.Users[0].UserName + "'");
                }

                #endregion


                // Owners of accounts that have been provisioned will get an email, create a list of owner emails before all users are delted
                var accountOwnerEmails = AccountManager.GetAccountOwnerEmails(account.AccountID.ToString());

                string accountOwners = string.Empty;

                foreach (string ownerEmail in accountOwnerEmails)
                {
                    accountOwners += ownerEmail + " ";
                }


                #region STEPS 1-3 DELETE ACCOUNT USERS AND ACCOUNT

                // 1. Delete All Account Users
                AccountDeprovisioning.DeleteAllAccountUsers(account);

                // 2. Delete Account
                AccountDeprovisioning.DeleteAccount(account);

                // 3. Delete Customer in Stripe if the account has a StripeCustomerID
                if (account.StripeCustomerID != null)
                {
                    try
                    {
                        var stripeManager = new StripeManager();
                        stripeManager.DeleteCustomer(account.StripeCustomerID);
                    }
                    catch
                    {
                    }
                }

                #endregion

                if (!account.Provisioned)
                {
                    #region Log closure if account is not provisioned
                    //Account has never been provisioned, since we already deleted the account and all associated users, we are done. Log activity completion and return result:
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Purged,
                        "Purging of unprovisioned account '" + account.AccountName + "' has completed",
                        "Account Owners: '" + accountOwners + "'",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account)
                        );


                    //Log the closed account
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Closed,
                        "Unprovisioned",
                        account.AccountNameKey,
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account));

                    response.isSuccess      = true;
                    response.SuccessMessage = "Purging of account '" + account.AccountID + "' Complete!";


                    #endregion
                }
                else
                {
                    // 4. Clear SQL Data Schema &
                    AccountDeprovisioning.DestroySqlSchemaAndTables(account);

                    // 5. Clear Table Storage Data
                    AccountDeprovisioning.DestroyTableStorageData(account);

                    // 6. Clear Blob Storage Data
                    AccountDeprovisioning.DestroyBlobStorageData(account);

                    // 7. Clear Document Data (Retired)
                    AccountDeprovisioning.DestroyDocumentCollection(account);

                    // 8. Clear Search Indexes
                    AccountDeprovisioning.DestroySearchIndexes(account);

                    // 9. Decriment both STORAGE & SEARCH Partitions
                    Sql.Statements.UpdateStatements.UpdatePartitionsTenantCounts(account.StoragePartition, account.SearchPartition);

                    // 10. Log Activity
                    #region Logging


                    PlatformLogManager.LogActivity(
                        CategoryType.GarbageCollection,
                        ActivityType.GarbageCollection_ClosedAccounts,
                        "All resources for account '" + account.AccountName + "' have been destroyed",
                        "Purged resources now available to new accounts",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account)
                        );


                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Deprovisioned,
                        "Deprovisioning of '" + account.AccountName + "' has completed",
                        "SqlPartition: '" + account.SqlPartition + "'",
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account)
                        );

                    //Log the closed account
                    PlatformLogManager.LogActivity(
                        CategoryType.Account,
                        ActivityType.Account_Closed,
                        "Deprovisioned",
                        account.AccountNameKey + " | " + account.PaymentPlanName,
                        account.AccountID.ToString(),
                        account.AccountName,
                        null,
                        null,
                        null,
                        null,
                        null,
                        JsonConvert.SerializeObject(account));

                    #endregion

                    // 11. Email all account users regarding closure:
                    EmailManager.Send(
                        accountOwnerEmails,
                        Settings.Endpoints.Emails.FromAlerts,
                        Settings.Copy.EmailMessages.DeprovisioningComplete.FromName,
                        Settings.Copy.EmailMessages.DeprovisioningComplete.Subject,
                        String.Format(Settings.Copy.EmailMessages.DeprovisioningComplete.Body, account.AccountName),
                        true);

                    // 12. Destroy ALL caches associated with an account
                    AccountManager.DestroyAccountCaches(account.AccountID.ToString(), account.AccountNameKey, account.StripeCustomerID);

                    // 13. Destroy subdomains
                    try
                    {
                        var cloudFlareResult = CloudFlareManager.RemoveSubdomains(account.AccountNameKey);

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

                    response.isSuccess      = true;
                    response.SuccessMessage = "Deprovisioning of account '" + account.AccountID + "' Complete!";
                }

                //TODO: Log purged account into ClosedAccounts Table
            }
            catch (Exception e)
            {
                #region LOG ERROR (Deprovisioning Errors)

                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to deprovision or purge account: " + account.AccountName,
                    System.Reflection.MethodBase.GetCurrentMethod(),
                    account.AccountID.ToString(),
                    account.AccountName
                    );

                #endregion

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
            }

            // Archive the closed account
            //ClosedAccountsStorageManager.ArchiveClosedAccount(account);


            return(response);
        }
コード例 #28
0
        public static DataAccessResponseType AddProductPropertyToSearchIndexFields(string searchPartition, string indexName, string fieldName, string propertyTypeNameKey) //, string searchPartitionName, string searchPartitionKey)
        {
            var searchUpdateResponse = new DataAccessResponseType();

            try
            {
                #region Determine Search Field DataType from PropertyType

                //Default is string:
                Microsoft.Azure.Search.Models.DataType fieldDataType = Microsoft.Azure.Search.Models.DataType.String;

                switch (propertyTypeNameKey)
                {
                case "number":
                    fieldDataType = Microsoft.Azure.Search.Models.DataType.Double;
                    break;

                case "datetime":
                    fieldDataType = Microsoft.Azure.Search.Models.DataType.DateTimeOffset;
                    break;

                case "location":
                    fieldDataType = Microsoft.Azure.Search.Models.DataType.GeographyPoint;
                    break;

                case "predefined":
                    fieldDataType = Microsoft.Azure.Search.Models.DataType.Collection(Microsoft.Azure.Search.Models.DataType.String);
                    break;

                case "swatch":
                    fieldDataType = Microsoft.Azure.Search.Models.DataType.Collection(Microsoft.Azure.Search.Models.DataType.String);
                    break;

                default:
                    break;
                }

                #endregion

                //SearchServiceClient searchServiceClient = Settings.Azure.Search.AccountsSearchServiceClient;
                //SearchServiceClient searchServiceClient = new SearchServiceClient(searchPartitionName, new SearchCredentials(searchPartitionKey));

                //Get search partition
                SearchServiceClient searchServiceClient = Settings.Azure.Search.GetSearchPartitionClient(searchPartition);

                //Get Index -----------------------------------
                Microsoft.Azure.Search.Models.Index index = searchServiceClient.Indexes.Get(indexName);

                //Manage field options based on DataType

                bool isSearchable  = false;
                bool isSortable    = true;
                bool isFacetable   = true;
                bool isRetrievable = true;
                bool isFilterable  = true;

                if (propertyTypeNameKey == "paragraph")
                {
                    isSearchable = true;  //<-- Only Strings and Collections of Strngs can be searchable
                    isFacetable  = false; //<-- Paragraphs SHOULD not be set as facetable in Azure search
                    isSortable   = false; //<-- Paragraphs SHOULD not be set as sortable in Azure search
                    //isRetrievable = false;  //<-- Paragraphs SHOULD not be returned in results (Now we do return paragraphs since we use this for detail pages)
                    isFilterable = false; //<-- Paragraphs SHOULD not be filterable
                }
                else if (propertyTypeNameKey == "string")
                {
                    isFacetable  = false; //<-- Allows for string searches of ID's, etc. + Saves storage on search index on fre form strings
                    isSearchable = true;
                }
                else if (propertyTypeNameKey == "predefined" || propertyTypeNameKey == "swatch")
                {
                    isSearchable = true;  //<-- Collections CAN be searchable
                    isSortable   = false; //<-- Collections CAN NOT be set as sortable in Azure search
                }
                else if (propertyTypeNameKey == "location")
                {
                    isFacetable = false; //<-- Geography points CAN NOT be set as facetable in Azure search
                }

                index.Fields.Add(new Field {
                    Name = fieldName, Type = fieldDataType, IsFilterable = isFilterable, IsRetrievable = isRetrievable, IsSearchable = isSearchable, IsFacetable = isFacetable, IsSortable = isSortable
                });

                #region Add an additional string metadata field for geography data

                //Allows us to search for address copy in order to get back products with the associated geographic points
                //We append the term "LocationMetadata" to the field name and create a SEARCHABLE ONLY field
                //We now added ability to retrieve so it can be unpacked by API calls and merged with location results

                if (propertyTypeNameKey == "location")
                {
                    index.Fields.Add(new Field {
                        Name = fieldName + "LocationMetadata", Type = Microsoft.Azure.Search.Models.DataType.String, IsFilterable = false, IsRetrievable = true, IsSearchable = true, IsFacetable = false, IsSortable = false
                    });
                }

                #endregion

                var indexResult = searchServiceClient.Indexes.CreateOrUpdate(index);

                if (indexResult != null)
                {
                    searchUpdateResponse.isSuccess = true;
                }
            }
            catch (Exception e)
            {
                searchUpdateResponse.isSuccess    = false;
                searchUpdateResponse.ErrorMessage = e.Message;

                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to create new field '" + fieldName + "' for index '" + indexName + "'",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                /*
                 * PlatformLogManager.LogActivity(
                 *          CategoryType.ManualTask,
                 *          ActivityType.ManualTask_Search,
                 *          "Search index field creation failed during setup of new field '" + fieldName + "' on index '" + indexName + "'",
                 *          "You may need to manually create index field '" + fieldName + "' on index '" + indexName + "'",
                 *          null,
                 *          null,
                 *          null,
                 *          null,
                 *          null,
                 *          null,
                 *          System.Reflection.MethodBase.GetCurrentMethod().ToString()
                 *      );*/
            }

            return(searchUpdateResponse);
        }
コード例 #29
0
        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);
        }
コード例 #30
0
        public static DataAccessResponseType InsertPaymentPlan(string paymentPlanName,
                                                               bool visibile, decimal monthlyRate, int maxUsers, int maxCategorizationsPerSet, int maxProductsPerSet, int maxProperties, int maxValuesPerProperty, int maxTags,
                                                               bool allowSalesLeads, int monthlySupportHours, bool allowLocationData, bool allowCustomOrdering, bool allowThemes, bool allowImageEnhancements, int maxImageGroups, int maxImageFormats, int maxImageGalleries, int maxImagesPerGallery)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            StringBuilder SqlStatement = new StringBuilder();


            //newAccountModel.Provisioned = false;

            //SQL Statement =============================================================
            SqlStatement.Append("INSERT INTO PaymentPlans (");

            SqlStatement.Append("PaymentPlanName,");
            SqlStatement.Append("MonthlyRate,");
            SqlStatement.Append("Visible, ");

            SqlStatement.Append("MaxUsers,");

            SqlStatement.Append("MaxCategorizationsPerSet,");
            SqlStatement.Append("MaxProductsPerSet,");

            SqlStatement.Append("MaxImageGroups,");
            SqlStatement.Append("MaxImageFormats,");
            SqlStatement.Append("MaxImageGalleries,");
            SqlStatement.Append("MaxImagesPerGallery,");

            SqlStatement.Append("MaxTags,");
            SqlStatement.Append("MaxProperties,");
            SqlStatement.Append("MaxValuesPerProperty,");

            SqlStatement.Append("AllowSalesLeads,");
            SqlStatement.Append("MonthlySupportHours,");
            //SqlStatement.Append("BasicSupport,");
            //SqlStatement.Append("EnhancedSupport,");

            SqlStatement.Append("AllowLocationData,");
            SqlStatement.Append("AllowCustomOrdering,");

            SqlStatement.Append("AllowThemes,");
            SqlStatement.Append("AllowImageEnhancements");

            SqlStatement.Append(") VALUES (");

            //Using parameterized queries to protect against injection

            SqlStatement.Append("@PaymentPlanName, ");
            SqlStatement.Append("@MonthlyRate, ");
            SqlStatement.Append("@Visible, ");

            SqlStatement.Append("@MaxUsers, ");


            //SqlStatement.Append("@MaxCategorizations,");
            SqlStatement.Append("@MaxCategorizationsPerSet,");
            //SqlStatement.Append("@MaxProducts,");
            SqlStatement.Append("@MaxProductsPerSet,");


            SqlStatement.Append("@MaxImageGroups,");
            SqlStatement.Append("@MaxImageFormats,");
            SqlStatement.Append("@MaxImageGalleries,");
            SqlStatement.Append("@MaxImagesPerGallery,");

            SqlStatement.Append("@MaxTags,");
            SqlStatement.Append("@MaxProperties, ");
            SqlStatement.Append("@MaxValuesPerProperty, ");


            SqlStatement.Append("@AllowSalesLeads,");
            SqlStatement.Append("@MonthlySupportHours,");
            //SqlStatement.Append("@BasicSupport,");
            //SqlStatement.Append("@EnhancedSupport,");

            SqlStatement.Append("@AllowLocationData,");
            SqlStatement.Append("@AllowCustomOrdering,");

            SqlStatement.Append("@AllowThemes,");
            SqlStatement.Append("@AllowImageEnhancements");

            SqlStatement.Append(")");

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

            sqlCommand.CommandText = SqlStatement.ToString();



            //Using parameterized queries to protect against injection
            sqlCommand.Parameters.Add("@PaymentPlanName", SqlDbType.Text);
            sqlCommand.Parameters.Add("@MonthlyRate", SqlDbType.Decimal);
            sqlCommand.Parameters.Add("@Visible", SqlDbType.Bit);

            sqlCommand.Parameters.Add("@MaxUsers", SqlDbType.Int);


            //sqlCommand.Parameters.Add("@MaxCategorizations", SqlDbType.Int);
            sqlCommand.Parameters.Add("@MaxCategorizationsPerSet", SqlDbType.Int);
            //sqlCommand.Parameters.Add("@MaxProducts", SqlDbType.Int);
            sqlCommand.Parameters.Add("@MaxProductsPerSet", SqlDbType.Int);


            /*
             * sqlCommand.Parameters.Add("@MaxCategories", SqlDbType.Int);
             * sqlCommand.Parameters.Add("@MaxSubcategories", SqlDbType.Int);
             * sqlCommand.Parameters.Add("@MaxSubsubcategories", SqlDbType.Int);
             * sqlCommand.Parameters.Add("@MaxSubsubsubcategories", SqlDbType.Int);
             * sqlCommand.Parameters.Add("@MaxProductsPerSet", SqlDbType.Int);
             * sqlCommand.Parameters.Add("@MaxSubcategoriesPerSet", SqlDbType.Int);
             */

            sqlCommand.Parameters.Add("@MaxImageGroups", SqlDbType.Int);
            sqlCommand.Parameters.Add("@MaxImageFormats", SqlDbType.Int);
            sqlCommand.Parameters.Add("@MaxImageGalleries", SqlDbType.Int);
            sqlCommand.Parameters.Add("@MaxImagesPerGallery", SqlDbType.Int);


            sqlCommand.Parameters.Add("@MaxTags", SqlDbType.Int);
            sqlCommand.Parameters.Add("@MaxProperties", SqlDbType.Int);
            sqlCommand.Parameters.Add("@MaxValuesPerProperty", SqlDbType.Int);


            sqlCommand.Parameters.Add("@AllowSalesLeads", SqlDbType.Bit);
            sqlCommand.Parameters.Add("@MonthlySupportHours", SqlDbType.Int);
            //sqlCommand.Parameters.Add("@BasicSupport", SqlDbType.Bit);
            //sqlCommand.Parameters.Add("@EnhancedSupport", SqlDbType.Bit);

            sqlCommand.Parameters.Add("@AllowLocationData", SqlDbType.Bit);
            sqlCommand.Parameters.Add("@AllowCustomOrdering", SqlDbType.Bit);

            sqlCommand.Parameters.Add("@AllowThemes", SqlDbType.Bit);
            sqlCommand.Parameters.Add("@AllowImageEnhancements", SqlDbType.Bit);

            //Assign values
            sqlCommand.Parameters["@PaymentPlanName"].Value = paymentPlanName;
            sqlCommand.Parameters["@MonthlyRate"].Value     = monthlyRate;
            sqlCommand.Parameters["@Visible"].Value         = visibile;

            sqlCommand.Parameters["@MaxUsers"].Value = maxUsers;

            //sqlCommand.Parameters["@MaxCategorizations"].Value = maxCategorizations;
            sqlCommand.Parameters["@MaxCategorizationsPerSet"].Value = maxCategorizationsPerSet;
            //sqlCommand.Parameters["@MaxProducts"].Value = maxProducts;
            sqlCommand.Parameters["@MaxProductsPerSet"].Value = maxProductsPerSet;

            /*
             * sqlCommand.Parameters["@MaxCategories"].Value = maxCategories;
             * sqlCommand.Parameters["@MaxSubcategories"].Value = maxSubcategories;
             * sqlCommand.Parameters["@MaxSubsubcategories"].Value = maxSubsubcategories;
             * sqlCommand.Parameters["@MaxSubsubsubcategories"].Value = maxSubsubsubcategories;
             * sqlCommand.Parameters["@MaxProductsPerSet"].Value = MaxProductsPerSet;
             * sqlCommand.Parameters["@MaxSubcategoriesPerSet"].Value = MaxSubcategoriesPerSet;
             */

            sqlCommand.Parameters["@MaxImageGroups"].Value      = maxImageGroups;
            sqlCommand.Parameters["@MaxImageFormats"].Value     = maxImageFormats;
            sqlCommand.Parameters["@MaxImageGalleries"].Value   = maxImageGalleries;
            sqlCommand.Parameters["@MaxImagesPerGallery"].Value = maxImagesPerGallery;

            sqlCommand.Parameters["@MaxTags"].Value              = maxTags;
            sqlCommand.Parameters["@MaxProperties"].Value        = maxProperties;
            sqlCommand.Parameters["@MaxValuesPerProperty"].Value = maxValuesPerProperty;


            sqlCommand.Parameters["@AllowSalesLeads"].Value     = allowSalesLeads;
            sqlCommand.Parameters["@MonthlySupportHours"].Value = monthlySupportHours;
            //sqlCommand.Parameters["@BasicSupport"].Value = basicSupport;
            //sqlCommand.Parameters["@EnhancedSupport"].Value = enhancedSupport;

            sqlCommand.Parameters["@AllowLocationData"].Value   = allowLocationData;
            sqlCommand.Parameters["@AllowCustomOrdering"].Value = allowCustomOrdering;

            sqlCommand.Parameters["@AllowThemes"].Value            = allowThemes;
            sqlCommand.Parameters["@AllowImageEnhancements"].Value = allowImageEnhancements;

            int insertAccountResult = 0;

            sqlCommand.Connection.OpenWithRetry();

            try
            {
                insertAccountResult = sqlCommand.ExecuteNonQueryWithRetry(); // returns Int indicating number of rows affected
                if (insertAccountResult > 0)
                {
                    response.isSuccess = true;
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to insert a payment plan into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

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

            sqlCommand.Connection.Close();

            return(response);
        }