예제 #1
0
        // ------------------------------------------
        // STATIC
        // ------------------------------------------

        #region Static

        // Serialization ----------------------------

        /// <summary>
        /// Saves the xml string of this instance.
        /// </summary>
        /// <param name="object1">The object1 to save.</param>
        /// <param name="log">The saving log to consider.</param>
        /// <returns>The Xml string of this instance.</returns>
        public static string ToXml(this Object object1, IBdoLog log = null)
        {
            if (object1 == null)
            {
                return(string.Empty);
            }

            string       st           = string.Empty;
            StringWriter streamWriter = null;

            try
            {
                // if the object is a data item then we update the storage info
                if (object1 is DataItem dataItem)
                {
                    dataItem?.UpdateStorageInfo(log);
                }

                XmlSerializer xmlSerializer = new XmlSerializer(object1.GetType());
                streamWriter = new StringWriter();
                xmlSerializer.Serialize(streamWriter, object1);
                st = streamWriter.ToString();
            }
            catch (Exception ex)
            {
                log?.AddException(ex);
            }
            finally
            {
                streamWriter?.Close();
            }

            return(st);
        }
예제 #2
0
        /// <summary>
        /// Gets the assembly of this instance from embed resource.
        /// </summary>
        /// <param name="appDomain">Application domain to consider.</param>
        /// <param name="assemblyName">The assembly name to use.</param>
        /// <param name="log">The loading log to consider.</param>
        /// <returns>The assembly of this instance.</returns>
        public static Assembly LoadAssembly(AppDomain appDomain, string assemblyName, IBdoLog log = null)
        {
            Assembly assembly = null;

            if ((appDomain != null) && (!string.IsNullOrEmpty(assemblyName)))
            {
                assembly = Array.Find(appDomain.GetAssemblies(), p => p.GetName().Name.KeyEquals(assemblyName));
                if (assembly == null)
                {
                    try
                    {
                        assembly = Assembly.Load(assemblyName);
                    }
                    catch (FileNotFoundException)
                    {
                        log?.AddError("Could not find the assembly '" + assemblyName + "'");
                    }
                    catch (Exception ex)
                    {
                        log?.AddException("Error while attempting to load assembly '" + assemblyName + "'", description: ex.ToString());
                    }
                }
            }

            return(assembly);
        }
