Exemple #1
0
        /// <summary>
        /// Initializes an instance of the BuiltInBlobProviderSelector
        /// </summary>
        public BuiltInBlobProviderSelector()
        {
            // check if there is a configuration for an external blob provider
            if (string.IsNullOrEmpty(BlobStorage.BlobProviderClassName) || ExternalBlobProvider != null)
            {
                return;
            }

            try
            {
                ExternalBlobProvider = (IBlobProvider)TypeResolver.CreateInstance(BlobStorage.BlobProviderClassName);
                SnLog.WriteInformation("External BlobProvider created by configuration. Type: " + BlobStorage.BlobProviderClassName,
                                       EventId.RepositoryLifecycle);
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);
            }

            // We throw an exception in a static constructor (which will prevent this type to work)
            // because if something is wrong with the blob provider configuration, it will affect
            // the whole system and it should be resolved immediately.
            if (ExternalBlobProvider == null)
            {
                throw new ConfigurationErrorsException("Unknown blob provider name in configuration: " + BlobStorage.BlobProviderClassName);
            }
        }
Exemple #2
0
        private object DeserializeObjectFromCurrent()
        {
            var identifier = CurrentNode["Identifier"].Value;

            if (UseReferences && ReferenceObjects.ContainsKey(identifier))
            {
                return(ReferenceObjects[identifier]);
            }
            if (CurrentNode["CLRType"] == null)
            {
                return(null);
            }
            var clrType        = CurrentNode["CLRType"].Value;
            var instance       = TypeResolver.CreateInstance(clrType, identifier);
            var ufSerializable = instance as IUFSerializable;

            if (ufSerializable != null)
            {
                if (UseReferences)
                {
                    ReferenceObjects.Add(identifier, ufSerializable);
                }
                ufSerializable.Read(this);
            }
            return(instance);
        }
Exemple #3
0
        public static void CheckComponentVersions()
        {
            //TODO: have a pinned list of components in the Providers class
            // so that the instances can be replaced by tests.
            foreach (var componentType in TypeResolver.GetTypesByInterface(typeof(ISnComponent)).Where(vct => !vct.IsAbstract))
            {
                var component = TypeResolver.CreateInstance(componentType.FullName) as ISnComponent;
                if (component == null)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(component.ComponentId))
                {
                    SnLog.WriteWarning($"Component class {component.GetType().FullName} is invalid, it does not provide a ComponentId.");
                    continue;
                }

                var componentVersion = Instance.Components.FirstOrDefault(c => c.ComponentId == component.ComponentId)?.Version;

                if (component.IsComponentAllowed(componentVersion))
                {
                    SnTrace.System.Write($"Component {component.ComponentId} is allowed to run (version: {componentVersion})");
                    continue;
                }

                throw new ApplicationException($"Component and assembly version mismatch. Component {component.ComponentId} (version: {componentVersion}) is not allowed to run. Please check assembly versions and available ugrades before starting the repository.");
            }
        }
        static ContentNamingProvider()
        {
            var className = Providers.ContentNamingProviderClassName;

            ContentNamingProvider instance = null;

            if (string.IsNullOrEmpty(className))
            {
                instance = new CharReplacementContentNamingProvider();
            }
            else
            {
                try
                {
                    instance = (ContentNamingProvider)TypeResolver.CreateInstance(className);
                }
                catch (Exception)
                {
                    SnLog.WriteWarning("Error loading ContentNamingProvider type: " + className, EventId.RepositoryLifecycle);
                }
            }

            if (instance == null)
            {
                instance = new CharReplacementContentNamingProvider();
            }

            SnLog.WriteInformation("ContentNamingProvider created: " + instance);

            __instance = instance;
        }
