コード例 #1
0
        public static User CreateTestUser(Guid accountId, string password = null)
        {
            using (var dispatcherContext = DispatcherContext.Create())
            {
                var userService = dispatcherContext.UserService;
                var login       = "******" + Guid.NewGuid();
                var user        = new User()
                {
                    Login      = login,
                    LastName   = login,
                    FirstName  = login,
                    MiddleName = login,
                    Post       = "Post"
                };

                if (!string.IsNullOrEmpty(password))
                {
                    user.PasswordHash = PasswordHelper.GetPasswordHashString(password);
                }

                // должны быть уникальные, т.к. это используется юнит-тестах уведомлений на смс
                var phone = Guid.NewGuid().ToString();

                user.UserContacts.Add(new UserContact()
                {
                    Type  = UserContactType.MobilePhone,
                    Value = phone
                });

                user = userService.CreateUser(user, accountId, false);
                return(user);
            }
        }
コード例 #2
0
        public static IMetricTypeCacheReadObject CreateTestMetricType(Guid accountId)
        {
            var name = "Counter." + Guid.NewGuid();

            using (var dispatcherContext = DispatcherContext.Create())
            {
                var service = dispatcherContext.MetricService;
                var type    = service.GetOrCreateType(accountId, name);
                return(type);
            }
        }
コード例 #3
0
 public static IUnitTestTypeCacheReadObject CreateTestUnitTestType(Guid accountId)
 {
     using (var dispatcherContext = DispatcherContext.Create())
     {
         var service      = dispatcherContext.UnitTestTypeService;
         var unitTestType = service.GetOrCreateUnitTestType(accountId, new GetOrCreateUnitTestTypeRequestData()
         {
             DisplayName = "Тестовый тип проверки " + Guid.NewGuid(),
             SystemName  = "UnitTestType.Test " + Guid.NewGuid()
         });
         return(unitTestType);
     }
 }
コード例 #4
0
        public static ComponentType CreateRandomComponentType(Guid accountId)
        {
            var guid = Guid.NewGuid().ToString();

            using (var dispatcherContext = DispatcherContext.Create())
            {
                var data = new GetOrCreateComponentTypeRequestData()
                {
                    DisplayName = "display name " + guid,
                    SystemName  = "sysName " + guid
                };
                var type = dispatcherContext.ComponentTypeService.GetOrCreateComponentType(accountId, data);
                return(type);
            }
        }
コード例 #5
0
        public static IMetricCacheReadObject CreateTestMetric(Guid accountId, Guid componentId)
        {
            var type = CreateTestMetricType(accountId);

            using (var dispatcherContext = DispatcherContext.Create())
            {
                var service  = dispatcherContext.MetricService;
                var metricId = service.CreateMetric(accountId, componentId, type.Id);
                return(AllCaches.Metrics.Find(new AccountCacheRequest()
                {
                    AccountId = accountId,
                    ObjectId = metricId
                }));
            }
        }
コード例 #6
0
ファイル: UserService.cs プロジェクト: crazyants/ZidiumServer
        public User CreateUser(User user, Guid accountId, bool sendLetter = true)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (user.Login == null)
            {
                throw new Exception("Не заполнено поле Login");
            }

            var existingLogin = ConfigDbServicesHelper.GetLoginService().GetOneOrNull(accountId, user.Login);

            if (existingLogin != null)
            {
                throw new LoginAlreadyExistsException(user.Login);
            }

            user.SecurityStamp = Guid.NewGuid().ToString();
            user.DisplayName   = user.DisplayName ?? user.Login;

            user.UserContacts.Add(new UserContact()
            {
                Type  = UserContactType.Email,
                Value = user.Login
            });

            foreach (var role in user.Roles)
            {
                role.User = user;
                if (role.Id == Guid.Empty)
                {
                    role.Id = Guid.NewGuid();
                }
            }

            foreach (var contact in user.UserContacts)
            {
                contact.User = user;
                if (contact.Id == Guid.Empty)
                {
                    contact.Id         = Guid.NewGuid();
                    contact.CreateDate = DateTime.Now;
                }
            }

            var accountContext = Context.GetAccountDbContext(accountId);
            var userRepository = accountContext.GetUserRepository();

            userRepository.Add(user);

            ConfigDbServicesHelper.GetLoginService().Add(user.Id, accountId, user.Login);

            Context.SaveChanges();

            // По умолчанию включаем отправку новостей
            var userSettingService = accountContext.GetUserSettingService();

            userSettingService.SendMeNews(user.Id, true);
            Context.SaveChanges();

            // Для нового пользователя нужно создать подписки
            var subscriptionService = new SubscriptionService(Context);

            subscriptionService.CreateDefaultForUser(accountId, user.Id);
            Context.SaveChanges();

            if (sendLetter)
            {
                var token = StartResetPassword(user.Id, false);
                using (var dispatcherContext = DispatcherContext.Create())
                {
                    var userService = dispatcherContext.UserService;
                    userService.SendNewUserLetter(accountId, user.Id, token);
                }
            }

            return(user);
        }
