Exemple #1
0
        public async Task <Result> Create(int nationalSocietyId, CreateTechnicalAdvisorRequestDto createTechnicalAdvisorRequestDto)
        {
            try
            {
                string securityStamp;
                TechnicalAdvisorUser user;
                using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var identityUser = await _identityUserRegistrationService.CreateIdentityUser(createTechnicalAdvisorRequestDto.Email, Role.TechnicalAdvisor);

                    securityStamp = await _identityUserRegistrationService.GenerateEmailVerification(identityUser.Email);

                    user = await CreateTechnicalAdvisorUser(identityUser, nationalSocietyId, createTechnicalAdvisorRequestDto);

                    transactionScope.Complete();
                }

                await _verificationEmailService.SendVerificationEmail(user, securityStamp);

                return(Success(ResultKey.User.Registration.Success));
            }
            catch (ResultException e)
            {
                _loggerAdapter.Debug(e);
                return(e.Result);
            }
        }
Exemple #2
0
        private void ProcessConfig()
        {
            // TODO: [TESTS] (CsvMetricOutput.ProcessConfig) Add tests
            var rootDir = _environment.CurrentDirectory.AppendIfMissing("\\");

            _config.OutputDir = _config.OutputDir
                                .Replace("./", rootDir)
                                .Replace(".\\", rootDir)
                                .Replace("/", "\\")
                                .AppendIfMissing("\\");

            _logger.Debug("Output directory set to: {path}", _config.OutputDir);

            if (!_directory.Exists(_config.OutputDir))
            {
                _directory.CreateDirectory(_config.OutputDir);
            }

            if (!_directory.Exists(_config.OutputDir))
            {
                _logger.Error("Unable to create output directory ({dir}) - disabling output",
                              _config.OutputDir
                              );

                Enabled = false;
                return;
            }

            _csvFileMask = $"{_config.OutputDir}{{yyyy}}\\{{mm}}\\{{dd}}\\";
            if (_config.UseHourlyFolders)
            {
                _csvFileMask += "{hh}\\";
            }
            _csvFileMask += "{yyyy}-{mm}-{dd} {hh}-{mod-min}0.csv";
        }
        public async Task <Result> Archive(int nationalSocietyId)
        {
            var openedProjectsQuery = _nyssContext.Projects.Where(p => p.State == ProjectState.Open);
            var nationalSocietyData = await _nyssContext.NationalSocieties
                                      .Where(ns => ns.Id == nationalSocietyId)
                                      .Where(ns => !ns.IsArchived)
                                      .Select(ns => new
            {
                NationalSociety    = ns,
                HasRegisteredUsers = ns.NationalSocietyUsers.AsQueryable()
                                     .Where(UserNationalSocietyQueries.IsNotDeletedUser)
                                     .Any(uns => uns.UserId != ns.HeadManager.Id),
                HasOpenedProjects = openedProjectsQuery.Any(p => p.NationalSocietyId == ns.Id),
                HeadManagerId     = ns.HeadManager != null
                        ? (int?)ns.HeadManager.Id
                        : null,
                HeadManagerRole = ns.HeadManager != null
                        ? (Role?)ns.HeadManager.Role
                        : null
            })
                                      .SingleAsync();

            if (nationalSocietyData.HasOpenedProjects)
            {
                return(Error(ResultKey.NationalSociety.Archive.ErrorHasOpenedProjects));
            }

            if (nationalSocietyData.HasRegisteredUsers)
            {
                return(Error(ResultKey.NationalSociety.Archive.ErrorHasRegisteredUsers));
            }

            try
            {
                using var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);

                if (nationalSocietyData.HeadManagerId.HasValue)
                {
                    await DeleteHeadManager(nationalSocietyData.NationalSociety.Id, nationalSocietyData.HeadManagerId.Value, nationalSocietyData.HeadManagerRole.Value);
                }

                await RemoveApiKeys(nationalSocietyData.NationalSociety.Id);

                nationalSocietyData.NationalSociety.IsArchived = true;

                await _nyssContext.SaveChangesAsync();

                transactionScope.Complete();

                return(SuccessMessage(ResultKey.NationalSociety.Archive.Success));
            }
            catch (ResultException e)
            {
                _loggerAdapter.Debug(e);
                return(e.Result);
            }
        }
        public async Task <Result> Create(CreateGlobalCoordinatorRequestDto dto)
        {
            try
            {
                string securityStamp;
                GlobalCoordinatorUser user;
                using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    var identityUser = await _identityUserRegistrationService.CreateIdentityUser(dto.Email, Role.GlobalCoordinator);

                    securityStamp = await _identityUserRegistrationService.GenerateEmailVerification(identityUser.Email);

                    var defaultUserApplicationLanguage = await _dataContext.ApplicationLanguages
                                                         .SingleOrDefaultAsync(al => al.LanguageCode == EnglishLanguageCode);

                    user = new GlobalCoordinatorUser
                    {
                        IdentityUserId        = identityUser.Id,
                        EmailAddress          = identityUser.Email,
                        Name                  = dto.Name,
                        PhoneNumber           = dto.PhoneNumber,
                        AdditionalPhoneNumber = dto.AdditionalPhoneNumber,
                        Organization          = dto.Organization,
                        Role                  = Role.GlobalCoordinator,
                        ApplicationLanguage   = defaultUserApplicationLanguage
                    };
                    await _dataContext.AddAsync(user);

                    await _dataContext.SaveChangesAsync();

                    transactionScope.Complete();
                }

                await _verificationEmailService.SendVerificationEmail(user, securityStamp);

                return(Success(ResultKey.User.Registration.Success));
            }
            catch (ResultException e)
            {
                _loggerAdapter.Debug(e);
                return(e.Result);
            }
        }
        public async Task DeleteIdentityUser(string identityUserId)
        {
            var user = await _userManager.FindByIdAsync(identityUserId);

            if (user == null)
            {
                throw new ResultException(ResultKey.User.Registration.UserNotFound);
            }

            var userDeletionResult = await _userManager.DeleteAsync(user);

            if (!userDeletionResult.Succeeded)
            {
                var errorMessages = string.Join(",", userDeletionResult.Errors.Select(x => x.Description));
                _loggerAdapter.Debug($"A user with id {identityUserId} could not be deleted. {errorMessages}");

                throw new ResultException(ResultKey.User.Registration.UnknownError);
            }
        }
        public IActionResult Index()
        {
            _loggerAdapter.Debug("Logs Debug");
            _loggerAdapter.Information("Logs Information");
            _loggerAdapter.Warning("Logs Warning");
            _loggerAdapter.Error("Logs Error");
            _loggerAdapter.Fatal("Logs Fatal");
            _loggerAdapter.WriteMethodInfo("WriteMethodInfo");

            return(View());
        }