Exemple #5
0
        private static void InitializeOAuthProviders()
        {
            var providerTypeNames = new List <string>();

            foreach (var providerType in TypeResolver.GetTypesByInterface(typeof(IOAuthProvider)).Where(t => !t.IsAbstract))
            {
                if (!(TypeResolver.CreateInstance(providerType.FullName) is IOAuthProvider provider))
                {
                    continue;
                }

                if (string.IsNullOrEmpty(provider.ProviderName))
                {
                    SnLog.WriteWarning($"OAuth provider type {providerType.FullName} does not expose a valid ProviderName value, therefore cannot be initialized.");
                    continue;
                }
                if (string.IsNullOrEmpty(provider.IdentifierFieldName))
                {
                    SnLog.WriteWarning($"OAuth provider type {providerType.FullName} does not expose a valid IdentifierFieldName value, therefore cannot be initialized.");
                    continue;
                }

                Providers.Instance.SetProvider(OAuthProviderTools.GetProviderRegistrationName(provider.ProviderName), provider);
                providerTypeNames.Add($"{providerType.FullName} ({provider.ProviderName})");
            }

            if (providerTypeNames.Any())
            {
                SnLog.WriteInformation("OAuth providers registered: " + Environment.NewLine +
                                       string.Join(Environment.NewLine, providerTypeNames));
            }
        }
Exemple #6
0
        internal static ActionBase CreateAction(Type actionType, Application application, Content context, string backUri, object parameters)
        {
            var act = TypeResolver.CreateInstance(actionType.FullName) as ActionBase;

            act?.Initialize(context, backUri, application, parameters);

            return(act == null || !act.Visible ? null : act);
        }
Exemple #7
0
        public static void CheckComponentVersions()
        {
            var components = TypeResolver.GetTypesByInterface(typeof(ISnComponent)).Where(vct => !vct.IsAbstract)
                             .Select(t => TypeResolver.CreateInstance(t.FullName) as ISnComponent)
                             .Where(c => c != null)
                             .Select(SnComponentInfo.Create)
                             .ToArray();

            CheckComponentVersions(components);
        }
        public static TOptions Cached <TOptions>(CacheMode cacheMode)
            where TOptions : ICrudServiceOptionsAutomationSupport
        {
            var instance = TypeResolver.CreateInstance <TOptions>();

            if (instance == null)
            {
                throw new InvalidOperationException();
            }

            instance.SetCacheMode(cacheMode);

            return(instance);
        }
        public static TOptions FromContext <TOptions>(object context)
            where TOptions : ICrudServiceOptions
        {
            var instance = TypeResolver.CreateInstance <TOptions>() as ICrudServiceOptionsAutomationSupport;

            if (instance == null)
            {
                throw new InvalidOperationException();
            }

            instance.SetContext(context);

            return((TOptions)instance);
        }