예제 #3
0
        // Deserialiaze ----------------------------

        /// <summary>
        /// Loads a data item from the specified file path.
        /// </summary>
        /// <param name="filePath">The path of the Xml file to load.</param>
        /// <param name="scope">The scope to consider.</param>
        /// <param name="scriptVariableSet">The set of script variables to consider.</param>
        /// <param name="log">The output log of the method.</param>
        /// <param name="xmlSchemaSet">The XML schema set to consider for checking.</param>
        /// <param name="mustFileExist">Indicates whether the file must exist.</param>
        /// <param name="isRuntimeUpdated">Indicates whether it is updated in runtime.</param>
        /// <returns>The loaded log.</returns>
        /// <remarks>If the XML schema set is null then the schema is not checked.</remarks>
        public static T Load <T>(
            String filePath,
            IBdoScope scope = null,
            IScriptVariableSet scriptVariableSet = null,
            IBdoLog log = null,
            XmlSchemaSet xmlSchemaSet = null,
            bool mustFileExist        = true,
            bool isRuntimeUpdated     = true) where T : class, IDataItem
        {
            T dataItem = default;

            StreamReader streamReader = null;

            if (!File.Exists(filePath))
            {
                if (mustFileExist)
                {
                    log?.AddError("File not found ('" + filePath + "'). Could not load '" + typeof(T).Name + "' object");
                }
            }
            else
            {
                try
                {
                    IBdoLog checkLog = new BdoLog();

                    if (xmlSchemaSet != null)
                    {
                        XDocument xDocument = XDocument.Load(filePath);
                        xDocument.Validate(xmlSchemaSet, (o, e) => checkLog.AddError("File not valid ('" + filePath + "'). Could not load '" + typeof(T).Name + "' object"));
                        log?.AddEvents(checkLog);
                    }

                    if (!checkLog.HasErrorsOrExceptions())
                    {
                        // then we load
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                        streamReader = new StreamReader(filePath);
                        dataItem     = xmlSerializer.Deserialize(XmlReader.Create(streamReader)) as T;

                        if (isRuntimeUpdated)
                        {
                            dataItem?.UpdateRuntimeInfo(scope, scriptVariableSet, log);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log?.AddException(ex);
                }
                finally
                {
                    streamReader?.Close();
                }
            }

            return(dataItem);
        }
예제 #4
0
        /// <summary>
        /// Saves this instance to the specified file path.
        /// </summary>
        /// <param name="object1">The object1 to save.</param>
        /// <param name="filePath">Path of the file to save.</param>
        /// <param name="log">The log to consider.</param>
        /// <returns>True if the saving operation has been done. False otherwise.</returns>
        public static bool SaveXml(this object object1, string filePath, IBdoLog log = null)
        {
            if (object1 == null)
            {
                return(false);
            }

            bool         isWasSaved   = false;
            StreamWriter streamWriter = null;

            try
            {
                if (!string.IsNullOrEmpty(filePath))
                {
                    // we create the folder if it does not exist
                    if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    }

                    // if the object is a data item then we update the storage info
                    if (object1 is DataItem dataItem)
                    {
                        dataItem?.UpdateStorageInfo(log);
                    }

                    if (object1 is IBdoExtensionItem appExtensionItem)
                    {
                        object1 = appExtensionItem.Configuration;
                    }

                    // we save the xml file
                    XmlSerializer xmlSerializer = new XmlSerializer(object1.GetType());
                    streamWriter = new StreamWriter(filePath, false, Encoding.UTF8);
                    xmlSerializer.Serialize(streamWriter, object1);

                    isWasSaved = true;
                }
            }
            catch (Exception exception)
            {
                log?.AddException(exception);

                isWasSaved = exception == null;
            }
            finally
            {
                streamWriter?.Close();
            }

            return(isWasSaved);
        }
        /// <summary>
        /// Extract extension definition from the specified assembly.
        /// </summary>
        /// <param name="assembly">The assembly to consider.</param>
        /// <param name="resourceFullName">The full name of the resouce to consider.</param>
        /// <param name="log">The log to consider.</param>
        /// <returns>The created library.</returns>
        private IBdoExtensionDefinition ExtractExtensionDefinition(
            Assembly assembly,
            string resourceFullName = null,
            IBdoLog log             = null)
        {
            IBdoExtensionDefinition definition = null;

            if (assembly != null)
            {
                if (resourceFullName == null)
                {
                    resourceFullName = Array.Find(
                        assembly.GetManifestResourceNames(), p => p.EndsWith(__DefaultResourceFileName, StringComparison.OrdinalIgnoreCase));
                }

                Stream stream = null;
                if (resourceFullName == null)
                {
                    log?.AddError("Could not find any library definition in assembly (default named '" + __DefaultResourceFileName.ToLower() + "')");
                }
                else
                {
                    try
                    {
                        stream = assembly.GetManifestResourceStream(resourceFullName);
                        if (stream == null)
                        {
                            log?.AddError("Could not find the library definition named '" + resourceFullName + "' in assembly");
                        }
                        else
                        {
                            IBdoExtensionDefinitionDto definitionDto = null;
                            XmlSerializer serializer = new XmlSerializer(typeof(BdoExtensionDefinitionDto));
                            definitionDto = (BdoExtensionDefinitionDto)serializer.Deserialize(stream);
                            definitionDto?.Initialize();

                            definition = new BdoExtensionDefinition(definitionDto);
                        }
                    }
                    catch (Exception ex)
                    {
                        log?.AddException(ex);
                    }
                    finally
                    {
                        stream?.Close();
                    }
                }
            }

            return(definition);
        }
예제 #6
0
        /// <summary>
        /// Loads the data item from the specified file path.
        /// </summary>
        /// <typeparam name="T">The data item class to consider.</typeparam>
        /// <param name="xmlString">The Xml string to load.</param>
        /// <param name="scope">The scope to consider.</param>
        /// <param name="scriptVariableSet">The set of script variables to consider.</param>
        /// <param name="log">The output log of the load method.</param>
        /// <param name="xmlSchemaSet">The XML schema set to consider for checking.</param>
        /// <returns>The loaded log.</returns>
        /// <remarks>If the XML schema set is null then the schema is not checked.</remarks>
        public static T LoadFromString <T>(
            String xmlString,
            IBdoScope scope = null,
            IScriptVariableSet scriptVariableSet = null,
            IBdoLog log = null,
            XmlSchemaSet xmlSchemaSet = null) where T : DataItem
        {
            T dataItem = null;

            if (xmlString != null)
            {
                StreamReader streamReader = null;
                try
                {
                    IBdoLog checkLog = new BdoLog();

                    if (xmlSchemaSet != null)
                    {
                        XDocument xDocument = XDocument.Parse(xmlString);
                        xDocument.Validate(xmlSchemaSet, (o, e) =>
                        {
                            log?.AddError(
                                title: "Xml string not valid",
                                description: e.Message);
                        });
                        log?.AddEvents(checkLog);
                    }

                    if (!checkLog.HasErrorsOrExceptions())
                    {
                        // then we load
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                        StringReader  stringReader  = new StringReader(xmlString);
                        dataItem = xmlSerializer.Deserialize(XmlReader.Create(stringReader)) as T;

                        dataItem?.UpdateRuntimeInfo(scope, scriptVariableSet, log);
                    }
                }
                catch (Exception ex)
                {
                    log?.AddException(ex);
                }
                finally
                {
                    streamReader?.Close();
                }
            }

            return(dataItem);
        }
예제 #7
0
        public void CreateEventsTest()
        {
            _log = new BdoLog();

            for (int i = 0; i < _testData.itemNumber; i++)
            {
                _log.AddError("Error" + i);
                _log.AddException("Exception" + i);
                _log.AddMessage("Message" + i);
                _log.AddWarning("Warning" + i);
                _log.AddSubLog(new BdoLog());
            }

            Test(_log);
        }
        /// <summary>
        /// Loads the specified BindOpen extension dictionary.
        /// </summary>
        /// <param name="assembly">The assembly to consider.</param>
        /// <param name="log">The log to consider.</param>
        /// <returns>The created library.</returns>
        private ITBdoExtensionDictionaryDto <T> ExtractDictionaryFromAssembly <T>(
            Assembly assembly,
            IBdoLog log = null) where T : BdoExtensionItemDefinitionDto
        {
            TBdoExtensionDictionaryDto <T> dictionary = default;

            if (assembly != null)
            {
                string resourceFileName = GetDictionaryResourceName <T>();

                string resourceFullName = Array.Find(
                    assembly.GetManifestResourceNames(), p => p.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase));

                Stream stream = null;
                if (resourceFullName == null)
                {
                    log?.AddWarning("No dictionary named '" + resourceFileName + "' found in assembly");
                }
                else
                {
                    try
                    {
                        stream = assembly.GetManifestResourceStream(resourceFullName);
                        if (stream == null)
                        {
                            log?.AddError("Could not open the item dictionary named '" + resourceFullName + "' in assembly");
                        }
                        else
                        {
                            Type          type       = GetDictionaryType <T>();
                            XmlSerializer serializer = new XmlSerializer(type);
                            dictionary = (TBdoExtensionDictionaryDto <T>)serializer.Deserialize(stream);
                        }
                    }
                    catch (Exception ex)
                    {
                        log?.AddException(ex);
                    }
                    finally
                    {
                        stream?.Close();
                    }
                }
            }

            return(dictionary);
        }
