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 }
/// <summary> /// Deletes all image records for an object in table storage /// </summary> /// <param name="accountId"></param> /// <param name="imageGroupTypeNameKey"></param> /// <param name="objectId"></param> /// <returns></returns> internal static DataAccessResponseType DeleteAllImageRecordsForObject(string accountId, string storagePartition, string imageFormatGroupTypeNameKey, string objectId) { var response = new DataAccessResponseType(); //CloudTableClient cloudTableClient = Sahara.Core.Settings.Azure.Storage.StorageConnections.AccountsStorage.CreateCloudTableClient(); CloudTableClient cloudTableClient = Settings.Azure.Storage.GetStoragePartitionAccount(storagePartition).CreateCloudTableClient(); //Create and set retry policy //IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 4); IRetryPolicy linearRetryPolicy = new LinearRetry(TimeSpan.FromSeconds(1), 4); cloudTableClient.DefaultRequestOptions.RetryPolicy = linearRetryPolicy; try { //Delete From MAIN table CloudTable cloudTable1 = cloudTableClient.GetTableReference(Sahara.Core.Common.Methods.SchemaNames.AccountIdToTableStorageName(accountId) + ImageRecordTableName(imageFormatGroupTypeNameKey)); //cloudTable1.CreateIfNotExists(); List <TableEntity> productImageEntities1 = cloudTable1.CreateQuery <TableEntity>().Where(p => p.PartitionKey == objectId).ToList(); foreach (TableEntity productImageEntity in productImageEntities1) { cloudTable1.Execute(TableOperation.Delete(productImageEntity)); } //Delete From LISTING table CloudTable cloudTable2 = cloudTableClient.GetTableReference(Sahara.Core.Common.Methods.SchemaNames.AccountIdToTableStorageName(accountId) + ImageRecordListingTableName(imageFormatGroupTypeNameKey)); //cloudTable2.CreateIfNotExists(); List <TableEntity> productImageEntities2 = cloudTable2.CreateQuery <TableEntity>().Where(p => p.PartitionKey == objectId).ToList(); foreach (TableEntity productImageEntity in productImageEntities2) { cloudTable2.Execute(TableOperation.Delete(productImageEntity)); } response.isSuccess = true; } catch (Exception e) { if (!e.Message.Contains("(404) Not Found")) { PlatformLogManager.LogActivity( CategoryType.Error, ActivityType.Error_Exception, e.Message, "Exception while attempting to delete all image records for " + imageFormatGroupTypeNameKey + " '" + objectId + "' in table storage", accountId, null, null, null, null, null, System.Reflection.MethodBase.GetCurrentMethod().ToString(), null ); } } return(response); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. #region Startup Tasks // 1.) ------ System.Net.ServicePointManager.DefaultConnectionLimit = 12 * Environment.ProcessorCount; //<-- Allows us to marshal up more SearchService/SearchIndex Clients to avoid exhausting sockets. #region Working w/ Service Fabric Enviornment Variables //Pull in enviornment variables: ----------------------------------------------------------- //var hostId = Environment.GetEnvironmentVariable("Fabric_ApplicationHostId"); //var appHostType = Environment.GetEnvironmentVariable("Fabric_ApplicationHostType"); //var tyoeEndpoint = Environment.GetEnvironmentVariable("Fabric_Endpoint_[YourServiceName]TypeEndpoint"); //var nodeName = Environment.GetEnvironmentVariable("Fabric_NodeName"); //Or print them all out (Fabric Only): /* * foreach (DictionaryEntry de in Environment.GetEnvironmentVariables()) * { * if (de.Key.ToString().StartsWith("Fabric")) * { * ServiceEventSource.Current.ServiceMessage(this.Context, " Environment variable {0} = {1}", de.Key, de.Value); * } * } */ //EVERY SINGLE ONE: /* * foreach (DictionaryEntry de in Environment.GetEnvironmentVariables()) * { * ServiceEventSource.Current.ServiceMessage(this.Context, " Environment variable {0} = {1}", de.Key, de.Value); * * }*/ #endregion // 2.) ------ var nodeName = Environment.GetEnvironmentVariable("Fabric_NodeName"); // 3.) ------ //string environment = "production"; //RoleEnvironment.GetConfigurationSettingValue("Environment"); string environment = Environment.GetEnvironmentVariable("Env").ToLower(); Sahara.Core.Settings.Startup.Initialize(environment); Sahara.Core.Settings.Azure.CurrentRoleInstance.Name = nodeName; // RoleEnvironment.CurrentRoleInstance.Role.Name; //Sahara.Core.Settings.Azure.CurrentRoleInstance.Id = nodeName; //instanceIndex; // TODO: Track down use of Sahara.Core.Settings.Azure.CurrentRoleInstance.Id and replace with nodeName or anotehr var type //Trace.TraceInformation("Sahara.CoreServices.WcfEndpoints node:" + nodeName + " entry point called on env: " + environment); //Log Activity: PlatformLogManager.LogActivity( CategoryType.Custodian, ActivityType.Custodian_Status_Update, "Custodian Worker starting on node '" + nodeName + "' (env: " + environment + ")....", "WORKER.CustodialWorker entry point called on env: " + environment + " (node:" + nodeName + ") (env: " + environment + ")" ); #endregion ServiceRuntime.RegisterServiceAsync("CustodianWorkerType", context => new CustodianWorker(context)).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(CustodianWorker).Name); // Prevents this host process from terminating so services keep running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } }
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); } }
public DataAccessResponseType UpdatePlatformUserActiveState(string userId, bool isActive, string requesterId, RequesterType requesterType, string sharedClientKey) { // Ensure the clients are certified. if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey) { return(null); } #region Validate Request var requesterName = string.Empty; var requesterEmail = string.Empty; var requestResponseType = RequestManager.ValidateRequest(requesterId, requesterType, out requesterName, out requesterEmail, Sahara.Core.Settings.Platform.Users.Authorization.Roles.SuperAdmin, null); if (!requestResponseType.isApproved) { //Request is not approved, send results: return(new DataAccessResponseType { isSuccess = false, ErrorMessage = requestResponseType.requestMessage }); } #endregion var result = PlatformUserManager.UpdateActiveState(userId, isActive); #region Log Platform Activity if (result.isSuccess) { try { var user = PlatformUserManager.GetUser(userId); var description = string.Empty; if (isActive) { description = requesterName + " activated " + user.FullName + "'s account"; } else { description = requesterName + " deactivated " + user.FullName + "'s account"; } PlatformLogManager.LogActivity( CategoryType.PlatformUser, ActivityType.PlatformUser_Edited, "Active state updated", description, null, null, requesterId, requesterName, requesterEmail ); } catch { } } #endregion return(result); }
// Future performance update: have client upload image to intermediary storage, submit location with imag eid for WCF processing (similar to other imageing solutions) public DataAccessResponseType UpdatePlatformUserProfilePhoto(string userId, byte[] imageByteArray, string requesterId, RequesterType requesterType, string sharedClientKey) { // Ensure the clients are certified. if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey) { return(null); } #region Validate Request var requesterName = string.Empty; var requesterEmail = string.Empty; var requestResponseType = RequestManager.ValidateRequest(requesterId, requesterType, out requesterName, out requesterEmail, Sahara.Core.Settings.Platform.Users.Authorization.Roles.SuperAdmin, null); if (!requestResponseType.isApproved) { //Request is not approved, send results: return(new DataAccessResponseType { isSuccess = false, ErrorMessage = requestResponseType.requestMessage }); } #endregion var result = PlatformUserManager.UpdateProfilePhoto(userId, imageByteArray); #region Log Platoform Activity if (result.isSuccess) { try { var logDescription = string.Empty; if (userId == requesterId) { logDescription = requesterName + " has updated their profile photo"; } else { var user = PlatformUserManager.GetUser(userId); logDescription = requesterName + " updated " + user.FullName + "'s profile photo"; } PlatformLogManager.LogActivity( CategoryType.PlatformUser, ActivityType.PlatformUser_Edited, "Photo updated", logDescription, null, null, requesterId, requesterName, requesterEmail ); } catch { } } #endregion return(result); }
public static DataAccessResponseType PingSites() { //Set up security channel to allow for SSL/TLS ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; var response = new DataAccessResponseType(); #region Marketing site 1 try { string siteName = "marketing site (1)"; string url = "https://" + Settings.Endpoints.URLs.MasterDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging registration site (1): " + e.Message); } #endregion #region Marketing site 2 try { string siteName = "marketing site (2)"; string url = "https://www." + Settings.Endpoints.URLs.MasterDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging registration site (2): " + e.Message); } #endregion #region Registration site try { string siteName = "registration site"; string url = Settings.Endpoints.URLs.RegistrationUrl; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging registration site: " + e.Message); } #endregion #region Subscription site try { string siteName = "subscription site"; string url = "https://subscribe." + Settings.Endpoints.URLs.MasterDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging subscription site: " + e.Message); } #endregion #region Platform admin try { string siteName = "platform admin"; string url = "https://" + Settings.Endpoints.URLs.PlatformDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging platform admin: " + e.Message); } #endregion #region Account Admin site try { string siteName = "accounts admin site"; string url = "https://accounts." + Settings.Endpoints.URLs.AccountManagementDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging accounts admin site: " + e.Message); } #endregion #region Account API try { string siteName = "accounts api"; string url = "https://accounts." + Settings.Endpoints.URLs.AccountServiceDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging accounts api: " + e.Message); } #endregion #region Account Sites try { string siteName = "accounts site"; string url = "https://accounts." + Settings.Endpoints.URLs.AccountSiteDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging accounts site: " + e.Message); } #endregion #region Imaging API try { string siteName = "imaging api"; string url = Settings.Endpoints.URLs.ImagingApiUrl; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging imaging api: " + e.Message); } #endregion #region Registration API try { string siteName = "registration api"; string url = Settings.Endpoints.URLs.RegistrationApiEndpoint + "/deploymentEnvironments/local"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging registration api: " + e.Message); } #endregion #region Registration API (AccountName Validation) try { string siteName = "api account name validator"; string url = Settings.Endpoints.URLs.RegistrationApiEndpoint + "/validation/accountname"; //Post to the AccountName Validator to make this really speedy: var values = new Dictionary <string, string> { { "accountname", "kaz" } }; var content = new FormUrlEncodedContent(values); var responseString = ""; using (var client = new HttpClient()) { var postResponse = client.PostAsync(url, content).Result; responseString = postResponse.Content.ReadAsStringAsync().Result; } try { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "posted to " + siteName + " response:" + responseString); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error posting to " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pstong to api account name validator: " + e.Message); } #endregion #region Webhooks API try { string siteName = "stripe webhooks api"; string url = "http://webhooks." + Settings.Endpoints.URLs.ApiDomain + "/DeploymentEnvironments"; //<-- We use HTTP here only as there are no certs on cloud service. HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_KeepAlive_Status, "Pinged " + siteName + " at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging " + siteName + ": " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error pinging stripe webhooks: " + e.Message); } #endregion response.isSuccess = true; //response.ErrorMessage = "Not implemented."; return(response); }
public static DataAccessResponseType CacheAccountData() { //Set up security channel to allow for SSL/TLS ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; var response = new DataAccessResponseType(); var accounts = AccountManager.GetAllAccountsByFilter("Provisioned", "1", 0, 2000, "AccountNameKey"); //Loop through each account and call public api to preload data foreach (var account in accounts) { #region Account Info try { string callName = "account"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountServiceDomain + "/account"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshCache_Status, "Refreshing " + callName + " api cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " api cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing account api cache for '" + account.AccountName + ": " + e.Message); } #endregion #region Category Tree try { string callName = "categories"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountServiceDomain + "/categories/tree?includeImages=true"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshCache_Status, "Refreshing " + callName + " api cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " api cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing categories api cache for '" + account.AccountName + ": " + e.Message); } #endregion #region Search Query try { string callName = "search"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountServiceDomain + "/search/products?query=test?skip=0&take=2"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshCache_Status, "Refreshing " + callName + " api cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " api cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing search api cache for '" + account.AccountName + ": " + e.Message); } #endregion #region Search Sortables try { string callName = "search-sortables"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountServiceDomain + "/search/sortables"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshCache_Status, "Refreshing " + callName + " api cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " api cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing search-sortables api cache for '" + account.AccountName + ": " + e.Message); } #endregion #region Search Facets try { string callName = "search-facets"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountServiceDomain + "/search/facets"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshCache_Status, "Refreshing " + callName + " api cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " api cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing search-facets api cache for '" + account.AccountName + ": " + e.Message); } #endregion #region Properties try { string callName = "properties"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountServiceDomain + "/properties/product"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshCache_Status, "Refreshing " + callName + " api cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " api cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing properties api cache for '" + account.AccountName + ": " + e.Message); } #endregion #region Tags try { string callName = "tags"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountServiceDomain + "/tags"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshCache_Status, "Refreshing " + callName + " api cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " api cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing tags api cache for '" + account.AccountName + ": " + e.Message); } #endregion } //Loop through each account and call public site to preload pages foreach (var account in accounts) { #region Public Site Search try { string callName = "account-search"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountSiteDomain + "/search"; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshAccountSite_Status, "Refreshing " + callName + " site cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " site cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing account-search site cache for '" + account.AccountName + ": " + e.Message); } #endregion #region Public Site Search try { string callName = "account-home"; string url = "https://" + account.AccountNameKey + "." + Settings.Endpoints.URLs.AccountSiteDomain; HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; //optional HttpWebResponse webRequestResponse = webRequest.GetResponse() as HttpWebResponse; try { Stream stream = webRequestResponse.GetResponseStream(); PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Custodian_RefreshAccountSite_Status, "Refreshing " + callName + " site cache for '" + account.AccountName + "' at:" + url); } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing " + callName + " site cache for '" + account.AccountName + "': " + e.Message); } } catch (Exception e) { PlatformLogManager.LogActivity(CategoryType.Custodian, ActivityType.Error_Custodian, "Error refreshing account-home site cache for '" + account.AccountName + ": " + e.Message); } #endregion } response.isSuccess = true; //response.ErrorMessage = "Not implemented."; return(response); }
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); }
public DataAccessResponseType ProvisionAccount(string accountId, string requesterId, RequesterType requesterType, string sharedClientKey) { // Ensure the clients are certified. if (sharedClientKey != Sahara.Core.Platform.Requests.RequestManager.SharedClientKey) { return(null); } #region Validate Request var requesterName = string.Empty; var requesterEmail = string.Empty; var requestResponseType = RequestManager.ValidateRequest(requesterId, requesterType, out requesterName, out requesterEmail, Sahara.Core.Settings.Platform.Users.Authorization.Roles.SuperAdmin, null); //<-- Only Platform Super Admins can provision accounts if (!requestResponseType.isApproved) { //Request is not approved, send results: return(new DataAccessResponseType { isSuccess = false, ErrorMessage = requestResponseType.requestMessage }); } #endregion if (accountId == null) { //Request is not approved, send results: return(new DataAccessResponseType { isSuccess = false, ErrorMessage = "AccountID cannot be null" }); } var response = new DataAccessResponseType(); // 0. Check to see if the account has been previously verified: var account = AccountManager.GetAccount(accountId, false, AccountManager.AccountIdentificationType.AccountID); if (account.Provisioned) { response.isSuccess = false; response.ErrorMessage = "This account has already been provisioned"; return(response); } if (account.StripeSubscriptionID == null || account.StripeCustomerID == null || account.PaymentPlan.MonthlyRate == 0) { response.isSuccess = false; response.ErrorMessage = "This account has not been assigned a payment plan or a Stripe CustomerID"; return(response); } else { // 1. Send provisioning request for the Worker via the PlatformQueue PlatformQueuePipeline.SendMessage.ProvisionAccount(accountId); // 2. Set Active state to TRUE to indicate that PlatformAdmin has activated the account and is now PENDING provisioning AccountManager.UpdateAccountActiveState(account.AccountID.ToString(), true); // 3. Invalidated/Update the cache for this account AccountManager.UpdateAccountDetailCache(accountId); // 4. Log the activity PlatformLogManager.LogActivity(Sahara.Core.Logging.PlatformLogs.Types.CategoryType.Account, Sahara.Core.Logging.PlatformLogs.Types.ActivityType.Account_Provisioning_Requested, "Provisioning request sent for: '" + account.AccountName + "'", "Provisioning request sent.", accountId, account.AccountName); // 4. Return results! response.SuccessMessage = "Account provisioning request sent!"; response.isSuccess = true; } return(response); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. #region Startup Tasks // 1.) ------ System.Net.ServicePointManager.DefaultConnectionLimit = 12 * Environment.ProcessorCount; //<-- Allows us to marshal up more SearchService/SearchIndex Clients to avoid exhausting sockets. // 2.) ------ var nodeName = Environment.GetEnvironmentVariable("Fabric_NodeName"); // 3.) ------ //string environment = "production"; //RoleEnvironment.GetConfigurationSettingValue("Environment"); string environment = Environment.GetEnvironmentVariable("Env").ToLower(); Sahara.Core.Settings.Startup.Initialize(environment); Sahara.Core.Settings.Azure.CurrentRoleInstance.Name = nodeName; // RoleEnvironment.CurrentRoleInstance.Role.Name; //Sahara.Core.Settings.Azure.CurrentRoleInstance.Id = nodeName; //instanceIndex; // TODO: Track down use of Sahara.Core.Settings.Azure.CurrentRoleInstance.Id and replace with nodeName or anotehr var type //Trace.TraceInformation("Sahara.CoreServices.WcfEndpoints node:" + nodeName + " entry point called on env: " + environment); // TODO: Proper enviornment settings // TODO Proper WCF endpoint URL set up (local, stage, prod, etc. ( //Log Activity: PlatformLogManager.LogActivity( CategoryType.WCFHost, ActivityType.WCFHost_Status, "WCF Endpoints starting on node '" + nodeName + "' (env: " + environment + ")....", "Sahara.CoreServices.Host entry point called on env: " + environment + " (node:" + nodeName + ") (env: " + environment + ")" ); #endregion ServiceRuntime.RegisterServiceAsync("WcfEndpointsType", context => new WcfEndpoints(context)).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(WcfEndpoints).Name); // Prevents this host process from terminating so services keep running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } }
public static PlatformQueueMessage GetNextQueueMessage(TimeSpan timeSpan) { var message = _queue.GetMessage(timeSpan); if (message != null) { if (message.DequeueCount > 3) { //If this message has had 4 or more failed attempts (DequeueCount) at processing, log the raw message, email system admins, delete from queue & return null //Log Issues For Administrator Analysis: PlatformLogManager.LogActivity( CategoryType.Error, ActivityType.Error_QueuePipeline, "Could not process message after " + message.DequeueCount + " attempts", "Raw Message: {" + message.AsString + "}, " + "Dequeue Count: {" + message.DequeueCount + "}" ); //Delete Message From Queue _queue.DeleteMessage(message); //Email administrators about the issue: EmailManager.Send( Settings.Endpoints.Emails.PlatformEmailAddresses, Settings.Endpoints.Emails.FromAlerts, "platform Queue", "Platform Queue Alert", "A platform queue message has been dequeued past the minimum allowed and has been archived.</br></br>Message Contents:</br></br>" + message.AsString, true ); //Create a ManualTask for this message PlatformLogManager.LogActivity( CategoryType.ManualTask, ActivityType.ManualTask_MessageQueue, "Message Processing Failed", "Raw Message: {" + message.AsString + "}", null, null, null, null, null, null, System.Reflection.MethodBase.GetCurrentMethod().ToString() ); return(null); } } try { string messageType; string[] messageParts; if (message != null) { messageParts = message.AsString.Split(new char[] { ',' }); messageType = messageParts[0]; } else { return(null); } switch (messageType) { case PlatformMessageTypes.ProvisionAccount: ProvisionAccount_QueueMessage provisionAccount = new ProvisionAccount_QueueMessage(); provisionAccount.rawMessage = message; provisionAccount.QueueMessageType = messageType; provisionAccount.AccountID = messageParts[1]; return(provisionAccount); case PlatformMessageTypes.StripeChargeSucceeded: StripeChargeSucceeded_QueueMessage stripeChargeSucceeded = new StripeChargeSucceeded_QueueMessage(); stripeChargeSucceeded.rawMessage = message; stripeChargeSucceeded.QueueMessageType = messageType; stripeChargeSucceeded.StripeCustomerId = messageParts[1]; stripeChargeSucceeded.StripeChargeId = messageParts[2]; stripeChargeSucceeded.StripeCardId = messageParts[3]; stripeChargeSucceeded.StripeInvoiceId = messageParts[4]; stripeChargeSucceeded.StripeEventId = messageParts[5]; return(stripeChargeSucceeded); case PlatformMessageTypes.StripeRecurringChargeFailed: StripeRecurringChargeFailed_QueueMessage stripeRecurringChargeFailed = new StripeRecurringChargeFailed_QueueMessage(); stripeRecurringChargeFailed.rawMessage = message; stripeRecurringChargeFailed.QueueMessageType = messageType; stripeRecurringChargeFailed.StripeCustomerId = messageParts[1]; stripeRecurringChargeFailed.StripeChargeId = messageParts[2]; stripeRecurringChargeFailed.Amount = messageParts[3]; stripeRecurringChargeFailed.FailureMessage = messageParts[4]; stripeRecurringChargeFailed.StripeEventId = messageParts[5]; return(stripeRecurringChargeFailed); case PlatformMessageTypes.RetryUnpaidInvoices: RetryUnpaidInvoices_QueueMessage retryUnpaidInvoices = new RetryUnpaidInvoices_QueueMessage(); retryUnpaidInvoices.rawMessage = message; retryUnpaidInvoices.QueueMessageType = messageType; retryUnpaidInvoices.StripeCustomerId = messageParts[1]; return(retryUnpaidInvoices); case PlatformMessageTypes.StripeChargeFailed: StripeChargeFailed_QueueMessage stripeChargeFailed = new StripeChargeFailed_QueueMessage(); stripeChargeFailed.rawMessage = message; stripeChargeFailed.QueueMessageType = messageType; stripeChargeFailed.StripeCustomerId = messageParts[1]; stripeChargeFailed.StripeChargeId = messageParts[2]; stripeChargeFailed.Amount = messageParts[3]; stripeChargeFailed.FailureMessage = messageParts[4]; stripeChargeFailed.StripeEventId = messageParts[5]; return(stripeChargeFailed); case PlatformMessageTypes.StripeCustomerDelinquencyChanged: StripeCustomerDelinquencyChanged_QueueMessage stripeCustomerDelinquencyChanged = new StripeCustomerDelinquencyChanged_QueueMessage(); stripeCustomerDelinquencyChanged.rawMessage = message; stripeCustomerDelinquencyChanged.QueueMessageType = messageType; stripeCustomerDelinquencyChanged.accountId = messageParts[1]; stripeCustomerDelinquencyChanged.newDelinquencyStatus = Convert.ToBoolean(messageParts[2]); return(stripeCustomerDelinquencyChanged); case PlatformMessageTypes.StripeSubscriptionStatusChanged: StripeSubscriptionStatusChanged_QueueMessage stripeSubscriptionStatusChanged = new StripeSubscriptionStatusChanged_QueueMessage(); stripeSubscriptionStatusChanged.rawMessage = message; stripeSubscriptionStatusChanged.QueueMessageType = messageType; stripeSubscriptionStatusChanged.customerId = messageParts[1]; stripeSubscriptionStatusChanged.newSubscriptionStatus = messageParts[2]; stripeSubscriptionStatusChanged.previousSubscriptionStatus = messageParts[3]; return(stripeSubscriptionStatusChanged); #region (OPTIONAL) Processing of manual Invoice or Charge Failures #endregion case PlatformMessageTypes.SendNotificationToBulkAccounts: SendNotificationToBulkAccounts_QueueMessage sendNotificationToBulkAccounts = new SendNotificationToBulkAccounts_QueueMessage(); sendNotificationToBulkAccounts.rawMessage = message; sendNotificationToBulkAccounts.QueueMessageType = messageType; sendNotificationToBulkAccounts.NotificationMessage = messageParts[1]; sendNotificationToBulkAccounts.NotificationType = messageParts[2]; sendNotificationToBulkAccounts.ExpirationMinutes = Convert.ToDouble(messageParts[3]); sendNotificationToBulkAccounts.AccountOwnersOnly = Convert.ToBoolean(messageParts[4]); sendNotificationToBulkAccounts.ColumnName = messageParts[5]; sendNotificationToBulkAccounts.ColumnValue = messageParts[6]; return(sendNotificationToBulkAccounts); case PlatformMessageTypes.SendEmailToBulkAccounts: SendEmailToBulkAccounts_QueueMessage sendEmailToBulkAccounts = new SendEmailToBulkAccounts_QueueMessage(); sendEmailToBulkAccounts.rawMessage = message; sendEmailToBulkAccounts.QueueMessageType = messageType; sendEmailToBulkAccounts.FromEmail = messageParts[1]; sendEmailToBulkAccounts.FromName = messageParts[2]; sendEmailToBulkAccounts.EmailSubject = messageParts[3]; sendEmailToBulkAccounts.EmailMessage = messageParts[4]; sendEmailToBulkAccounts.AccountOwnersOnly = Convert.ToBoolean(messageParts[5]); sendEmailToBulkAccounts.IsImportant = Convert.ToBoolean(messageParts[6]); sendEmailToBulkAccounts.ColumnName = messageParts[7]; sendEmailToBulkAccounts.ColumnValue = messageParts[8]; return(sendEmailToBulkAccounts); case PlatformMessageTypes.SendApplicationDataInjectionImageDocuments: SendApplicationDataInjectionImageDocuments_QueueMessage sendApplicationDataInjectionImageDocuments = new SendApplicationDataInjectionImageDocuments_QueueMessage(); sendApplicationDataInjectionImageDocuments.rawMessage = message; sendApplicationDataInjectionImageDocuments.QueueMessageType = messageType; sendApplicationDataInjectionImageDocuments.AccountID = messageParts[1]; sendApplicationDataInjectionImageDocuments.DocumentCount = Convert.ToInt32(messageParts[2]); return(sendApplicationDataInjectionImageDocuments); case PlatformMessageTypes.AnotherMessage: return(null); default: Invalid_QueueMessage invalid = new Invalid_QueueMessage(); return(invalid); } } catch (Exception e) { //Log Issues For Administrator Analysis: PlatformLogManager.LogActivity( CategoryType.Error, ActivityType.Error_QueuePipeline_UnreadableMessage, "Could Not Read Message.", "Raw Message: {" + message.AsString + "}, " + "Dequeue Count: {" + message.DequeueCount + "}" + "(Error: " + e.Message + ")" ); //Delete Message From Queue _queue.DeleteMessage(message); //Log exception and email platform admins PlatformExceptionsHelper.LogExceptionAndAlertAdmins( e, "attempting to get a platform queue message. Message has been archived. Message Contents: " + message.AsString, System.Reflection.MethodBase.GetCurrentMethod() ); return(null); } }
public static void Send(List <string> recipients, string fromEmail, string fromName, string subject, string body, bool isHtml, bool isImportant = false) { dynamic sg = new SendGridAPIClient(Settings.Services.SendGrid.Account.APIKey); Email from = new Email(fromEmail, fromName); var personalization = new Personalization(); foreach (var email in recipients) { if (email.ToLower() == "platformadmin@[Config_PlatformEmail]") { //on recipients with LISTS we always BCC platformAdmin in order to keep that email hidden from the account users Email bcc = new Email(email); personalization.Bccs = new List <Email>(); personalization.Bccs.Add(bcc); } else { Email to = new Email(email); personalization.AddTo(to); } } //Mail mail = new Mail(from, subject, to, content); Mail mail = new Mail(); mail.From = from; mail.Subject = subject; mail.Personalization = new List <Personalization>(); mail.Personalization.Add(personalization); if (isHtml) { Content content = new Content("text/html", body); mail.Contents = new List <Content>(); mail.Contents.Add(content); } else { Content content = new Content("text/plain", body); mail.Contents = new List <Content>(); mail.Contents.Add(content); } // Send the email. try { if (Settings.Services.SendGrid.Account.Active) //<-- We check to see if email service is inactive due to load testing to avoid extra service charges { var requestBody = mail.Get(); //dynamic response = await sg.client.mail.send.post(requestBody: requestBody); dynamic response = sg.client.mail.send.post(requestBody: requestBody); //dynamic d = response; } } catch (Exception e) { //Log the Exception PlatformLogManager.LogActivity( CategoryType.Error, ActivityType.Error_SendGrid, e.Message, "An error occured when attempting to use SendGrid" ); //Log the Exception PlatformLogManager.LogActivity( CategoryType.Error, ActivityType.Error_Exception, e.Message, "An exception occured when attempting to use SendGrid", null, null, null, null, null, null, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, JsonConvert.SerializeObject(e) ); } }