Exemple #7
0
        public async Task <Result <int> > Create(int nationalSocietyId, GatewaySettingRequestDto gatewaySettingRequestDto)
        {
            try
            {
                var nationalSocietyExists = await _nyssContext.NationalSocieties.AnyAsync(ns => ns.Id == nationalSocietyId);

                if (!nationalSocietyExists)
                {
                    return(Error <int>(ResultKey.NationalSociety.SmsGateway.NationalSocietyDoesNotExist));
                }

                var apiKeyExists = await _nyssContext.GatewaySettings.AnyAsync(gs => gs.ApiKey == gatewaySettingRequestDto.ApiKey);

                if (apiKeyExists)
                {
                    return(Error <int>(ResultKey.NationalSociety.SmsGateway.ApiKeyAlreadyExists));
                }

                var gatewaySettingToAdd = new GatewaySetting
                {
                    Name              = gatewaySettingRequestDto.Name,
                    ApiKey            = gatewaySettingRequestDto.ApiKey,
                    GatewayType       = gatewaySettingRequestDto.GatewayType,
                    EmailAddress      = gatewaySettingRequestDto.EmailAddress,
                    NationalSocietyId = nationalSocietyId
                };

                await _nyssContext.GatewaySettings.AddAsync(gatewaySettingToAdd);

                await _nyssContext.SaveChangesAsync();

                await UpdateAuthorizedApiKeys();

                return(Success(gatewaySettingToAdd.Id, ResultKey.NationalSociety.SmsGateway.SuccessfullyAdded));
            }
            catch (ResultException exception)
            {
                _loggerAdapter.Debug(exception);
                return(exception.GetResult <int>());
            }
        }