Exemple #10
0
        /// <summary>
        /// This method collects all the available text extractors. First it builds a list of the built-in
        /// extractors than adds the dynamic ones from the setting (they can override the built-in ones).
        /// </summary>
        private Dictionary <string, ITextExtractor> LoadTextExtractors()
        {
            var extractors = new Dictionary <string, ITextExtractor>
            {
                { "contenttype", new XmlTextExtractor() },
                { "xml", new XmlTextExtractor() },
                { "doc", new DocTextExtractor() },
                { "xls", new XlsTextExtractor() },
                { "xlb", new XlbTextExtractor() },
                { "msg", new MsgTextExtractor() },
                { "pdf", new PdfTextExtractor() },
                { "docx", new DocxTextExtractor() },
                { "docm", new DocxTextExtractor() },
                { "xlsx", new XlsxTextExtractor() },
                { "xlsm", new XlsxTextExtractor() },
                { "pptx", new PptxTextExtractor() },
                { "txt", new PlainTextExtractor() },
                { "settings", new PlainTextExtractor() },
                { "rtf", new RtfTextExtractor() }
            };

            // load text extractor settings (they may override the defaults listed above)
            foreach (var field in Content.Fields.Values.Where(field => field.Name.StartsWith(TextExtractorsTextfieldName + ".")))
            {
                var extractorName = field.GetData() as string;
                if (string.IsNullOrEmpty(extractorName))
                {
                    continue;
                }

                extractorName = extractorName.Trim('.', ' ');

                try
                {
                    var extension = field.Name.Substring(field.Name.LastIndexOf('.')).Trim('.', ' ').ToLower();
                    extractors[extension] = (ITextExtractor)TypeResolver.CreateInstance(extractorName);
                }
                catch (Exception ex)
                {
                    SnLog.WriteWarning($"Text extractor type could not be instatiated: {extractorName} {ex}", EventId.Indexing);
                }
            }

            return(extractors);
        }
        protected override string GetQueryFilter()
        {
            var originalQueryFilter = base.GetQueryFilter();

            if (SearchForm == null)
            {
                return(originalQueryFilter);
            }

            SearchForm.UpdateContent();

            DefaultQueryBuilder qBuilder;

            if (string.IsNullOrEmpty(PluginFullPath))
            {
                qBuilder = new DefaultQueryBuilder(originalQueryFilter, SearchForm.Content, EmptyQueryTerm);
            }
            else
            {
                qBuilder = TypeResolver.CreateInstance(PluginFullPath, new object[] { originalQueryFilter, SearchForm.Content }) as DefaultQueryBuilder;
            }

            var filter = qBuilder.BuildQuery(/*kv*/);

            var sb     = new StringBuilder();
            var writer = XmlWriter.Create(sb);

            writer.WriteStartDocument();
            writer.WriteStartElement("ContentMetaData");
            writer.WriteElementString("ContentType", SearchForm.Content.ContentType.Name);
            writer.WriteElementString("ContentName", SearchForm.Content.Name);
            writer.WriteStartElement("Fields");

            SearchForm.Content.ExportFieldData(writer, new ExportContext("/Root", ""));

            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();

            _state.ExportQueryFields = sb.ToString();
            PortletState.Persist(_state);

            return(filter);
        }
Exemple #12
0
        public virtual T GetProvider <T>(string name) where T : class
        {
            // Test cached instance if there is.
            if (!_providersByName.TryGetValue(name, out var provider))
            {
                // Try to resolve by configuration
                // 1 - read classname from configuration.
                var className = GetProvider(name);

                // 2 - resolve provider instance.
                provider = className == null ? null : TypeResolver.CreateInstance(className);

                // 3 - memorize even if null.
                SetProvider(name, provider);
            }

            return(provider as T);
        }
Exemple #13
0
        /// <summary>
        /// The get service.
        /// </summary>
        /// <param name="name">
        /// The name.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <returns>
        /// The <see cref="IServiceRunner"/>.
        /// </returns>
        private static IServiceRunner GetService(string name, ILogger logger)
        {
            var targetType = Type.GetType(name);
            if (targetType == null)
            {
                return null;
            }

            var typeResolver = new TypeResolver(logger);
            if (targetType.IsClass && !targetType.IsAbstract && typeof(IServiceRunner).IsAssignableFrom(targetType))
            {
                var result = typeResolver.CreateInstance<IServiceRunner>(targetType);
                result.Logger = logger;
                return result;
            }

            return null;
        }
Exemple #14
0
        public static File CreateByBinary(IFolder parent, BinaryData binaryData)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            if (binaryData == null)
            {
                return(new File(parent as Node));
            }

            File file;
            // Resolve filetype by binary-config matching
            BinaryTypeResolver resolver = new BinaryTypeResolver();

            if (!resolver.ParseBinary(binaryData))
            {
                // Unknown file type
                file = new File(parent as Node);
            }
            else
            {
                // Specific File subtype has been found
                file = TypeResolver.CreateInstance <File>(resolver.NodeType.ClassName, parent);

                var fname = binaryData.FileName.FileNameWithoutExtension;
                if (string.IsNullOrEmpty(fname))
                {
                    fname = file.Name;
                }
                else if (fname.Contains("\\"))
                {
                    fname = System.IO.Path.GetFileNameWithoutExtension(fname);
                }

                binaryData.FileName    = new BinaryFileName(fname, resolver.FileNameExtension);
                binaryData.ContentType = resolver.ContentType;
            }

            file.Binary = binaryData;
            return(file);
        }
        public static TOptions FromPagingParameters <TEntity, TOptions>(
            Expression <Func <TEntity, object> > sortField, SortingOrder sortingOrder,
            long skip, long take)
            where TOptions : IPagableCrudServiceOptionsAutomationSupport <TEntity>
        {
            var instance = TypeResolver.CreateInstance <TOptions>();

            if (instance == null)
            {
                throw new InvalidOperationException();
            }

            if (sortField != null)
            {
                instance.SetSorting(new[] { new SortingContext <TEntity>(sortField, sortingOrder) });
            }
            instance.SetSkip(skip);
            instance.SetTake(take);

            return(instance);
        }