コード例 #7
0
        public static bool UpdateAll(string sectionName, bool isTestEnviroment)
        {
            try
            {
                Initialization.SetServices();
                Provider.SetSectionName(sectionName);
                var connectionString = ConfigurationManager.ConnectionStrings[sectionName].ConnectionString;
                DatabaseService.SetConnectionString(connectionString);
                var provider = Provider.Current();
                provider.Configuration();

                var count = provider.InitializeDb(connectionString);

                bool adminCreated;
                using (var accountDbContext = AccountDbContext.CreateFromConnectionString(connectionString))
                {
                    // обновляем справочники
                    var registrator = new AccountDbDataRegistator(accountDbContext);
                    registrator.RegisterAll();

                    // Проверим, создан ли админ
                    adminCreated = accountDbContext.GetUserRepository().QueryAll().FirstOrDefault(x => x.Roles.Any(y => y.RoleId == RoleId.AccountAdministrators)) != null;
                }

                if (count == 0)
                {
                    _logger.Info("База не изменилась");
                }
                else
                {
                    _logger.Info("База обновлена, установлено миграций: " + count);
                }

                if (adminCreated)
                {
                    _logger.Info("Администратор аккаунта уже создан");
                }
                else
                {
                    var accountInfo = ConfigDbServicesHelper.GetAccountService().GetSystemAccount();

                    using (var context = DispatcherContext.Create())
                    {
                        // создаем root компонент
                        var componentService = context.ComponentService;
                        componentService.CreateRoot(accountInfo.Id, accountInfo.RootId);

                        // создаем админа
                        Console.Write("Укажите EMail администратора: ");
                        var adminEMail = Console.ReadLine();

                        Console.Write("Укажите пароль администратора: ");
                        var adminPassword = Console.ReadLine();

                        var userService = context.UserService;

                        var adminUser = userService.CreateAccountAdmin(
                            accountInfo.Id,
                            adminEMail,
                            null, null, null, null, null);

                        // Установим пароль админа
                        var passwordToken = userService.StartResetPassword(adminUser.Id, false);
                        userService.EndResetPassword(accountInfo.Id, passwordToken, adminPassword);
                        context.SaveChanges();

                        _logger.Info($"Создан пользователь {adminEMail} с паролем {adminPassword}");
                    }

                    // Установим бесконечные лимиты аккаунта
                    var limits = SystemTariffLimits.BaseUnlimited;

                    using (var accountDbContext = AccountDbContext.CreateFromConnectionString(connectionString))
                    {
                        var accountTariffRepository = accountDbContext.GetAccountTariffRepository();
                        var tariffLimitRepository   = accountDbContext.GetTariffLimitRepository();

                        var tariff = new TariffLimit()
                        {
                            Type   = TariffLimitType.Soft,
                            Source = TariffLimitSource.Base,
                            Name   = "Soft",
                            EventsRequestsPerDay     = limits.EventRequestsPerDay,
                            EventsMaxDays            = limits.EventsMaxDays,
                            LogMaxDays               = limits.LogMaxDays,
                            LogSizePerDay            = limits.LogSizePerDay,
                            ComponentsMax            = limits.ComponentsMax,
                            ComponentTypesMax        = limits.ComponentTypesMax,
                            UnitTestTypesMax         = limits.UnitTestTypesMax,
                            HttpUnitTestsMaxNoBanner = limits.HttpChecksMaxNoBanner,
                            UnitTestsMax             = limits.UnitTestsMax,
                            UnitTestsRequestsPerDay  = limits.UnitTestsRequestsPerDay,
                            UnitTestsMaxDays         = limits.UnitTestsMaxDays,
                            MetricsMax               = limits.MetricsMax,
                            MetricsRequestsPerDay    = limits.MetricRequestsPerDay,
                            MetricsMaxDays           = limits.MetricsMaxDays,
                            StorageSizeMax           = limits.StorageSizeMax,
                            SmsPerDay = limits.SmsPerDay,
                        };

                        tariffLimitRepository.Add(tariff);

                        var accountTariff = new AccountTariff()
                        {
                            TariffLimit = tariff
                        };
                        accountTariffRepository.Add(accountTariff);

                        tariff = new TariffLimit()
                        {
                            Type   = TariffLimitType.Hard,
                            Source = TariffLimitSource.Base,
                            Name   = "Hard",
                            EventsRequestsPerDay     = limits.EventRequestsPerDay,
                            EventsMaxDays            = limits.EventsMaxDays,
                            LogMaxDays               = limits.LogMaxDays,
                            LogSizePerDay            = limits.LogSizePerDay,
                            ComponentsMax            = limits.ComponentsMax,
                            ComponentTypesMax        = limits.ComponentTypesMax,
                            UnitTestTypesMax         = limits.UnitTestTypesMax,
                            HttpUnitTestsMaxNoBanner = limits.HttpChecksMaxNoBanner,
                            UnitTestsMax             = limits.UnitTestsMax,
                            UnitTestsRequestsPerDay  = limits.UnitTestsRequestsPerDay,
                            UnitTestsMaxDays         = limits.UnitTestsMaxDays,
                            MetricsMax               = limits.MetricsMax,
                            MetricsRequestsPerDay    = limits.MetricRequestsPerDay,
                            MetricsMaxDays           = limits.MetricsMaxDays,
                            StorageSizeMax           = limits.StorageSizeMax,
                            SmsPerDay = limits.SmsPerDay,
                        };

                        tariffLimitRepository.Add(tariff);

                        accountTariff = new AccountTariff()
                        {
                            TariffLimit = tariff
                        };
                        accountTariffRepository.Add(accountTariff);

                        accountDbContext.SaveChanges();
                    }
                }

                _logger.Info("База успешно обновлена");

                return(true);
            }
            catch (Exception exception)
            {
                _logger.Fatal(exception);
                return(false);
            }
        }
