Exemplo n.º 1
0
 public async Task StoreTenantInfoAsync(TenantInformation tenantInfo)
 {
     await _dataStorageManager.StoreAsync(
         DataStorageKey.CurrentSession_TenantInfo,
         _objectMapper.Map <TenantInformationPersistanceModel>(tenantInfo)
         );
 }
Exemplo n.º 2
0
        public static async Task Send(ActionMessage message, TenantInformation tenant, IWorkflowMessagingProcessor workflowMessagingProcessor)
        {
            Logger.Log($"Sending {message.ActionType} message with transaction ID '{message.TransactionId}' for tenant '{tenant.TenantId}': {message.ToJSON()}", message, tenant);
            await workflowMessagingProcessor.SendMessageAsync(tenant.TenantId, message);

            Logger.Log($"Successfully sent {message.ActionType} message", message, tenant);
        }
        protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var message = (NotificationMessage)actionMessage;
            var result  = await SendNotificationEmail(tenant, message, (INotificationRepository)baseRepository);

            Logger.Log($"Finished processing message with result: {result}", message, tenant);
            return(await Task.FromResult(result == SendEmailResult.Success));
        }
Exemplo n.º 4
0
        public async Task StoreTenantInfoAsync(TenantInformation tenantInfo)
        {
            _dataStorageManager.SetValue(
                DataStorageKey.CurrentSession_TenantInfo,
                mapper.Map <TenantInformationPersistanceModel>(tenantInfo)
                );

            await Task.CompletedTask;
        }
Exemplo n.º 5
0
 public void TestInitialize()
 {
     _transactionValidator = new TransactionValidator();
     _message = new NotificationMessage
     {
         TransactionId = 123
     };
     _tenant       = new TenantInformation();
     _baseRepoMock = new Mock <IBaseRepository>(MockBehavior.Strict);
 }
 public void TestInitialize()
 {
     _helper  = new UsersGroupsChangedActionHelper();
     _message = new UsersGroupsChangedMessage
     {
         ChangeType = UsersGroupsChangedType.Update,
         UserId     = 1,
         RevisionId = 2
     };
     _repositoryMock = new Mock <IUsersGroupsChangedRepository>(MockBehavior.Strict);
     _workflowMessagingProcessorMock = new Mock <IWorkflowMessagingProcessor>(MockBehavior.Strict);
     _tenantInformation = new TenantInformation();
 }
 public void TestInitialize()
 {
     _helper  = new WorkflowsChangedActionHelper();
     _message = new WorkflowsChangedMessage
     {
         WorkflowId = 1,
         RevisionId = 2,
         UserId     = 3
     };
     _repositoryMock = new Mock <IWorkflowsChangedRepository>(MockBehavior.Strict);
     _workflowMessagingProcessorMock = new Mock <IWorkflowMessagingProcessor>(MockBehavior.Strict);
     _tenantInformation = new TenantInformation();
 }
Exemplo n.º 8
0
    /// <summary>
    /// Initializes a new instance of the <see cref="UserCultureInfo"/> class.
    /// </summary>
    public UserCultureInfo(TenantInformation ti)
    {
        if (ti != null && ti.Timezone != null)
        {
            TimeZone = TimeZoneInfo.FindSystemTimeZoneById(ti.Timezone);
        }
        else
        {
            TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time");
        }
        // TODO: Need to through DB Context.

        DateTimeFormat = "M/d/yyyy h:m:ss tt"; // Default format.
    }
Exemplo n.º 9
0
 public void TestInitialize()
 {
     _helper  = new PropertyItemTypesChangedActionHelper();
     _message = new PropertyItemTypesChangedMessage
     {
         IsStandard = true,
         ChangeType = PropertyItemTypeChangeType.ItemType,
         UserId     = 1,
         RevisionId = 2
     };
     _repositoryMock = new Mock <IPropertyItemTypesChangedRepository>(MockBehavior.Strict);
     _workflowMessagingProcessorMock = new Mock <IWorkflowMessagingProcessor>(MockBehavior.Strict);
     _tenantInformation = new TenantInformation();
 }