Exemple #8
0
        public async Task <bool> ReceiveReport(Report report)
        {
            if (report == null)
            {
                _loggerAdapter.Error("Received a report with null value.");
                return(false);
            }

            _loggerAdapter.Debug($"Received report: {report}");

            switch (report.ReportSource)
            {
            case ReportSource.SmsEagle:
                await _smsEagleHandler.Handle(report.Content);

                break;

            default:
                _loggerAdapter.Error($"Could not find a proper handler to handle a report '{report}'.");
                break;
            }

            return(true);
        }
Exemple #9
0
 public void Debug(string message)
 {
     Logger.Debug(message);
 }
Exemple #10
0
        public async Task <Result <int> > Create(int nationalSocietyId, ProjectRequestDto projectRequestDto)
        {
            try
            {
                var nationalSocietyData = await _nyssContext.NationalSocieties
                                          .Where(ns => ns.Id == nationalSocietyId)
                                          .Select(ns => new { ns.IsArchived })
                                          .SingleOrDefaultAsync();

                if (nationalSocietyData == null)
                {
                    return(Error <int>(ResultKey.Project.NationalSocietyDoesNotExist));
                }

                if (nationalSocietyData.IsArchived)
                {
                    return(Error <int>(ResultKey.Project.CannotAddProjectInArchivedNationalSociety));
                }

                var healthRiskIdsInDatabase = await _nyssContext.HealthRisks.Select(hr => hr.Id).ToListAsync();

                var healthRiskIdsToAttach = projectRequestDto.HealthRisks.Select(hr => hr.HealthRiskId).ToList();

                if (!healthRiskIdsToAttach.All(healthRiskId => healthRiskIdsInDatabase.Contains(healthRiskId)))
                {
                    return(Error <int>(ResultKey.Project.HealthRiskDoesNotExist));
                }

                var projectToAdd = new Project
                {
                    Name               = projectRequestDto.Name,
                    TimeZone           = projectRequestDto.TimeZoneId,
                    NationalSocietyId  = nationalSocietyId,
                    State              = ProjectState.Open,
                    StartDate          = _dateTimeProvider.UtcNow,
                    EndDate            = null,
                    ProjectHealthRisks = projectRequestDto.HealthRisks.Select(phr => new ProjectHealthRisk
                    {
                        FeedbackMessage = phr.FeedbackMessage,
                        CaseDefinition  = phr.CaseDefinition,
                        HealthRiskId    = phr.HealthRiskId,
                        AlertRule       = new AlertRule
                        {
                            //ToDo: make CountThreshold nullable or change validation
                            CountThreshold      = phr.AlertRuleCountThreshold ?? 0,
                            DaysThreshold       = phr.AlertRuleDaysThreshold,
                            KilometersThreshold = phr.AlertRuleKilometersThreshold
                        }
                    }).ToList(),
                    EmailAlertRecipients = projectRequestDto.EmailAlertRecipients.Select(ar => new EmailAlertRecipient {
                        EmailAddress = ar.Email
                    }).ToList(),
                    SmsAlertRecipients = projectRequestDto.SmsAlertRecipients.Select(ar => new SmsAlertRecipient {
                        PhoneNumber = ar.PhoneNumber
                    }).ToList()
                };

                await _nyssContext.Projects.AddAsync(projectToAdd);

                await _nyssContext.SaveChangesAsync();

                return(Success(projectToAdd.Id, ResultKey.Project.SuccessfullyAdded));
            }
            catch (ResultException exception)
            {
                _loggerAdapter.Debug(exception);
                return(exception.GetResult <int>());
            }
        }