コード例 #8
0
        public void SendUnitTestAfterEnablingComponentTest()
        {
            // Создадим отключенный компонент и проверку до создания диспетчера
            Component component;
            Guid      unitTestId;
            var       account = TestHelper.GetTestAccount();

            using (var dispatcherContext = DispatcherContext.Create())
            {
                var testAccountContext = dispatcherContext.GetAccountDbContext(account.Id);
                var componentService   = dispatcherContext.ComponentService;
                component = componentService.GetOrCreateComponent(account.Id, new GetOrCreateComponentRequestData()
                {
                    DisplayName = Guid.NewGuid().ToString(),
                    SystemName  = Guid.NewGuid().ToString(),
                    TypeId      = SystemComponentTypes.Others.Id
                });
                componentService.DisableComponent(account.Id, component.Id, null, null);

                var unitTestTypeService = dispatcherContext.UnitTestTypeService;
                var unitTestType        = unitTestTypeService.GetOrCreateUnitTestType(account.Id, new GetOrCreateUnitTestTypeRequestData()
                {
                    SystemName  = "Main",
                    DisplayName = "Main"
                });

                var unitTestService = dispatcherContext.UnitTestService;
                var unitTestCache   = unitTestService.GetOrCreateUnitTest(account.Id, new GetOrCreateUnitTestRequestData()
                {
                    ComponentId    = component.Id,
                    SystemName     = Guid.NewGuid().ToString(),
                    DisplayName    = Guid.NewGuid().ToString(),
                    UnitTestTypeId = unitTestType.Id
                });

                unitTestId = unitTestCache.Id;

                unitTestService.SendUnitTestResult(account.Id, new SendUnitTestResultRequestData()
                {
                    UnitTestId            = unitTestCache.Id,
                    Result                = UnitTestResult.Unknown,
                    ActualIntervalSeconds = 60
                });
            }

            // Создадим диспетчер
            var dispatcher = TestHelper.GetDispatcherClient();

            // Включим компонент
            var componentEnableResponse = dispatcher.SetComponentEnable(account.Id, component.Id);

            componentEnableResponse.Check();

            // Проверим, что компонент стал серым
            var getComponentTotalStateResponse = dispatcher.GetComponentTotalState(account.Id, component.Id, true);
            var componentState = getComponentTotalStateResponse.Data;

            Assert.Equal(MonitoringStatus.Unknown, componentState.Status);

            // Отправим проверку
            var sendUnitTestResultResponse = dispatcher.SendUnitTestResult(account.Id, new SendUnitTestResultRequestData()
            {
                UnitTestId            = unitTestId,
                Result                = UnitTestResult.Success,
                ActualIntervalSeconds = 60,
                Message               = "OK"
            });

            sendUnitTestResultResponse.Check();

            // Проверим, что она отправилась
            var getUnitTestStateResponse = dispatcher.GetUnitTestState(account.Id, component.Id, unitTestId);
            var unitTestState            = getUnitTestStateResponse.Data;

            Assert.Equal(MonitoringStatus.Success, unitTestState.Status);

            // Проверим, что компонент стал зелёным
            getComponentTotalStateResponse = dispatcher.GetComponentTotalState(account.Id, component.Id, true);
            componentState = getComponentTotalStateResponse.Data;
            Assert.Equal(MonitoringStatus.Success, componentState.Status);
        }