Exemplo n.º 10
0
        public IActionResult Me([FromServices] TenantInformation ti)
        {
            var user       = _context.Users.Where(e => e.Id == ti.UserId).FirstOrDefault();
            var timeformat = _context.schools.FirstOrDefault();

            return(new JsonResult(new
            {
                user = user,
                school = timeformat.name,
                logo = timeformat.imgPath,
                timeformat = timeformat.date_format,
                currency_symbol = timeformat.currency_format,
                currency_name = timeformat.currency_name
            }));
        }
        protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var message = (GenerateTestsMessage)actionMessage;

            if (message == null || message.ArtifactId <= 0 || message.ProjectId <= 0 || message.RevisionId <= 0 || message.UserId <= 0 || string.IsNullOrWhiteSpace(message.UserName) || tenant == null)
            {
                Logger.Log($"Invalid GenerateTestsMessage received: {message?.ToJSON()}", message, tenant, LogLevel.Error);
                return(false);
            }

            Logger.Log($"Handling of type: {message.ActionType} started for user ID {message.UserId}, revision ID {message.RevisionId} with message {message.ToJSON()}", message, tenant, LogLevel.Debug);

            var repository = (IGenerateActionsRepository)baseRepository;

            var generateProcessTestInfos = new List <GenerateProcessTestInfo>
            {
                new GenerateProcessTestInfo
                {
                    ProcessId = message.ArtifactId
                }
            };
            var parameters = SerializationHelper.ToXml(generateProcessTestInfos);

            var user = await repository.GetUser(message.UserId);

            Logger.Log($"Retrieved user: {user?.Login}", message, tenant);

            var jobId = await repository.JobsRepository.AddJobMessage(JobType.GenerateProcessTests,
                                                                      false,
                                                                      parameters,
                                                                      null,
                                                                      message.ProjectId,
                                                                      message.ProjectName,
                                                                      message.UserId,
                                                                      user?.Login,
                                                                      message.BaseHostUri);

            if (jobId.HasValue)
            {
                Logger.Log($"Job scheduled for {message.ActionType} with id: {jobId.Value}", message, tenant);
            }
            else
            {
                Logger.Log("No jobId received", message, tenant);
            }

            return(jobId.HasValue && jobId > 0);
        }
        public async Task <bool> HandleWorkflowsChangedAction(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository, IWorkflowMessagingProcessor workflowMessagingProcessor)
        {
            var message    = (WorkflowsChangedMessage)actionMessage;
            var repository = (IWorkflowsChangedRepository)baseRepository;

            Logger.Log("Getting affected artifact IDs", message, tenant);
            var workflowIds = new[]
            {
                message.WorkflowId
            };
            var artifactIds = await repository.GetAffectedArtifactIds(workflowIds, message.RevisionId);

            await ArtifactsChangedMessageSender.Send(artifactIds, tenant, actionMessage, workflowMessagingProcessor);

            return(true);
        }
Exemplo n.º 13
0
        public void TestInitialize()
        {
            var artifactIds = new[]
            {
                1
            };

            _message = new ArtifactsChangedMessage(artifactIds)
            {
                ChangeType = ArtifactChangedType.Save,
                RevisionId = 12,
                UserId     = 34
            };
            _repositoryMock    = new Mock <IArtifactsChangedRepository>(MockBehavior.Strict);
            _helper            = new ArtifactsChangedActionHelper();
            _tenantInformation = new TenantInformation();
        }
        protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var message    = (ProjectsChangedMessage)actionMessage;
            var repository = (ProjectsChangedRepository)baseRepository;

            Logger.Log("Getting affected artifact IDs", message, tenant);
            var artifactIds = await repository.GetAffectedArtifactIds();

            if (!artifactIds.Any())
            {
                Logger.Log("No artifact IDs found", message, tenant);
                return(false);
            }
            Logger.Log($"Found artifact IDs {string.Join(",", artifactIds)}", message, tenant);

            return(true);
        }
        protected override async Task <bool> PreActionValidation(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var projectContainerActionMessage = actionMessage as ProjectContainerActionMessage;

            if (projectContainerActionMessage == null)
            {
                Logger.Log("The message is not a projectContainerActionMessage", actionMessage, tenant, LogLevel.Error);
                return(false);
            }
            var isProjectMaxArtifactBoundaryReached = await baseRepository.IsProjectMaxArtifactBoundaryReached(projectContainerActionMessage.ProjectId);

            if (isProjectMaxArtifactBoundaryReached)
            {
                Logger.Log($"Max artifact boundary for project {projectContainerActionMessage.ProjectId} has been reached", projectContainerActionMessage, tenant, LogLevel.Error);
            }
            return(!isProjectMaxArtifactBoundaryReached);
        }