Exemple #16
0
        private static T CreateProviderInstance <T>(string className, string providerName)
        {
            T provider;

            try
            {
                provider = (T)TypeResolver.CreateInstance(className);
            }
            catch (TypeNotFoundException)
            {
                throw new ConfigurationException($"{providerName} implementation does not exist: {className}");
            }
            catch (InvalidCastException)
            {
                throw new ConfigurationException($"Invalid {providerName} implementation: {className}");
            }

            SnLog.WriteInformation($"{providerName} created: {className}");

            return(provider);
        }
        /// <summary>
        /// Loads and instantiates all available ISnComponent types and returns them
        /// in the same order as they were installed in the database.
        /// </summary>
        internal static SnComponentInfo[] GetAssemblyComponents()
        {
            return(TypeResolver.GetTypesByInterface(typeof(ISnComponent)).Where(vct => !vct.IsAbstract)
                   .Select(t =>
            {
                ISnComponent component = null;

                try
                {
                    component = TypeResolver.CreateInstance(t.FullName) as ISnComponent;
                }
                catch (Exception ex)
                {
                    SnLog.WriteException(ex, $"Error during instantiating the component type {t.FullName}.");
                }

                return component;
            })
                   .Where(c => c != null)
                   .OrderBy(c => c.ComponentId, new SnComponentComparer())
                   .Select(SnComponentInfo.Create)
                   .ToArray());
        }
        /* ===================================================================== Public methods */
        public void AddToControls(ControlCollection controls)
        {
            var portletStart = this.InnerText.IndexOf("<td>") + 4;
            var beginTable   = this.InnerText.Substring(0, portletStart);
            var portletEnd   = this.InnerText.LastIndexOf("</td>");
            var endTable     = this.InnerText.Substring(portletEnd);

            var portlet = TypeResolver.CreateInstance("SenseNet.Portal.Portlets.ContentCollectionPortlet") as ContextBoundPortlet;

            portlet.ID             = Guid.NewGuid().ToString();
            portlet.CustomRootPath = this.CustomRootPath;
            portlet.Renderer       = this.Renderer;
            portlet.RenderingMode  = SenseNet.Portal.UI.PortletFramework.RenderMode.Xslt;
            portlet.BindTarget     = BindTarget.CustomRoot;

            controls.Add(new LiteralControl {
                Text = beginTable
            });
            controls.Add(portlet);
            controls.Add(new LiteralControl {
                Text = endTable
            });
        }
Exemple #19
0
 public object CreateInstance(string typename)
 {
     return(TypeResolver.CreateInstance(typename));
 }