예제 #9
0
        // -----------------------------------------------
        // BdoRepoConnection METHODS
        // -----------------------------------------------

        #region BdoRepoConnection_Methods

        // Pull ---------------------------------------

        /// <summary>
        /// Pulls a remote file to a local URI.
        /// </summary>
        /// <param name="remoteFileUri">The URI of the remote file to consider.</param>
        /// <param name="localUri">The local URI to consider.</param>
        /// <param name="log">The log to consider.</param>
        /// <param name="canOverwrite">Indicates whether the local file can be overwritten.</param>
        public override void Pull(
            string remoteFileUri,
            string localUri,
            bool canOverwrite,
            IBdoLog log = null)
        {
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(localUri)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(localUri));
                }

                File.Copy(remoteFileUri, localUri, canOverwrite);
            }
            catch (IOException exception)
            {
                log?.AddException(exception);
            }
        }
예제 #10
0
        /// <summary>
        /// Creates the specified file directory if it does not exist.
        /// </summary>
        /// <param name="folderPath">The path of the file directory to consider.</param>
        /// <param name="log">The log to append.</param>
        /// <returns>Returns True whether the directory exists henceforth. False otherwise.</returns>
        public static bool CreateDirectory(string folderPath, IBdoLog log = null)
        {
            var isExisting = false;

            try
            {
                // we create the folder if it does not exist
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                isExisting = true;
            }
            catch (IOException ex)
            {
                log?.AddException(ex);
            }

            return(isExisting);
        }