Exemplo n.º 16
0
        public async Task <HttpResponseMessage> SendWebhook(TenantInformation tenant, WebhookMessage message)
        {
            try
            {
                var webhookUri         = new Uri(message.Url);
                var httpClientProvider = new HttpClientProvider();
                var httpClient         = httpClientProvider.CreateWithCustomCertificateValidation(webhookUri, message.IgnoreInvalidSSLCertificate, ConfigHelper.WebhookConnectionTimeout);

                var request = new HttpRequestMessage
                {
                    RequestUri = webhookUri,
                    Method     = HttpMethod.Post,
                    Content    = new StringContent(message.WebhookJsonPayload, Encoding.UTF8, "application/json")
                };

                AddHttpHeaders(request, message, tenant);

                AddBasicAuthentication(request, message, tenant);

                AddSignatureAuthentication(request, message, tenant);

                AddNServiceBusHeaders(request, message, tenant);

                return(await httpClient.SendAsync(request));
            }
            catch (HttpRequestException e)
            {
                if (e.InnerException is WebException)
                {
                    var webException = (WebException)e.InnerException;
                    if (webException.Status == WebExceptionStatus.TrustFailure)
                    {
                        throw new WebhookExceptionRetryPerPolicy($"Failed to send webhook due to invalid SSL Certificate. {webException.Message}.");
                    }
                    else
                    {
                        throw new WebhookExceptionRetryPerPolicy($"Failed to send webhook due {webException.Status}. {webException.Message} {webException.Response}");
                    }
                }
                else
                {
                    throw new WebhookExceptionRetryPerPolicy($"Failed to send webhook due to {e.InnerException}.");
                }
            }
        }
 public void TestInitialize()
 {
     _tenantInformation = new TenantInformation
     {
         TenantId = Guid.NewGuid().ToString(),
         BlueprintConnectionString = ""
     };
     _notificationMessage = new NotificationMessage
     {
         ArtifactId             = 1,
         ArtifactName           = "MyArtifact",
         ArtifactTypeId         = 2,
         ArtifactTypePredefined = (int)ItemTypePredefined.Process,
         ArtifactUrl            = "",
         From = "*****@*****.**",
         To   = new[]
         {
             "*****@*****.**"
         },
         Header       = "header",
         Message      = "",
         ProjectId    = 3,
         ProjectName  = "MyProject",
         RevisionId   = 5,
         Subject      = "Test Email",
         UserId       = 1,
         BlueprintUrl = ""
     };
     _emailSettings = new EmailSettings
     {
         HostName           = "localhost",
         Id                 = "1",
         EnableSSL          = true,
         Authenticated      = true,
         EnableAllUsers     = true,
         UserName           = "******",
         Password           = "",
         Port               = 227,
         SenderEmailAddress = "*****@*****.**"
     };
     _notificationRepositoryMock = new Mock <INotificationRepository>(MockBehavior.Strict);
     _notificationsActionHelper  = new NotificationsActionHelper();
 }
        protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var message = (ArtifactsPublishedMessage)actionMessage;

            Logger.Log($"Handling started for user ID {message.UserId}, revision ID {message.RevisionId} with message {message.ToJSON()}", message, tenant, LogLevel.Debug);

            var repository = (IArtifactsPublishedRepository)baseRepository;

            var serviceLogRepository = new ServiceLogRepository(new HttpClientProvider(),
                                                                new LocalFileLog(),
                                                                tenant.AdminStoreLog);

            // Get modified properties for all artifacts and create a dictionary with key as artifact ids
            bool handledAllUpdatedArtifacts = await UpdatedArtifactsNotificationHandler.ProcessUpdatedArtifacts(tenant,
                                                                                                                message,
                                                                                                                repository,
                                                                                                                serviceLogRepository,
                                                                                                                _actionsParser,
                                                                                                                WorkflowMessagingProcessor.Instance);

            if (!handledAllUpdatedArtifacts)
            {
                Logger.Log("Could not process messages for all published updated artifacts", message, tenant, LogLevel.Debug);
            }
            Logger.Log("Finished processing updated artifacts", message, tenant);

            var handledAllCreatedArtifacts =
                await
                CreatedArtifactsNotificationHandler.ProcessCreatedArtifacts(tenant,
                                                                            message,
                                                                            repository,
                                                                            serviceLogRepository,
                                                                            WorkflowMessagingProcessor.Instance);

            if (!handledAllCreatedArtifacts)
            {
                Logger.Log("Could not process messages for all published created artifacts", message, tenant, LogLevel.Debug);
            }
            Logger.Log("Finished processing created artifacts", message, tenant);

            Logger.Log("Finished processing message", message, tenant, LogLevel.Debug);
            return(handledAllUpdatedArtifacts && handledAllCreatedArtifacts);
        }