Exemple #20
0
        /// <summary>
        /// This method collects all the available text extractors. First it builds a list of the built-in
        /// extractors than adds the dynamic ones from the setting (they can override the built-in ones).
        /// </summary>
        private Dictionary <string, ITextExtractor> LoadTextExtractors()
        {
            var extractors = new Dictionary <string, ITextExtractor>
            {
                { "contenttype", new XmlTextExtractor() },
                { "xml", new XmlTextExtractor() },
                { "doc", new DocTextExtractor() },
                { "xls", new XlsTextExtractor() },
                { "xlb", new XlbTextExtractor() },
                { "msg", new MsgTextExtractor() },
                { "pdf", new PdfTextExtractor() },
                { "docx", new DocxTextExtractor() },
                { "docm", new DocxTextExtractor() },
                { "xlsx", new XlsxTextExtractor() },
                { "xlsm", new XlsxTextExtractor() },
                { "pptx", new PptxTextExtractor() },
                { "txt", new PlainTextExtractor() },
                { "settings", new PlainTextExtractor() },
                { "rtf", new RtfTextExtractor() }
            };

            var isCommunity = RepositoryVersionInfo.Instance != null &&
                              RepositoryVersionInfo.Instance.OfficialSenseNetVersion != null &&
                              RepositoryVersionInfo.Instance.OfficialSenseNetVersion.Edition == "Community";

            // add text extractors available only in the Enterprise Edition
            if (!isCommunity)
            {
                try
                {
                    // load text extractor types that are available only in the Enterprise edition
                    //extractors["pdf"] = (ITextExtractor)TypeResolver.CreateInstance(ASPOSE_PDF_TEXTEXTRACTOR_NAME);
                }
                catch (Exception ex)
                {
                    SnLog.WriteWarning("Text extractor type could not be instatiated (Aspose Pdf extractor). " + ex, EventId.Indexing);
                }
            }

            // load text extractor settings (they may override the defaults listed above)
            foreach (var field in this.Content.Fields.Values.Where(field => field.Name.StartsWith(TEXTEXTRACTORS_TEXTFIELDNAME + ".")))
            {
                var extractorName = field.GetData() as string;
                if (string.IsNullOrEmpty(extractorName))
                {
                    continue;
                }

                extractorName = extractorName.Trim('.', ' ');

                // make sure that only Enterprise customers can use the Aspose provider
                if (isCommunity && string.Compare(extractorName, ASPOSE_PDF_TEXTEXTRACTOR_NAME, StringComparison.InvariantCulture) == 0)
                {
                    continue;
                }

                try
                {
                    var extension = field.Name.Substring(field.Name.LastIndexOf('.')).Trim('.', ' ').ToLower();

                    extractors[extension] = (ITextExtractor)TypeResolver.CreateInstance(extractorName);
                }
                catch (Exception ex)
                {
                    SnLog.WriteWarning($"Text extractor type could not be instatiated: {extractorName} {ex}", EventId.Indexing);
                }
            }

            return(extractors);
        }
 /// <inheritdoc />
 public IFirewall Reload()
 {
     UnderlyingObject = TypeResolver.CreateInstance <INetFwPolicy2>();
     return(this);
 }
 public static T Default <T>() => TypeResolver.CreateInstance <T>();
Exemple #23
0
 public static object CreateInstance(string typeName, params object[] args)
 {
     return(TypeResolver.CreateInstance(typeName, args));
 }
Exemple #24
0
 public static T CreateInstance <T>(string typeName) where T : new()
 {
     return(TypeResolver.CreateInstance <T>(typeName));
 }
