예제 #1
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="environment"></param>
 /// <param name="options"></param>
 /// <param name="section"></param>
 public WritableOptions(
     IHostingEnvironment environment,
     IOptionsMonitor <T> options,
     string section)
 {
     _environment = environment;
     _options     = options;
     _section     = section;
     _file        = ResourceProvider.AppSettingsFilepath(environment);
 }
예제 #2
0
 /// <summary>
 /// Get settings
 /// </summary>
 public static AppSettingsModel.RootObject Settings(IHostingEnvironment hostingEnvironment)
 => JsonParser.ReadObjectDataFromJsonFile <AppSettingsModel.RootObject>(
     ResourceProvider.AppSettingsFilepath(hostingEnvironment));
        /// <summary>
        /// Add language
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel AddLanguage(AddLanguageViewModel model)
        {
            var response = new ResultModel {
                IsSuccess = true
            };
            var existsInConfig =
                _locConfig.Value.Languages.Any(m => m.Identifier == model.Identifier && m.Name == model.Name);

            var cPaths = new[]
            {
                _env.ContentRootPath,
                _locConfig.Value.Path,
                $"{model.Identifier}.json"
            };

            var filePath   = Path.Combine(cPaths);
            var fileExists = File.Exists(filePath);

            if (existsInConfig || fileExists)
            {
                response.Errors.Add(new ErrorModel
                {
                    Key     = string.Empty,
                    Message = "Language already exists."
                });
                response.IsSuccess = false;
            }
            else
            {
                using (Stream stream =
                           new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                    using (var sWriter = new StreamWriter(stream))
                        using (var writer = new JsonTextWriter(sWriter))
                        {
                            var keys = _localizer.GetAllForLanguage("en").ToList();
                            var dict = new Dictionary <string, string>();
                            foreach (var item in keys)
                            {
                                var translated = _externalTranslationProvider.TranslateText(item.Value, "en", model.Identifier);
                                dict.Add(item.Name, translated);
                            }
                            var obj = JObject.FromObject(dict);

                            writer.Formatting = Formatting.Indented;
                            obj.WriteTo(writer);
                        }

                var langsFile = _env.ContentRootFileProvider.GetFileInfo(ResourceProvider.AppSettingsFilepath(_env));

                using (Stream str = new FileStream(langsFile.PhysicalPath, FileMode.Open, FileAccess.Read,
                                                   FileShare.ReadWrite))
                    using (var sReader = new StreamReader(str))
                        using (var reader = new JsonTextReader(sReader))
                        {
                            var fileObj = JObject.Load(reader);
                            _locConfig.Value.Languages.Add(new LanguageCreateViewModel
                            {
                                Identifier = model.Identifier,
                                Name       = model.Name,
                                IsDisabled = false
                            });
                            var newLangs = JArray.FromObject(_locConfig.Value.Languages);
                            fileObj[nameof(LocalizationConfig)][nameof(LocalizationConfig.Languages)] = newLangs;
                            reader.Close();
                            File.WriteAllText(langsFile.PhysicalPath, fileObj.ToString());
                        }
            }

            return(response);
        }
        /// <summary>
        /// Change status of language
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel ChangeStatusOfLanguage(LanguageCreateViewModel model)
        {
            var response = new ResultModel {
                IsSuccess = true
            };
            var existsInConfig =
                _locConfig.Value.Languages.Any(m => m.Identifier == model.Identifier && m.Name == model.Name);

            var cPaths = new[]
            {
                _env.ContentRootPath,
                _locConfig.Value.Path,
                $"{model.Identifier}.json"
            };

            var filePath   = Path.Combine(cPaths);
            var fileExists = File.Exists(filePath);

            if (existsInConfig || fileExists)
            {
                var langsFile = _env.ContentRootFileProvider.GetFileInfo(ResourceProvider.AppSettingsFilepath(_env));
                using (Stream str = new FileStream(langsFile.PhysicalPath, FileMode.Open, FileAccess.Read,
                                                   FileShare.ReadWrite))
                    using (var sReader = new StreamReader(str))
                        using (var reader = new JsonTextReader(sReader))
                        {
                            var fileObj   = JObject.Load(reader);
                            var languages = _locConfig.Value.Languages;
                            var updLangs  = new HashSet <LanguageCreateViewModel>();
                            foreach (var e in languages)
                            {
                                if (e.Identifier == model.Identifier)
                                {
                                    updLangs.Add(new LanguageCreateViewModel
                                    {
                                        Identifier = model.Identifier,
                                        Name       = model.Name,
                                        IsDisabled = model.IsDisabled
                                    });
                                }
                                else
                                {
                                    updLangs.Add(new LanguageCreateViewModel
                                    {
                                        Identifier = e.Identifier,
                                        Name       = e.Name,
                                        IsDisabled = e.IsDisabled
                                    });
                                }
                            }

                            var updatedLangs = JObject
                                               .FromObject(new LocalizationConfigModel
                            {
                                DefaultLanguage     = _locConfig.Value.DefaultLanguage,
                                Languages           = updLangs,
                                Path                = _locConfig.Value.Path,
                                SessionStoreKeyName = _locConfig.Value.SessionStoreKeyName
                            });

                            fileObj[nameof(LocalizationConfig)] = updatedLangs;
                            reader.Close();
                            File.WriteAllText(langsFile.PhysicalPath, fileObj.ToString());
                        }
            }
            else
            {
                response.IsSuccess = false;
                response.Errors.Add(new ErrorModel
                {
                    Key     = string.Empty,
                    Message = "Language does exists"
                });
            }

            return(response);
        }
예제 #5
0
        /// <summary>
        /// Install gear settings
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual async Task <ResultModel> InstallAsync(SetupModel model)
        {
            var response = new ResultModel();
            var settings = GearWebApplication.Settings(_hostingEnvironment);

            TableQueryBuilder instance = null;

            switch (model.DataBaseType)
            {
            case DbProviderType.MsSqlServer:
                instance = new MsSqlTableQueryBuilder();
                settings.ConnectionStrings.Provider = DbProvider.SqlServer;
                break;

            case DbProviderType.PostgreSql:
                instance = new NpgTableQueryBuilder();
                settings.ConnectionStrings.Provider = DbProvider.PostgreSQL;
                break;
            }

            if (instance == null)
            {
                response.Errors.Add(new ErrorModel(string.Empty, "No provider registered"));
                return(response);
            }

            var(isConnected, error) = instance.IsSqlServerConnected(model.DatabaseConnectionString);
            if (!isConnected)
            {
                response.Errors.Add(new ErrorModel(string.Empty, error));
                return(response);
            }

            settings.ConnectionStrings.ConnectionString = model.DatabaseConnectionString;

            var tenantMachineName = TenantUtils.GetTenantMachineName(model.Organization.Name);

            if (string.IsNullOrEmpty(tenantMachineName))
            {
                response.Errors.Add(new ErrorModel(string.Empty, "Invalid name for organization"));
                return(response);
            }
            settings.IsConfigured = true;
            settings.SystemConfig.MachineIdentifier = $"_{tenantMachineName}_";
            var result = JsonConvert.SerializeObject(settings, Formatting.Indented);

            GearWebApplication.InitModulesMigrations();
            await System.IO.File.WriteAllTextAsync(ResourceProvider.AppSettingsFilepath(_hostingEnvironment), result);

            await _permissionService.SetOrResetPermissionsOnCacheAsync();

            var tenant =
                await _applicationDbContext.Tenants.FirstOrDefaultAsync(x => x.MachineName == tenantMachineName || x.Id == GearSettings.TenantId);

            if (tenant == null)
            {
                response.Errors.Add(new ErrorModel(string.Empty, "Something went wrong"));
                return(response);
            }

            tenant.Name    = model.Organization.Name;
            tenant.SiteWeb = model.Organization.SiteWeb;
            _applicationDbContext.Tenants.Update(tenant);

            //Set user settings
            var superUser = await _signInManager.UserManager.Users.FirstOrDefaultAsync();

            if (superUser != null)
            {
                superUser.UserName      = model.SysAdminProfile.UserName;
                superUser.Email         = model.SysAdminProfile.Email;
                superUser.UserFirstName = model.SysAdminProfile.FirstName;
                superUser.UserLastName  = model.SysAdminProfile.LastName;

                var hasher         = new PasswordHasher <GearUser>();
                var hashedPassword = hasher.HashPassword(superUser, model.SysAdminProfile.Password);
                superUser.PasswordHash = hashedPassword;
                await _signInManager.UserManager.UpdateAsync(superUser);
            }

            var contextRequest = await _applicationDbContext.PushAsync();

            if (!contextRequest.IsSuccess)
            {
                return(contextRequest);
            }

            GearApplication.BackgroundTaskQueue.PushBackgroundWorkItemInQueue(async x =>
            {
                var service = x.InjectService <IDynamicService>();
                //Register in memory types
                await service.RegisterInMemoryDynamicTypesAsync();
            });

            //Send welcome message to user
            await _notify.SendNotificationAsync(new List <Guid>
            {
                superUser?.Id.ToGuid() ?? Guid.Empty
            },
                                                new Notification
            {
                Subject            = $"Welcome to Gear App {model.SysAdminProfile.FirstName} {model.SysAdminProfile.LastName}",
                Content            = "The GEAR app is an integration system with your company's business, it has the skills to develop new applications, and allows you to create from the visual environment.",
                NotificationTypeId = NotificationType.Info
            });

            //sign in user
            await _signInManager.PasswordSignInAsync(superUser, model.SysAdminProfile.Password, true, false);

            response.IsSuccess = true;
            GearApplication.AppState.InstallOnProgress = false;
            GearApplication.AppState.Installed         = true;
            GearApplication.BackgroundTaskQueue.AddToExecutePendingBackgroundWorkItems();
            return(response);
        }