Exemplo n.º 19
0
        protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var message     = (ArtifactsChangedMessage)actionMessage;
            var repository  = (IArtifactsChangedRepository)baseRepository;
            var artifactIds = message.ArtifactIds?.ToList();

            if (artifactIds == null || !artifactIds.Any())
            {
                Logger.Log("The Artifacts Changed Message contains no artifact IDs", message, tenant);
                return(false);
            }

            Logger.Log($"Handling Artifacts Changed Message with change type {message.ChangeType} and {artifactIds.Count} artifact IDs: {string.Join(", ", artifactIds)}", message, tenant);
            Logger.Log("Started repopulating search items", message, tenant);
            await repository.RepopulateSearchItems(artifactIds);

            Logger.Log("Finished repopulating search items", message, tenant);
            return(true);
        }
        public async Task <bool> HandleUsersGroupsChangedAction(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository, IWorkflowMessagingProcessor workflowMessagingProcessor)
        {
            var message    = (UsersGroupsChangedMessage)actionMessage;
            var repository = (IUsersGroupsChangedRepository)baseRepository;

            Logger.Log($"Handling Users Groups Changed Message for change type {message.ChangeType}", message, tenant);

            if (message.ChangeType == UsersGroupsChangedType.Create)
            {
                Logger.Log("No need to send Artifacts Changed Messages when Creating Users or Groups", message, tenant);
                return(true);
            }

            Logger.Log("Getting affected artifact IDs", message, tenant);
            var artifactIds = await repository.GetAffectedArtifactIds(message.UserIds, message.GroupIds, message.RevisionId);

            await ArtifactsChangedMessageSender.Send(artifactIds, tenant, actionMessage, workflowMessagingProcessor);

            return(true);
        }
Exemplo n.º 21
0
        public async Task <TransactionStatus> GetStatus(ActionMessage message, TenantInformation tenant, IBaseRepository repository)
        {
            var transactionId = message.TransactionId;
            var tries         = 1;

            while (true)
            {
                var status = await repository.GetTransactionStatus(transactionId);

                if (!Enum.IsDefined(typeof(TransactionStatus), status))
                {
                    throw new ArgumentOutOfRangeException($"Invalid Transaction Status: {status}");
                }
                var transactionStatus = (TransactionStatus)status;
                switch (transactionStatus)
                {
                case TransactionStatus.Committed:
                    Logger.Log($"Transaction {transactionId} has been committed", message, tenant);
                    return(transactionStatus);

                case TransactionStatus.Uncommitted:
                    if (tries < TriesMax)
                    {
                        Logger.Log($"Transaction {transactionId} is uncommitted. Trying again", message, tenant);
                        Thread.Sleep(MillisecondsTimeout);
                        tries++;
                        continue;
                    }
                    var errorMessage = $"Transaction {transactionId} is still uncommitted. Unable to handle the message at this time";
                    Logger.Log(errorMessage, message, tenant);
                    throw new EntityNotFoundException(errorMessage);

                case TransactionStatus.RolledBack:
                    Logger.Log($"Transaction {transactionId} was rolled back. The message will not be handled", message, tenant);
                    return(transactionStatus);

                default:
                    throw new ArgumentOutOfRangeException($"Unhandled Transaction Status {transactionStatus}");
                }
            }
        }