예제 #11
0
 /// <summary>
 /// Deletes a local folder.
 /// </summary>
 /// <param name="localfolderUri">The local Uri to consider.</param>
 /// <param name="log">The log to consider.</param>
 public static void DeleteFolder(
     string localfolderUri,
     IBdoLog log = null)
 {
     try
     {
         if (Directory.Exists(localfolderUri))
         {
             Directory.Delete(localfolderUri, true);
             log?.AddMessage("Folder '" + localfolderUri + "' deleted");
         }
         else
         {
             log?.AddError("Could not delete folder '" + localfolderUri + "'");
         }
     }
     catch (IOException exception)
     {
         log?.AddException("Could not delete folder '" + localfolderUri + "'", description: exception.ToString());
     }
 }
예제 #12
0
        // -----------------------------------------------
        // OTHER METHODS
        // -----------------------------------------------

        #region Other_Methods


        // Delete ---------------------------------------------------

        /// <summary>
        /// Deletes a local file.
        /// </summary>
        /// <param name="localFileUri">The local Uri to consider.</param>
        /// <param name="log">The log to consider.</param>
        public static void DeleteFile(
            string localFileUri,
            IBdoLog log = null)
        {
            try
            {
                if (File.Exists(localFileUri))
                {
                    Directory.Delete(localFileUri, true);
                    log?.AddMessage("File '" + localFileUri + "' deleted");
                }
                else
                {
                    log?.AddError("Could not delete file '" + localFileUri + "'");
                }
            }
            catch (IOException exception)
            {
                log?.AddException(exception);
            }
        }