Exemple #25
0
        /// <summary>
        /// The load env.
        /// </summary>
        /// <param name="filePath">
        /// The file path.
        /// </param>
        /// <returns>
        /// The <see cref="MonitorEnvironment"/>.
        /// </returns>
        public MonitorEnvironment LoadEnv(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    return null;
                }

                var configs = new Dictionary<Type, ConfigInfo>();
                byte[][] rawData;
                var formatter = new TolerantBinaryFormatter(this.Logger);
                var typeResolver = new TypeResolver(this.Logger);
                using (var stream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        var productName = reader.ReadString();
                        var productVersion = reader.ReadString();
                        this.Logger.DebugFormat("Loading configuration for {0} {1}...", productName, productVersion);
                        rawData = formatter.Deserialize(stream) as byte[][];
                    }
                }

                if (rawData != null)
                {
                    foreach (var data in rawData)
                    {
                        try
                        {
                            using (var ms = new MemoryStream(data))
                            {
                                var configData = formatter.Deserialize(ms) as KeyValue<Type, ConfigInfo>;
                                if (configData != null && configData.Key != null)
                                {
                                    configs.Add(configData.Key, configData.Value);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            this.Logger.Warn("Cannot read configuration: " + ex.Message);
                        }
                    }
                }

                if (configs.Count > 0)
                {
                    IArchiveManager archiveManager = null;
                    IFareDataProvider fareDataProvider = null;
                    ISyncableDatabase syncDb = null;
                    IFareDatabase fareDatabase = null;
                    ICurrencyProvider currencyProvider = null;
                    BackgroundServiceManager backgroundServices = new BackgroundServiceManager(this.Logger);

                    foreach (var pair in configs)
                    {
                        Type type = pair.Key;
                        ConfigInfo info = pair.Value;

                        if (type == typeof(IArchiveManager))
                        {
                            if (info.ConfiguredType != null)
                            {
                                archiveManager = typeResolver.CreateInstance<IArchiveManager>(info.ConfiguredType);
                                if (archiveManager != null)
                                {
                                    archiveManager.Configuration = info.TypeConfiguration ?? archiveManager.DefaultConfig;
                                }
                            }
                        }
                        else if (type == typeof(IFareDataProvider))
                        {
                            if (info.ConfiguredType != null)
                            {
                                fareDataProvider = typeResolver.CreateInstance<IFareDataProvider>(info.ConfiguredType);
                                if (fareDataProvider != null)
                                {
                                    fareDataProvider.Configuration = info.TypeConfiguration ?? fareDataProvider.DefaultConfig;
                                }

                                if (archiveManager != null)
                                {
                                    archiveManager.FareDataProvider = fareDataProvider;
                                }
                            }
                        }
                        else if (type == typeof(IFareDatabase))
                        {
                            if (info.ConfiguredType != null)
                            {
                                fareDatabase = typeResolver.CreateInstance<IFareDatabase>(info.ConfiguredType);
                                if (fareDatabase != null)
                                {
                                    fareDatabase.Configuration = info.TypeConfiguration ?? fareDatabase.DefaultConfig;
                                }

                                syncDb = fareDatabase as ISyncableDatabase;
                            }
                        }
                        else if (type == typeof(IDatabaseSyncer<>))
                        {
                            if (syncDb != null)
                            {
                                if (info.ConfiguredType != null)
                                {
                                    var dbSyncer = typeResolver.CreateInstance<IPlugin>(info.ConfiguredType);
                                    if (dbSyncer != null)
                                    {
                                        var dataSyncer = dbSyncer as IDataSyncer;
                                        dbSyncer.Configuration = info.TypeConfiguration ?? dbSyncer.DefaultConfig;
                                        syncDb.DataSynchronizer = dataSyncer;
                                        syncDb.PackageSynchronizer = dbSyncer as IPackageSyncer<TravelRoute>;
                                    }
                                }
                            }
                        }
                        else if (typeof(IHelperService).IsAssignableFrom(type))
                        {
                            if (info.ConfiguredType != null)
                            {
                                var newService = typeResolver.CreateInstance<IHelperService>(info.ConfiguredType);
                                if (newService != null)
                                {
                                    newService.Configuration = info.TypeConfiguration ?? newService.DefaultConfig;
                                    backgroundServices.Add(newService, false);
                                    var currencyService = newService as ICurrencyProvider;
                                    if (currencyService != null)
                                    {
                                        currencyProvider = currencyService;
                                    }
                                }
                            }
                        }
                    }

                    return new MonitorEnvironment(
                        this,
                        this._pluginResolver,
                        fareDataProvider,
                        fareDatabase,
                        archiveManager,
                        currencyProvider,
                        backgroundServices,
                        this.Logger);
                }
            }
            catch (Exception ex)
            {
                this.Logger.ErrorFormat("Failed to load environment data: {0}", ex);
            }

            return null;
        }
Exemple #26
0
 public Crud() : this(TypeResolver.CreateInstance <IRawWrapper>())
 {
 }
Exemple #27
0
 public T CreateInstance <T>(string typeName, params object[] args)
 {
     return(TypeResolver.CreateInstance <T>(typeName, args));
 }
Exemple #28
0
 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
 {
     return(TypeResolver.CreateInstance(value.ToString()));
 }