Exemplo n.º 22
0
        public void BaseMessageHandler_ThrowsException_WhenTheRightTenantIsNotFound()
        {
            // arrange
            var tenant = new TenantInformation
            {
                TenantId = TenantId + "different"
            };
            var wrongTenant = new Dictionary <string, TenantInformation>
            {
                { tenant.TenantId, tenant }
            };

            _tenantInfoRetrieverMock.Setup(m => m.GetTenants()).ReturnsAsync(wrongTenant);
            var handler = new NotificationMessageHandler(_actionHelperMock.Object, _tenantInfoRetrieverMock.Object, _configHelperMock.Object, _transactionValidatorMock.Object);
            var message = new NotificationMessage();

            // act
            TestHandlerAndMessageWithHeader(handler, message);
            // assert
            _actionHelperMock.Verify(m => m.HandleAction(It.IsAny <TenantInformation>(), It.IsAny <ActionMessage>(), It.IsAny <BaseRepository>()), Times.Never);
        }
Exemplo n.º 23
0
 public void TestInitialize()
 {
     _jobsRepositoryMock            = new Mock <IJobsRepository>(MockBehavior.Strict);
     _generateActionsRepositoryMock = new Mock <IGenerateActionsRepository>(MockBehavior.Strict);
     _actionHelper = new GenerateUserStoriesActionHelper();
     _message      = new GenerateUserStoriesMessage
     {
         UserId      = 123,
         UserName    = "******",
         ArtifactId  = 23,
         BaseHostUri = "http://localhost:9801",
         ProjectId   = 123,
         ProjectName = "my project",
         RevisionId  = 123
     };
     _tenantInformation = new TenantInformation
     {
         BlueprintConnectionString = "TestBlueprintConnectionString",
         TenantId = "TestTenantId"
     };
 }
Exemplo n.º 24
0
        public async Task HandleAction_WhenAncestorInfiniteLoopExists_ReturnsFalse()
        {
            // arrange
            const int duplicateId            = 11;
            var       ancestorsWithDuplicate = new[]
            {
                duplicateId,
                12,
                13,
                14,
                duplicateId
            };
            var generateDescendantsMessage = new GenerateDescendantsMessage
            {
                AncestorArtifactTypeIds = ancestorsWithDuplicate,
                ArtifactId            = ArtifactId,
                BaseHostUri           = "uri",
                ChildCount            = 1,
                DesiredArtifactTypeId = DesiredArtifactTypeId,
                ProjectId             = ProjectId,
                ProjectName           = "project",
                RevisionId            = RevisionId,
                TypePredefined        = 1,
                UserId   = UserId,
                UserName = UserName
            };

            _generateActionsRepositoryMock.Setup(m => m.IsProjectMaxArtifactBoundaryReached(It.IsAny <int>())).ReturnsAsync(false);
            var tenantInformation = new TenantInformation();
            var actionHelper      = new GenerateDescendantsActionHelper();

            // act
            var result = await actionHelper.HandleAction(tenantInformation, generateDescendantsMessage, _generateActionsRepositoryMock.Object);

            // assert
            Assert.IsFalse(result, "Children should not have been generated.");
            _jobsRepoMock.Verify(t => t.AddJobMessage(It.IsAny <JobType>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int?>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>()), Times.Never);
        }
Exemplo n.º 25
0
        public void TestInitialize()
        {
            _actionHelperMock = new Mock <IActionHelper>(MockBehavior.Strict);

            _configHelperMock = new Mock <IConfigHelper>(MockBehavior.Strict);
            _configHelperMock.Setup(m => m.SupportedActionTypes).Returns(MessageActionType.All);

            _tenantInfoRetrieverMock = new Mock <ITenantInfoRetriever>(MockBehavior.Strict);
            var tenant = new TenantInformation
            {
                TenantId = TenantId,
                BlueprintConnectionString = "test connection string"
            };
            var tenants = new Dictionary <string, TenantInformation>
            {
                { tenant.TenantId, tenant }
            };

            _tenantInfoRetrieverMock.Setup(m => m.GetTenants()).ReturnsAsync(tenants);

            _transactionValidatorMock = new Mock <ITransactionValidator>(MockBehavior.Strict);
            _transactionValidatorMock.Setup(m => m.GetStatus(It.IsAny <ActionMessage>(), It.IsAny <TenantInformation>(), It.IsAny <BaseRepository>())).ReturnsAsync(TransactionStatus.Committed);
        }