예제 #13
0
        // ------------------------------------------
        // ASSEMBLIES
        // ------------------------------------------

        #region Assemblies

        /// <summary>
        /// Gets the assembly of this instance from file.
        /// </summary>
        /// <param name="appDomain">Application domain to consider.</param>
        /// <param name="filePath">Path of the file to use.</param>
        /// <param name="log">The loading log to consider.</param>
        /// <returns>The assembly of this instance.</returns>
        public static Assembly LoadAssemblyFromFile(AppDomain appDomain, string filePath, IBdoLog log = null)
        {
            Assembly assembly = null;

            if (((appDomain != null) & (!string.IsNullOrEmpty(filePath))) &&
                (File.Exists(filePath)))
            {
                string assemblyName = Path.GetFileNameWithoutExtension(filePath);
                foreach (global::System.Reflection.Assembly currentAssembly in appDomain.GetAssemblies())
                {
                    if (!currentAssembly.IsDynamic)
                    {
                        string assemblyCodeBasePath = currentAssembly.CodeBase.ToLower();
                        string assemblyFilePath     = filePath.ToLower().Replace(@"\", "/");

                        if (assemblyCodeBasePath.Contains(assemblyFilePath))
                        {
                            assembly = currentAssembly;
                            break;
                        }
                    }
                }

                if (assembly == null)
                {
                    try
                    {
                        assembly = Assembly.LoadFrom(filePath);
                    }
                    catch (Exception ex)
                    {
                        log?.AddException(
                            title: "Error while attempting to load assembly from file '" + filePath + "'",
                            description: ex.ToString());
                    }
                }
            }

            return(assembly);
        }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public override IBdoConnection CreateConnection(IBdoLog log = null)
        {
            IBdoDbConnection connection = null;

            if (!Check <BdoDbConnector_PostgreSql>().AddEventsTo(log, p => p.HasErrorsOrExceptions()).HasErrorsOrExceptions())
            {
                try
                {
                    var dbConnection = new NpgsqlConnection(ConnectionString);
                    if (dbConnection != null)
                    {
                        connection = new BdoDbConnection(this, dbConnection);
                    }
                }
                catch (Exception ex)
                {
                    log.AddException("An exception occured while trying to create connection",
                                     description: ex.ToString());
                }
            }

            return(connection);
        }
예제 #15
0
        // ------------------------------------------
        // LOAD MANAGEMENT
        // ------------------------------------------

        #region Load Management

        /// <summary>
        /// Initializes information.
        /// </summary>
        /// <param name="log">The log to populate.</param>
        /// <returns>Returns the log of the task.</returns>
        protected override void Initialize(IBdoLog log)
        {
            log ??= new BdoLog();

            // we bind the trigger actions

            var options = Options as TBdoHostOptions <S>;

            Action_OnExecutionSucess  = options?.Action_OnExecutionSucess;
            Action_OnExecutionFailure = options?.Action_OnExecutionFailure;
            Action_OnStartSuccess     = options?.Action_OnStartSuccess;
            Action_OnStartFailure     = options?.Action_OnStartFailure;

            // we clone the current options host settings as the primary ones

            var primaryHostSettings = Options.HostSettings?.Clone <BdoHostSettings>();

            // we determine the root folder path

            var rootFolderPathDefinition = Options?.RootFolderPathDefinitions?.FirstOrDefault(p => p.Predicate(Options) == true);

            if (rootFolderPathDefinition != null)
            {
                Options?.SetRootFolder(rootFolderPathDefinition?.RootFolderPath);
            }

            // we update options (specially paths)

            Options.Update();

            // we initialize the logger

            Log.SetLogger(Options.StartUpLogger);

            // we launch the standard initialization of service

            base.Initialize(log);

            IBdoLog subLog;

            // we load the core extensions

            subLog = log.AddSubLog(title: "Loading core extensions...", eventKind: EventKinds.Message);
            _scope.LoadExtensions(ExtensionReferenceFactory.CreateRuntime()).AddEventsTo(subLog);
            if (!subLog.HasErrorsOrExceptions())
            {
                subLog.AddMessage("Core extensions loaded");
            }

            // if no errors was found

            if (!log.HasErrorsOrExceptions())
            {
                try
                {
                    // we load the host configuration

                    string hostConfigFilePath = GetKnownPath(BdoHostPathKind.HostConfigFile);
                    Options.SetHostSettings(primaryHostSettings ?? new BdoHostSettings());

                    if (!File.Exists(hostConfigFilePath))
                    {
                        var message = "Host configuration file ('" + BdoDefaultHostPaths.__DefaultHostConfigFileName + "') not found";
                        if (Options.IsHostConfigFileRequired == true)
                        {
                            subLog.AddError(message);
                        }
                        else if (Options.IsHostConfigFileRequired == false)
                        {
                            subLog.AddWarning(message);
                        }
                    }
                    else
                    {
                        subLog = log.AddSubLog(title: "Loading host configuration...", eventKind: EventKinds.Message);
                        Options.HostSettings.UpdateFromFile(
                            hostConfigFilePath,
                            new SpecificationLevels[] { SpecificationLevels.Definition, SpecificationLevels.Configuration },
                            Options?.AppSettingsSpecificationSet,
                            _scope, null).AddEventsTo(log);
                        if (!subLog.HasErrorsOrExceptions())
                        {
                            subLog.AddMessage("Host configuration loaded");
                        }
                    }

                    Options.Update().AddEventsTo(subLog);

                    if (string.IsNullOrEmpty(Options?.HostSettings.ApplicationInstanceName))
                    {
                        Options.HostSettings.ApplicationInstanceName = BdoAppConfiguration.__ApplicationInstanceName;
                    }

                    // we load extensions

                    subLog = log.AddSubLog(title: "Loading extensions...", eventKind: EventKinds.Message);

                    if (Options?.ExtensionReferences.Count == 0)
                    {
                        subLog.AddMessage("No extensions found");
                    }
                    else
                    {
                        Options.ExtensionLoadOptions?.WithLibraryFolderPath(GetKnownPath(BdoHostPathKind.LibraryFolder));
                        foreach (var reference in Options?.ExtensionReferences)
                        {
                            subLog.AddEvents(_scope.LoadExtensions(p => p.Update(Options?.ExtensionLoadOptions), reference), l => l.HasErrorsOrExceptionsOrWarnings());
                        }

                        if (!subLog.HasErrorsOrExceptions())
                        {
                            subLog.AddMessage("Extensions loaded");
                        }
                    }

                    if (!log.HasErrorsOrExceptions())
                    {
                        // we load the application configuration

                        Options.SetAppSettings(new S());

                        string appConfigFilePath = GetKnownPath(BdoHostPathKind.ConfigurationFolder) + BdoDefaultHostPaths.__DefaultAppConfigFileName;

                        subLog = log.AddSubLog(title: "Loading application configuration...", eventKind: EventKinds.Message);
                        if (!File.Exists(appConfigFilePath))
                        {
                            var message = "Application configuration file ('" + BdoDefaultHostPaths.__DefaultAppConfigFileName + "') not found";
                            if (Options.HostSettings.IsAppConfigFileRequired == true)
                            {
                                subLog.AddError(message);
                            }
                            else if (Options.HostSettings.IsAppConfigFileRequired == false)
                            {
                                subLog.AddWarning(message);
                            }
                        }
                        else
                        {
                            Options.Settings.UpdateFromFile(
                                appConfigFilePath,
                                new SpecificationLevels[] { SpecificationLevels.Definition, SpecificationLevels.Configuration },
                                Options?.AppSettingsSpecificationSet,
                                _scope, null).AddEventsTo(subLog);
                        }
                        if (!subLog.HasErrorsOrExceptions())
                        {
                            subLog.AddMessage("Application configuration loaded");
                        }
                        else
                        {
                            subLog.AddMessage(title: "No configuration loaded");
                        }

                        // we set the logger

                        Log.SetLogger(Options.LoggerInit?.Invoke(this));

                        // we load the data store

                        _scope.DataStore = Options?.DataStore;
                        subLog           = log.AddSubLog(title: "Loading data store...", eventKind: EventKinds.Message);
                        if (_scope.DataStore == null)
                        {
                            subLog.AddMessage(title: "No data store registered");
                        }
                        else
                        {
                            _scope.DataStore.LoadLazy(this, subLog);

                            if (!subLog.HasErrorsOrExceptions())
                            {
                                subLog.AddMessage("Data store loaded (" + _scope.DataStore.Depots.Count + " depots added)");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.AddException(ex);
                }
                finally
                {
                }
            }

            _isLoaded = !log.HasErrorsOrExceptions();
        }