public static async Task <ILocalizationDictionary> Create(string sourceName, string cultureCode, IIocManager iocManager) { var dictionary = new DbLocalizationDictionary(sourceName, CultureInfo.GetCultureInfo(cultureCode)); var dublicateNames = new List <string>(); var providers = iocManager.ResolveAll <ILocalizationProvider>(); foreach (var provider in providers) { foreach (var item in await provider.getLocalizationDicionary(sourceName, cultureCode)) { if (string.IsNullOrEmpty(item.Key)) { throw new LocalizationException(StringLocal.Format("The key is empty in given dictionary.")); } if (dictionary.Contains(item.Key)) { dublicateNames.Add(item.Key); } dictionary[item.Key] = item.Value.NormalizeLineEndings(); } } if (dublicateNames.Count > 0) { throw new LocalizationException( StringLocal.Format("A dictionary can not contain same key twice. There are some duplicated names: " + string.Join(", ", dublicateNames))); } return(dictionary); }
public ProductInfo GetLicenseInfo() { var licenseFilePath = Path.Combine(AppContext.BaseDirectory, @"License"); if (!File.Exists(licenseFilePath)) { throw new LicenseException(StringLocal.Format("License file not found or no license.")); } ProductInfo productInfo; try { var fileInfo = File.ReadAllText(licenseFilePath); productInfo = JsonHelper.DeserializeObject <ProductInfo>(CryptTools.Decrypt(fileInfo, LicenseManager.Secret)); } catch (Exception) { throw new LicenseException(StringLocal.Format("License file not found or no license.")); } if (string.IsNullOrEmpty(productInfo.MainBoardSerialNumber)) { throw new LicenseException(StringLocal.Format("Main board serial number is null or empty.")); } return(productInfo); }
public static void Log(this ILogger logger, LogSeverity severity, Func <string> messageFactory) { switch (severity) { case LogSeverity.Fatal: logger.Fatal(messageFactory); break; case LogSeverity.Error: logger.Error(messageFactory); break; case LogSeverity.Warn: logger.Warn(messageFactory); break; case LogSeverity.Info: logger.Info(messageFactory); break; case LogSeverity.Debug: logger.Debug(messageFactory); break; default: throw new BlocksException(StringLocal.Format("Unknown LogSeverity value: " + severity)); } }
private WebNavigationItemDefinition FillNavUrl(INavigationItemDefinition navDefinitionItem) { if (navDefinitionItem == null) { return(null); } var navItem = navDefinitionItem; if (navItem.NavigationType == 1) { var p = navItem.Name; var navigationUrl = Mvc.Route.RouteHelper.GetUrl(navItem.RouteValues); var permissons = new List <Permission>(); if (navItem.RouteValues.Values.Count() < 3) { throw new BlocksException(StringLocal.Format("Navigation controller or action {0} can't null", navigationUrl)); } var requiredPermissions = new List <Permission>(); if (!navItem.HasPermissions.IsNullOrEmpty()) { requiredPermissions.Add(navItem.HasPermissions.FirstOrDefault()); } return(new WebNavigationItemDefinition(navItem.Name, navItem.DisplayName, Mvc.Route.RouteHelper.GetUrl(navItem.RouteValues), navItem.RequiresAuthentication, requiredPermissions.ToArray() , navItem.CustomData, navItem.IsVisible, navItem.HasPermissions, navItem.RouteValues, navItem.NavigationType )); } return(null); }
static AppConfigManager() { if (!IocManager.Instance.IsRegistered(typeof(IAbpStartupConfiguration))) { throw new ConfigurationException(StringLocal.Format($"Blocks system must be init IAbpStartupConfiguration first")); } AbpConfig = IocManager.Instance.Resolve <IAbpStartupConfiguration>(); }
public IDefaultControllerActionBuilder <T> GetMethod(string methodName) { if (!_actionBuilders.ContainsKey(methodName)) { throw new BlocksException(StringLocal.Format("There is no method with name " + methodName + " in type " + typeof(T).Name)); } return(_actionBuilders[methodName]); }
public static string ToAppRelative(this IFileInfo fileInfo, string appRootPath) { var matchIndex = fileInfo.PhysicalPath.IndexOf(appRootPath); if (matchIndex < 0) { throw new FileSystemsException(StringLocal.Format("ToAppRelative Fail.Current fileInfo could't match \"{0}\" appRootPath.", appRootPath)); } return(fileInfo.PhysicalPath.Remove(0, matchIndex + appRootPath.Length)); }
private async Task <INavigationDefinition> FillNav(INavigationDefinition navigationDefinition) { if (navigationDefinition == null) { throw new BlocksException(StringLocal.Format("There is no menu ")); } var navDefinitionResult = new NavigationDefinition(navigationDefinition); await FillNavItems(navigationDefinition.Items, navDefinitionResult.Items); return(navDefinitionResult); }
public static INavigationDefinition AddBuilder(this INavigationDefinition navItem, Action <NavigationItemBuilder> builderAction) { var navigationItemBuilder = new NavigationItemBuilder(); builderAction(navigationItemBuilder); var navigationItem = navigationItemBuilder.Build(); if (navItem.Items.Any(i => i.GetUniqueId() == navigationItem.GetUniqueId())) { throw new BlocksException(StringLocal.Format("System find navigatiomItems has same Id \"{0}\"", navigationItem.GetUniqueId())); } navItem.AddItem(navigationItem); return(navItem); }
protected virtual IDictionary <Platform, JsonNavigationConfig> GetConfig() { if (filePaths.IsNullOrEmpty()) { throw new BlocksCoreException(StringLocal.Format("filePath is null or empty")); } return(filePaths.ToDictionary(f => f.Key, f => { var a = _webSiteFolder.ListFiles(Extension.VirtualPath + "/Module_Start/Config", true).ToList(); var jsonString = _webSiteFolder.ReadFile(Extension.VirtualPath.TrimStart('~') + "/" + f.Value); return JsonHelper.DeserializeObject <JsonNavigationConfig>(jsonString); })); }
public void Granted() { string processName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName); if (Debugger.IsAttached || ignoredProcess.Any(p => processName.IndexOf(p, StringComparison.OrdinalIgnoreCase) > -1)) { return; } if (this.machineInfo.GetLicenseInfo().MainBoardSerialNumber != this.machineInfo.GetBIOSSerialNumber()) { throw new LicenseException(StringLocal.Format("License file not found or no license.")); } }
public virtual TDbContext GetOrCreateDbContext <TDbContext, TEntity>(MultiTenancySides?multiTenancySide = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide); connectionStringResolveArgs["DbContextType"] = typeof(TDbContext); connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType; var connectionString = ResolveConnectionString(connectionStringResolveArgs); var entityAssemblyId = typeof(TEntity).Assembly.GetName().Name; if (!entityConfigurations.Any(e => string.Equals(e.EntityModule, entityAssemblyId, StringComparison.OrdinalIgnoreCase))) { throw new BlocksDBORMException(StringLocal.Format($"{entityAssemblyId} not found in EntityConfigurations.")); } var moduleName = entityAssemblyId; //extensionManager.GetExtension(typeof(TEntity).Assembly.GetName().Name).Name; var dbContextKey = moduleName + "#" + concreteDbContextType.FullName + "#" + connectionString; DbContext dbContext; if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext)) { if (Options.IsTransactional == true) { dbContext = _transactionStrategy.CreateDbContext <TDbContext>(connectionString, _dbContextResolver, moduleName); } else { dbContext = _dbContextResolver.Resolve <TDbContext>(connectionString, moduleName); } if (Options.Timeout.HasValue && !dbContext.Database.GetCommandTimeout().HasValue) { dbContext.Database.SetCommandTimeout(SafeConvert.ToInt32(Options.Timeout.Value.TotalSeconds)); } //TODO ObjectMaterialize //((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) => //{ // ObjectContext_ObjectMaterialized(dbContext, args); //}; // FilterExecuter.As<IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext); ActiveDbContexts[dbContextKey] = dbContext; } return((TDbContext)dbContext); }
private WebNavigationItemDefinition FillNavUrl(INavigationItemDefinition navDefinitionItem) { if (navDefinitionItem == null) { return(null); } var navItem = navDefinitionItem; var controllerPath = Mvc.Route.RouteHelper.GetControllerPath(navItem.RouteValues); var controllerActionKv = _defaultControllerManager.FindOrNull(controllerPath)?.Actions .FirstOrDefault(a => a.Key == navItem.RouteValues["action"]?.ToString()); // if (navItem.NavigationType == 1) // { // var p = navItem.Name; // var navigationUrl = Mvc.Route.RouteHelper.GetUrl(navItem.RouteValues); // var permissons = new List<Permission>(); // //// var navigationRequirePermission = Permission.Create(p, navigationUrl, "navigation", //// navigationUrl + "/" + p, new LocalizableString(navItem.DisplayName.SourceName, p)); // if(navItem.RouteValues.Values.Count() < 3) // throw new BlocksException(StringLocal.Format("Navigation controller or action {0} can't null",navigationUrl)); // // return new WebNavigationItemDefinition(navItem.Name, // navItem.DisplayName, Mvc.Route.RouteHelper.GetUrl(navItem.RouteValues), navItem.RequiresAuthentication,null // , navItem.CustomData, navItem.IsVisible, navItem.HasPermissions,navItem.RouteValues, navItem.NavigationType // ); // } if (controllerActionKv == null || navDefinitionItem.NavigationType != 0) { return(null); } if (controllerActionKv?.Key == null) { throw new BlocksException(StringLocal.Format("Navigation or action {0} can't found", controllerPath)); } var controllerAction = controllerActionKv.Value.Value; var url = Mvc.Route.RouteHelper.GetUrl(navItem.RouteValues); var requirePermission = controllerAction.GetAuthorize()?.Select(p => Permission.Create(p, url, "navigation", url + "/" + p, new LocalizableString(navItem.DisplayName.SourceName, p))).ToArray(); return(new WebNavigationItemDefinition(navItem.Name, navItem.DisplayName, Mvc.Route.RouteHelper.GetUrl(navItem.RouteValues), navItem.RequiresAuthentication, requirePermission , navItem.CustomData, navItem.IsVisible, navItem.HasPermissions, navItem.RouteValues, navItem.NavigationType )); }
public async Task <UserNavigation> GetMenuAsync(string menuName, IUserIdentifier user) { var navDefinition = _navigationManager.Menus.GetOrDefault(menuName); if (navDefinition == null) { throw new BlocksException(StringLocal.Format("There is no menu with given name: " + menuName)); } var userMenu = new UserNavigation(navDefinition.Name, new List <UserNavigationItem>()); await FilterUserNavigation(user, navDefinition.Items, userMenu.Items); userMenu.Items = userMenu.Items.Where <UserNavigationItem>(i => i.IsVisible).ToList(); return(userMenu); }
private async Task FilterUserNavigation(IUserIdentifier user, IList <INavigationItemDefinition> navDefinitionItems, IList <UserNavigationItem> userMenuItems) { foreach (var navigationItemDefinition in navDefinitionItems) { var webNavItem = navigationItemDefinition as WebNavigationItemDefinition; if (webNavItem == null) { throw new BlocksCoreException(StringLocal.Format("WebNavItem not found")); } if (!await _authorizationService.TryCheckAccess(webNavItem.RequirePermissions, webNavItem.RequiresAuthentication, user)) { continue; } userMenuItems.Add(CreateUserNavItem(user, webNavItem)); } }
public void Initialize() { if (_permissions.Any()) { _permissions.Clear(); } foreach (var provider in _providers) { foreach (var permission in provider.GetPermissions()) { if (_permissions.ContainsKey(permission.ResourceKey)) { throw new PermissionException(StringLocal.Format($"Double permission resourceKey {permission.ResourceKey}")); } _permissions.Add(permission.ResourceKey, permission); } } }
private void validateParameter(LambdaExpression selector) { var keyParameter = selector.Parameters.FirstOrDefault(p => p.Type == typeof(TKey)); if (keyParameter != null && keyParameter.Name != "key") { throw new BlocksDBORMException( StringLocal.Format( "TKey parameter must be named [key].")); } var validateParams = selector.Parameters.Where(p => typeof(IEnumerable <Data.Entity.Entity>).IsAssignableFrom(p.Type)); //more TODO this.tableAlias.ValidateParameter(validateParams.Select(p => Expression.Parameter(p.Type.GetGenericArguments().FirstOrDefault(), p.Name) )); }
public void Intercept(IInvocation invocation) { var requestAttribute = invocation.MethodInvocationTarget.GetSingleAttributeOrNull <RequestMappingAttribute>(); if (requestAttribute == null || requestAttribute.Path.IsNullOrEmpty()) { throw new BlocksException(StringLocal.Format("Request Attribute is null or empty!")); } var url = _httpContextModel.RequestUrl; var prePath = $"{url.Scheme}://{url.Host}:{url.Port}"; var path = prePath + "/api/services" + requestAttribute.Path; var dataResult = HttpWebClient.GetResponse <DataResult>(path, _httpContextModel.CookieCollection, _httpContextModel.webHeaderCollection, invocation.Arguments.FirstOrDefault()); invocation.ReturnValue = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(dataResult.content), invocation.Method.ReturnType); ; // var a = invocation.Method.CustomAttributes.FirstOrDefault(t => t.) }
// protected override void Load(ContainerBuilder builder) { // builder.RegisterType<DefaultCacheManager>() // .As<ICacheManager>() // .InstancePerDependency(); // } public override void Initialize() { IocManager.Register <ICacheContextAccessor, DefaultCacheContextAccessor>(); IocManager.Register <IParallelCacheContext, DefaultParallelCacheContext>(); //IocManager.Register<ICacheManager,DefaultCacheManager>(DependencyLifeStyle.Transient); IocManager.Register <ICacheManager, DefaultCacheManager>((kernel, componentModel, creationContext) => { var resolutionContext = creationContext.SelectScopeRoot((t) => t.Length >= 2 ? t[t.Length - 2] : null); var handler = resolutionContext != null ? resolutionContext.Handler : null; if (handler == null) { throw new BlocksException(StringLocal.Format("Can't find suitable handler in resolutionContext.")); } return(new DefaultCacheManager(handler.ComponentModel.Implementation.UnderlyingSystemType, kernel.Resolve <ICacheHolder>())); }, DependencyLifeStyle.Transient); }
public override void PostInitialize() { var currentAssmeblyName = currentAssmebly.GetName().Name; var extensionName = extensionDescriptor.Name; var databaseType = IocManager.Resolve <ISettingManager>().GetSettingValueForApplication(typeof(DatabaseType).Name); if (databaseType == null) { throw new BlocksException(StringLocal.Format($"{typeof(DatabaseType).Name} global configuartion can't found.")); } if (!Enum.GetNames(typeof(DatabaseType)).Contains(databaseType)) { throw new BlocksException(StringLocal.Format($"{databaseType} isn't belong to global configuartion {typeof(DatabaseType).Name}.")); } if (moduleConfiguration != null && moduleConfiguration is IWebFrameworkConfiguration) { var webModuleConfiguration = moduleConfiguration as IWebFrameworkConfiguration; if (!string.IsNullOrEmpty(webModuleConfiguration.RespositoryModule)) { var RepModule = System.AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(t => string.Equals(t.GetName().Name, webModuleConfiguration.RespositoryModule, StringComparison.CurrentCultureIgnoreCase)); var listAssemblies = IocManager.Resolve <AbpPlugInManager>() .PlugInSources .GetAllAssemblies() .FirstOrDefault(t => t.GetName().Name == $"{RepModule.GetName().Name}.{databaseType}Module"); if (listAssemblies != null) { IocManager.RegisterAssemblyByConvention(listAssemblies); } IocManager.RegisterAssemblyByConvention(RepModule); } } }
public void GenernateLicenseWithRegister() { var registerFilePath = Path.Combine(AppContext.BaseDirectory, @"Register"); if (!File.Exists(registerFilePath)) { throw new LicenseException(StringLocal.Format("Register file not found.")); } ProductInfo productInfo; try { var fileInfo = File.ReadAllText(registerFilePath); productInfo = JsonHelper.DeserializeObject <ProductInfo>(CryptTools.Decrypt(fileInfo, LicenseManager.SecretRegister)); } catch (Exception) { throw new LicenseException(StringLocal.Format("License file not found or no license.")); } CryptTools.Encrypt(JsonHelper.SerializeObject(productInfo), LicenseManager.SecretRegister); var licenseFilePath = Path.Combine(AppContext.BaseDirectory, @"License"); File.WriteAllText(licenseFilePath, CryptTools.Encrypt(JsonHelper.SerializeObject(productInfo), LicenseManager.Secret)); }
public static string MapPath(this IFileProvider fileProvider, string subpath) { if (!(fileProvider is PhysicalFileProvider)) { throw new VirtualPathException(StringLocal.Format("fileProvider must be PhysicalFileProvider")); } if (string.IsNullOrEmpty(subpath) || PathUtils.HasInvalidPathChars(subpath)) { throw new VirtualPathException(StringLocal.Format("Path \"{0}\" is not available", subpath)); } subpath = subpath.TrimStart(_pathSeparators); if (Path.IsPathRooted(subpath)) { throw new VirtualPathException(StringLocal.Format("Path \"{0}\" is already root path", subpath)); } string fullPath = GetFullPath(fileProvider, subpath); if (fullPath == null) { throw new VirtualPathException(StringLocal.Format("Path \"{0}\" is not available", subpath)); } return(fullPath); }
public PermissionException(StringLocal message) : base(message) { }
public FileSystemsException(StringLocal message) : base(message) { }
public BlocksCoreException(StringLocal message, Exception innerException) : base(message, innerException) { }
public BlocksCoreException(StringLocal message) : base(message) { }
/// <summary> /// This is the first event called on application startup. /// Codes can be placed here to run before dependency injection registrations. /// </summary> /// This method is used to register dependencies for this module. /// </summary> public override void Initialize() { //Configuration.Localization.Sources.Add( // new DictionaryBasedLocalizationSource( // extensionDescriptor.Name, // new XmlEmbeddedFileLocalizationDictionaryProvider( // currentAssmebly, "Localization.Source" // ) // ) //); // var currentAssmeblyName = currentAssmebly.GetName().Name; if (currentAssmebly == null) { throw new BlocksException(StringLocal.Format("currentAssmebly is null.")); } var extensionName = extensionDescriptor.Name; IocManager.RegisterAssemblyByConvention(currentAssmebly); var serviceTypes = IocManager.IocContainer.Kernel.GetHandlers().SelectMany(t => t.Services); IocManager.Resolve <MvcControllerBuilderFactory>().ForAll <BlocksWebMvcController>(extensionName, serviceTypes.Where(t => t.Assembly == currentAssmebly)).Build(); if (moduleConfiguration != null && moduleConfiguration is IWebFrameworkConfiguration) { var webModuleConfiguration = moduleConfiguration as IWebFrameworkConfiguration; if (!string.IsNullOrEmpty(webModuleConfiguration.AppModule)) { var AppModule = System.AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(t => string.Equals(t.GetName().Name, webModuleConfiguration.AppModule, StringComparison.CurrentCultureIgnoreCase)); if (AppModule == null) { throw new BlocksException(StringLocal.Format("AppModule {0} is null.", webModuleConfiguration.AppModule)); } IocManager.RegisterAssemblyByConvention(AppModule); Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder .ForAll <IAppService>(AppModule, extensionName) .Build(); IocManager.Resolve <RPCApiManager>().Register( AppModule.GetTypes().Where(t => t.BaseType == typeof(IRPCProxy)).ToArray() ); IocManager.Resolve <RPCApiManager>().Register( AppModule.GetTypes().Where(t => !t.IsAbstract && t.IsClass && typeof(IRPCClientProxy).IsAssignableFrom(t)).ToArray() ); featureDescriptor.SubAssembly.AddIfNotContains(AppModule.GetName().Name); } if (!string.IsNullOrEmpty(webModuleConfiguration.DomainModule)) { var DomainModule = System.AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(t => string.Equals(t.GetName().Name, webModuleConfiguration.DomainModule, StringComparison.CurrentCultureIgnoreCase)); if (DomainModule == null) { throw new BlocksException(StringLocal.Format("DomainModule {0} is null.", webModuleConfiguration.DomainModule)); } IocManager.RegisterAssemblyByConvention(DomainModule); IocManager.Resolve <RPCApiManager>().Register( DomainModule.GetTypes().Where(t => t.BaseType == typeof(IRPCProxy)).ToArray() ); IocManager.Resolve <RPCApiManager>().Register( DomainModule.GetTypes().Where(t => !t.IsAbstract && t.IsClass && typeof(IRPCClientProxy).IsAssignableFrom(t)).ToArray() ); featureDescriptor.SubAssembly.AddIfNotContains(DomainModule.GetName().Name); } if (!string.IsNullOrEmpty(webModuleConfiguration.RespositoryModule)) { //TODO need to support mult sqldb var databaseType = ConfigurationManager.AppSettings["DbType"]; if (databaseType == null) { throw new BlocksException( StringLocal.Format($"{typeof(DatabaseType).Name} global configuartion can't found.")); } if (!Enum.GetNames(typeof(DatabaseType)).Contains(databaseType)) { throw new BlocksException( StringLocal.Format( $"{databaseType} isn't belong to global configuartion {typeof(DatabaseType).Name}.")); } var RepModule = System.AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(t => string.Equals(t.GetName().Name, webModuleConfiguration.RespositoryModule, StringComparison.CurrentCultureIgnoreCase)); if (RepModule == null) { throw new BlocksException(StringLocal.Format("RespositoryModule {0} is null.", webModuleConfiguration.RespositoryModule)); } var listAssemblies = IocManager.Resolve <AbpPlugInManager>() .PlugInSources .GetAllAssemblies() .FirstOrDefault(t => t.GetName().Name == $"{RepModule.GetName().Name}.{databaseType}Module"); IocManager.RegisterAssemblyByConvention(RepModule); featureDescriptor.SubAssembly.AddIfNotContains(RepModule.GetName().Name); if (listAssemblies != null) { IocManager.RegisterAssemblyByConvention(listAssemblies); featureDescriptor.SubAssembly.AddIfNotContains(listAssemblies.GetName().Name); } var nestTypes = RepModule.GetTypes().Where(t => typeof(IRepository <>).IsAssignableFrom(t)) .SelectMany(t => t.GetNestedTypes()).ToList(); // featureDescriptor.Types.AddRange(nestTypes); } } RouteHandle(extensionDescriptor.Name); InitializeEvent(); }
public LicenseException(StringLocal message) : base(message) { }
public ExtensionNotFoundException(StringLocal message) : base(message) { }
public VirtualPathException(StringLocal message) : base(message) { }