Exemplo n.º 26
0
        protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var message = (WebhookMessage)actionMessage;

            var result = await SendWebhook(tenant, message);

            if (result.IsSuccessStatusCode)
            {
                Logger.Log($"Finished processing webhook with result: {result.StatusCode}", message, tenant);
                return(true);
            }

            if (result.StatusCode == HttpStatusCode.Gone)
            {
                Logger.Log($"Failed to send webhook. Will not try again.", message, tenant, LogLevel.Error);
                throw new WebhookExceptionDoNotRetry($"Failed to send webhook.");
            }
            else
            {
                Logger.Log($"Failed to send webhook. {(int)result.StatusCode} - {result.StatusCode}. Will try again in {ConfigHelper.WebhookRetryInterval} seconds.",
                           message, tenant, LogLevel.Error);
                throw new WebhookExceptionRetryPerPolicy($"Failed to send webhook");
            }
        }
        private async Task <SendEmailResult> SendNotificationEmail(TenantInformation tenant, NotificationMessage message, INotificationRepository repository)
        {
            Logger.Log($"Handling started for user ID {message.UserId} with message {message.ToJSON()}", message, tenant);

            if (message.To == null || !message.To.Any() || message.To.All(string.IsNullOrWhiteSpace))
            {
                Logger.Log("Failed to send email because no recipients were specified", message, tenant, LogLevel.Error);
                return(await Task.FromResult(SendEmailResult.Error));
            }

            Logger.Log("Getting email settings", message, tenant);
            var emailSettings = await repository.GetEmailSettings();

            if (emailSettings == null || string.IsNullOrWhiteSpace(emailSettings.HostName))
            {
                Logger.Log($"Failed to send email because invalid email settings were provided for tenant {tenant.TenantId}", message, tenant, LogLevel.Error);
                return(await Task.FromResult(SendEmailResult.Error));
            }
            Logger.Log($"Email settings found. Host Name: {emailSettings.HostName}. Sender Email Address: {emailSettings.SenderEmailAddress}. User Name: {emailSettings.UserName}", message, tenant);

            // Get the logo
            byte[] logoImageArray = new LogoDataProvider().GetLogo();
            string logoImageSrc   = null;

            if (logoImageArray != null)
            {
                logoImageSrc = GetImageSrc(logoImageArray, DiscussionEmail.LogoImageAttachmentContentId);
            }

            var notificationEmail = new NotificationEmail(
                message.ProjectId,
                message.ProjectName,
                message.ArtifactId,
                message.ArtifactName,
                message.ArtifactUrl,
                message.Message,
                message.Header,
                logoImageSrc,
                message.BlueprintUrl);

            var emailMessage = new Message
            {
                Subject         = message.Subject,
                FromDisplayName = message.From,
                To         = message.To.ToArray(),
                From       = emailSettings.SenderEmailAddress,
                IsBodyHtml = true,
                Body       = new NotificationEmailContent(notificationEmail).TransformText()
            };

            if (logoImageArray != null)
            {
                emailMessage.DiscussionEmail = new DiscussionEmail
                {
                    LogoImageSrc             = logoImageSrc,
                    LogoImageAttachmentArray = logoImageArray
                };
            }

            var smtpClientConfiguration = new SMTPClientConfiguration
            {
                Authenticated = emailSettings.Authenticated,
                EnableSsl     = emailSettings.EnableSSL,
                HostName      = emailSettings.HostName,
                // Bug 61312: Password must be decrypted before saving in configuration
                Password = SystemEncryptions.DecryptFromSilverlight(emailSettings.Password),
                Port     = emailSettings.Port,
                UserName = emailSettings.UserName
            };

            if (string.IsNullOrWhiteSpace(smtpClientConfiguration.HostName))
            {
                Logger.Log("Sending email failed because no host name was found. Check your email settings", message, tenant, LogLevel.Error);
                return(await Task.FromResult(SendEmailResult.Error));
            }

            Logger.Log($"Sending Email to {string.Join(",", emailMessage.To)}", message, tenant);
            repository.SendEmail(smtpClientConfiguration, emailMessage);
            Logger.Log("Email Sent Successfully", message, tenant);
            return(await Task.FromResult(SendEmailResult.Success));
        }
Exemplo n.º 28
0
        protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
        {
            var message = (GenerateDescendantsMessage)actionMessage;

            if (message == null || message.ArtifactId <= 0 || message.ProjectId <= 0 || message.RevisionId <= 0 || message.UserId <= 0 || message.DesiredArtifactTypeId == null || string.IsNullOrWhiteSpace(message.UserName) || tenant == null)
            {
                Logger.Log($"Invalid GenerateDescendantsMessage received: {message?.ToJSON()}", message, tenant, LogLevel.Error);
                return(false);
            }

            Logger.Log($"Handling of type: {message.ActionType} started for user ID {message.UserId}, revision ID {message.RevisionId} with message {message.ToJSON()}", message, tenant, LogLevel.Debug);

            var ancestors = new List <int>(message.AncestorArtifactTypeIds ?? new int[0]);

            Logger.Log($"{ancestors.Count} ancestor artifact type IDs found: {string.Join(",", ancestors)}", message, tenant, LogLevel.Debug);
            var ancestorLoopExists = ancestors.GroupBy(i => i).Any(group => group.Count() > 1);

            if (ancestorLoopExists)
            {
                Logger.Log("Child generation was stopped. Infinite loop detected in the ancestor artifact type IDs.", message, tenant, LogLevel.Debug);
                return(false);
            }

            var repository            = (IGenerateActionsRepository)baseRepository;
            var sqlItemTypeRepository = repository.ItemTypeRepository;
            var desiredItemType       = await sqlItemTypeRepository.GetCustomItemTypeForProvidedStandardItemTypeIdInProject(message.ProjectId, message.DesiredArtifactTypeId.GetValueOrDefault());

            if (desiredItemType == null || desiredItemType.ItemTypeId <= 0 || string.IsNullOrWhiteSpace(desiredItemType.Name))
            {
                Logger.Log($"No artifact type found with instance Id: {message.DesiredArtifactTypeId.GetValueOrDefault()} in Project: {message.ProjectId}", message, tenant);
                return(false);
            }

            var generateDescendantsInfo = new GenerateDescendantsInfo
            {
                RevisionId              = message.RevisionId,
                ProjectId               = message.ProjectId,
                ArtifactId              = message.ArtifactId,
                UserId                  = message.UserId,
                ChildCount              = message.ChildCount,
                DesiredArtifactTypeId   = desiredItemType.ItemTypeId,
                Predefined              = (ItemTypePredefined)message.TypePredefined,
                DesiredArtifactTypeName = desiredItemType.Name,
                AncestorArtifactTypeIds = message.AncestorArtifactTypeIds?.ToArray()
            };

            var parameters = SerializationHelper.ToXml(generateDescendantsInfo);

            var user = await repository.GetUser(message.UserId);

            Logger.Log($"Retrieved user: {user?.Login}", message, tenant);

            var jobId = await repository.JobsRepository.AddJobMessage(JobType.GenerateDescendants,
                                                                      false,
                                                                      parameters,
                                                                      null,
                                                                      message.ProjectId,
                                                                      message.ProjectName,
                                                                      message.UserId,
                                                                      user?.Login, // Login is equal to username
                                                                      message.BaseHostUri);

            if (jobId.HasValue)
            {
                Logger.Log($"Job scheduled for {message.ActionType} with id: {jobId.Value}", message, tenant);
            }
            else
            {
                Logger.Log("No jobId received", message, tenant);
            }

            return(jobId.HasValue && jobId > 0);
        }
 public AccountAndTenant(Account account, TenantInformation tenant)
 {
     UserAccount = account;
     TenantToUse = tenant;
 }
 protected override async Task <bool> HandleActionInternal(TenantInformation tenant, ActionMessage actionMessage, IBaseRepository baseRepository)
 {
     return(await HandleUsersGroupsChangedAction(tenant, actionMessage, baseRepository, WorkflowMessagingProcessor.Instance));
 }