Пример #1
0
        /// <summary>
        /// Creates a new <see cref="WebServer"/>.
        /// </summary>
        /// <param name="options">Web server options to use; set to <c>null</c> for defaults.</param>
        /// <param name="razorEngineCS">Razor engine instance for .cshtml templates; uses default instance if not provided.</param>
        /// <param name="razorEngineVB">Razor engine instance for .vbhtml templates; uses default instance if not provided.</param>
        public WebServer(WebServerOptions options = null, IRazorEngine razorEngineCS = null, IRazorEngine razorEngineVB = null)
        {
            m_releaseMode = !AssemblyInfo.EntryAssembly.Debuggable;

            if ((object)options == null)
            {
                options = new WebServerOptions();
            }

            m_options           = options;
            RazorEngineCS       = razorEngineCS ?? (m_releaseMode ? RazorEngine <CSharp> .Default : RazorEngine <CSharpDebug> .Default as IRazorEngine);
            RazorEngineVB       = razorEngineVB ?? (m_releaseMode ? RazorEngine <VisualBasic> .Default : RazorEngine <VisualBasicDebug> .Default as IRazorEngine);
            PagedViewModelTypes = new ConcurrentDictionary <string, Tuple <Type, Type> >(StringComparer.InvariantCultureIgnoreCase);
            m_etagCache         = new ConcurrentDictionary <string, long>(StringComparer.InvariantCultureIgnoreCase);
            m_handlerTypeCache  = new ConcurrentDictionary <string, Type>(StringComparer.InvariantCultureIgnoreCase);

            // Validate web root path
            m_options.WebRootPath = FilePath.AddPathSuffix(m_options.WebRootPath ?? RazorEngineCS.TemplatePath);

            m_fileWatcher = new SafeFileWatcher(m_options.WebRootPath)
            {
                IncludeSubdirectories = true,
                EnableRaisingEvents   = true
            };

            m_fileWatcher.Changed += m_fileWatcher_FileChange;
            m_fileWatcher.Deleted += m_fileWatcher_FileChange;
            m_fileWatcher.Renamed += m_fileWatcher_FileChange;
        }
Пример #2
0
        // Attempt to auto-load initial host configuration file (useful when running from host service folder)
        private string LookupHostConfig()
        {
            // Search through list of known source applications (faster than manual search)
            foreach (string hostApp in new[] { "openPDC", "openHistorian", "SIEGate" })
            {
                string absolutePath = FilePath.GetAbsolutePath($"{hostApp}.exe.config");

                if (File.Exists(absolutePath))
                {
                    HostApp = hostApp;
                    return(absolutePath);
                }
            }

            // Fall back on manual search
            foreach (string configFile in FilePath.GetFileList($"{FilePath.AddPathSuffix(FilePath.GetAbsolutePath(""))}*.exe.config"))
            {
                if (IsHostConfig(configFile))
                {
                    return(configFile);
                }
            }

            return("");
        }
Пример #3
0
        public static void Main(string[] args)
        {
            CategorizedSettingsElementCollection systemSettings = ConfigurationFile.Open(GetConfigurationFileName(args)).Settings["systemSettings"];
            string  cachePath = string.Format("{0}{1}ConfigurationCache{1}", FilePath.GetAbsolutePath(""), Path.DirectorySeparatorChar);
            DataSet configuration;

            systemSettings.Add("NodeID", Guid.NewGuid().ToString(), "Unique Node ID");
            systemSettings.Add("ConfigurationType", "Database", "Specifies type of configuration: Database, WebService, BinaryFile or XmlFile");
            systemSettings.Add("ConnectionString", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=IaonHost.mdb", "Configuration database connection string");
            systemSettings.Add("DataProviderString", "AssemblyName={System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089};ConnectionType=System.Data.OleDb.OleDbConnection;AdapterType=System.Data.OleDb.OleDbDataAdapter", "Configuration database ADO.NET data provider assembly type creation string");
            systemSettings.Add("ConfigurationCachePath", cachePath, "Defines the path used to cache serialized configurations");
            systemSettings.Add("CachedConfigurationFile", "SystemConfiguration.xml", "File name for last known good system configuration (only cached for a Database or WebService connection)");
            systemSettings.Add("ConfigurationBackups", 5, "Defines the total number of older backup configurations to maintain.");

            s_nodeID                        = systemSettings["NodeID"].ValueAs <Guid>();
            s_configurationType             = systemSettings["ConfigurationType"].ValueAs <ConfigurationType>();
            s_connectionString              = systemSettings["ConnectionString"].Value;
            s_dataProviderString            = systemSettings["DataProviderString"].Value;
            s_cachedXmlConfigurationFile    = FilePath.AddPathSuffix(cachePath) + systemSettings["CachedConfigurationFile"].Value;
            s_cachedBinaryConfigurationFile = FilePath.AddPathSuffix(cachePath) + FilePath.GetFileNameWithoutExtension(s_cachedXmlConfigurationFile) + ".bin";
            s_configurationBackups          = systemSettings["ConfigurationBackups"].ValueAs(5);

            configuration = GetConfigurationDataSet();
            ExecuteConfigurationCache(configuration);

            Console.WriteLine("Press 'Enter' to exit...");
            Console.ReadLine();
        }
Пример #4
0
        private static void BuildDirectoryTags(List <string> directoryTags, List <string[]> folderList, int level)
        {
            List <IGrouping <string, string[]> > groupings = folderList
                                                             .Where(folder => folder.Length > level)
                                                             .GroupBy(folder => string.Join(Path.DirectorySeparatorChar.ToString(), folder.Take(level + 1)))
                                                             .OrderBy(grouping => grouping.Key)
                                                             .ToList();

            foreach (IGrouping <string, string[]> grouping in groupings)
            {
                if (grouping.Count() == 1)
                {
                    string[] folder = grouping.First();
                    string   name   = FilePath.GetLastDirectoryName(FilePath.AddPathSuffix(string.Join(Path.DirectorySeparatorChar.ToString(), folder)));

                    directoryTags.Add($"{new string(' ', level * 2)}<Directory Id=\"{GetDirectoryID(string.Join("", folder))}\" Name=\"{name}\" />");
                }
                else
                {
                    List <string[]> subfolderList = grouping
                                                    .Where(folder => folder.Length > level + 1)
                                                    .ToList();

                    string name = FilePath.GetLastDirectoryName(FilePath.AddPathSuffix(grouping.Key));

                    directoryTags.Add($"{new string(' ', level * 2)}<Directory Id=\"{GetDirectoryID(grouping.Key)}\" Name=\"{name}\">");
                    BuildDirectoryTags(directoryTags, subfolderList, level + 1);
                    directoryTags.Add($"{new string(' ', level * 2)}</Directory>");
                }
            }
        }
Пример #5
0
        private void StartConsoleProcess(string configFile)
        {
            // Stop any existing running process
            StopConsoleProcess();

            m_consoleProcess = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    UseShellExecute        = false,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    CreateNoWindow         = true,
                    FileName = $"{FilePath.AddPathSuffix(Path.GetDirectoryName(configFile))}{HostApp}Console.exe"
                },
                EnableRaisingEvents = true
            };

            // Example to send command to console:
            // m_consoleProcess.StandardInput.WriteLine("ReloadConfig");

            m_consoleProcess.OutputDataReceived += m_consoleProcess_DataReceived;
            m_consoleProcess.ErrorDataReceived  += m_consoleProcess_DataReceived;
            m_consoleProcess.Exited             += m_consoleProcess_Exited;
            m_consoleProcess.Start();
            m_consoleProcess.BeginOutputReadLine();
        }
Пример #6
0
        // Static Constructor

        static MainWindow()
        {
            CategorizedSettingsElementCollection systemSettings = ConfigurationFile.Current.Settings["systemSettings"];

            systemSettings.Add("WebHostURL", "http://localhost:8080", "The web hosting URL for user interface operation. For increased security, only bind to localhost.");
            systemSettings.Add("DefaultWebPage", "Index.cshtml", "Determines if cache control is enabled for browser clients.");
            systemSettings.Add("CompanyName", "Grid Protection Alliance", "The name of the company who owns this instance of the openMIC.");
            systemSettings.Add("CompanyAcronym", "GPA", "The acronym representing the company who owns this instance of the openMIC.");
            systemSettings.Add("DateFormat", "MM/dd/yyyy", "The default date format to use when rendering timestamps.");
            systemSettings.Add("TimeFormat", "HH:mm.ss.fff", "The default time format to use when rendering timestamps.");
            systemSettings.Add("BootstrapTheme", "Content/bootstrap.min.css", "Path to Bootstrap CSS to use for rendering styles.", false, SettingScope.User);
            systemSettings.Add("SubscriptionConnectionString", "server=localhost:6190; interface=0.0.0.0", "Connection string for data subscriptions to openECA server.", false, SettingScope.User);
            systemSettings.Add("DefaultProjectPath", "openECA Projects", "Default path on which to store the user's projects.", false, SettingScope.User);

            Model = new AppModel();
            Model.Global.WebHostURL                   = systemSettings["WebHostURL"].Value;
            Model.Global.DefaultWebPage               = systemSettings["DefaultWebPage"].Value;
            Model.Global.CompanyName                  = systemSettings["CompanyName"].Value;
            Model.Global.CompanyAcronym               = systemSettings["CompanyAcronym"].Value;
            Model.Global.ApplicationName              = "openECA Data Modeling Manager";
            Model.Global.ApplicationDescription       = "open Extensible Control & Analytics Client";
            Model.Global.ApplicationKeywords          = "open source, utility, software, analytics";
            Model.Global.DateFormat                   = systemSettings["DateFormat"].Value;
            Model.Global.TimeFormat                   = systemSettings["TimeFormat"].Value;
            Model.Global.DateTimeFormat               = $"{Model.Global.DateFormat} {Model.Global.TimeFormat}";
            Model.Global.BootstrapTheme               = systemSettings["BootstrapTheme"].Value;
            Model.Global.SubscriptionConnectionString = systemSettings["SubscriptionConnectionString"].Value;
            Model.Global.DefaultProjectPath           = FilePath.AddPathSuffix(systemSettings["DefaultProjectPath"].Value);
        }
Пример #7
0
        private static void RestoreEmbeddedFiles()
        {
            Assembly executingAssembly = AssemblyInfo.ExecutingAssembly.Assembly;
            string   targetPath        = FilePath.AddPathSuffix(FilePath.GetAbsolutePath(""));

            // This simple file restoration assumes embedded resources to restore are in root namespace
            foreach (string name in executingAssembly.GetManifestResourceNames())
            {
                using (Stream resourceStream = executingAssembly.GetManifestResourceStream(name))
                {
                    if (resourceStream == null)
                    {
                        continue;
                    }

                    string sourceNamespace = $"{nameof(DNP3ConfigGenerator)}.";
                    string filePath        = name;

                    // Remove namespace prefix from resource file name
                    if (filePath.StartsWith(sourceNamespace))
                    {
                        filePath = filePath.Substring(sourceNamespace.Length);
                    }

                    string targetFileName = Path.Combine(targetPath, filePath);
                    bool   restoreFile    = true;

                    if (File.Exists(targetFileName))
                    {
                        string resourceMD5 = GetMD5HashFromStream(resourceStream);
                        resourceStream.Seek(0, SeekOrigin.Begin);
                        restoreFile = !resourceMD5.Equals(GetMD5HashFromFile(targetFileName));
                    }

                    if (!restoreFile)
                    {
                        continue;
                    }

                    if (string.Compare(Path.GetExtension(targetFileName), ".exe", StringComparison.OrdinalIgnoreCase) == 0 ||
                        string.Compare(Path.GetExtension(targetFileName), ".dll", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        using (FileStream writer = File.Create(targetFileName))
                            resourceStream.CopyTo(writer);
                    }
                    else
                    {
                        byte[] buffer = new byte[resourceStream.Length];
                        resourceStream.Read(buffer, 0, (int)resourceStream.Length);

                        using (StreamWriter writer = File.CreateText(targetFileName))
                            writer.Write(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                    }
                }
            }
        }
Пример #8
0
        private static void BuildFolderList(List <string> folderList, string path, string rootPath)
        {
            string name;

            foreach (string folder in Directory.EnumerateDirectories(path))
            {
                name = FilePath.AddPathSuffix(rootPath + FilePath.GetLastDirectoryName(FilePath.AddPathSuffix(folder)));
                folderList.Add(name);
                BuildFolderList(folderList, folder, name);
            }
        }
Пример #9
0
        /// <summary>
        /// Restores embedded resource Modbus configurations.
        /// </summary>
        /// <param name="targetPath">Target locations for restoration.</param>
        public static void RestoreConfigurations(string targetPath)
        {
            Assembly executingAssembly = AssemblyInfo.ExecutingAssembly.Assembly;

            targetPath = FilePath.AddPathSuffix(targetPath);

            foreach (string name in executingAssembly.GetManifestResourceNames().Where(name => name.EndsWith(".json")))
            {
                using (Stream resourceStream = executingAssembly.GetManifestResourceStream(name))
                {
                    if ((object)resourceStream != null)
                    {
                        string filePath = name;

                        //                                 1         2
                        //                       012345678901234567890123456789
                        if (filePath.StartsWith("ModbusAdapters.ModbusConfigs."))
                        {
                            filePath = filePath.Substring(29);
                        }

                        filePath = $"{FilePath.GetFileNameWithoutExtension(filePath).Replace('.', Path.DirectorySeparatorChar).Replace("_", "")}.json";

                        string targetFileName = Path.Combine(targetPath, filePath);
                        bool   restoreFile    = true;

                        if (File.Exists(targetFileName))
                        {
                            string resourceMD5 = GetMD5HashFromStream(resourceStream);
                            resourceStream.Seek(0, SeekOrigin.Begin);
                            restoreFile = !resourceMD5.Equals(GetMD5HashFromFile(targetFileName));
                        }

                        if (restoreFile)
                        {
                            byte[] buffer = new byte[resourceStream.Length];
                            resourceStream.Read(buffer, 0, (int)resourceStream.Length);

                            string directory = Path.GetDirectoryName(targetFileName);

                            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            using (StreamWriter writer = File.CreateText(targetFileName))
                                writer.Write(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                        }
                    }
                }
            }
        }
Пример #10
0
        private static void BuildFolderList(List <string> folderList, string path, string rootPath)
        {
            string name;

            foreach (string folder in Directory.EnumerateDirectories(path))
            {
                name = FilePath.AddPathSuffix(rootPath + FilePath.GetLastDirectoryName(FilePath.AddPathSuffix(folder)));
                if (!name.Contains("Scripts\\TS\\") && !name.Contains("Scripts\\TSX\\"))
                {
                    folderList.Add(name);
                    BuildFolderList(folderList, folder, name);
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Kicks off a task to pre-compile Razor templates.
        /// </summary>
        /// <param name="modelType">The type of the model used for the application.</param>
        /// <param name="exceptionHandler">Exception handler used to report issues, if any.</param>
        /// <param name="templatePath">Template path is use; otherwise, set to <c>null</c> to use default path.</param>
        public Task PreCompile(Type modelType, Action <Exception> exceptionHandler, string templatePath)
        {
            if (string.IsNullOrEmpty(templatePath))
            {
                templatePath = TemplatePath;
            }

            return(Task.Run(() =>
            {
                TLanguage languageType = new TLanguage();

                if (languageType.ResolutionMode == RazorViewResolutionMode.EmbeddedResource)
                {
                    foreach (string fileName in Assembly.GetExecutingAssembly().GetManifestResourceNames().Where(fileName => fileName.StartsWith(templatePath)))
                    {
                        try
                        {
                            m_engineService.Compile(fileName, modelType);
                        }
                        catch (Exception ex)
                        {
                            if ((object)exceptionHandler != null)
                            {
                                exceptionHandler(new InvalidOperationException($"Failed to pre-compile razor template \"{fileName}\": {ex.Message}", ex));
                            }
                        }
                    }
                }
                else
                {
                    string webRootFolder = FilePath.AddPathSuffix(templatePath);
                    string[] razorFiles = FilePath.GetFileList($"{webRootFolder}*.{(languageType.TargetLanguage == Language.CSharp ? "cs" : "vb")}html");

                    foreach (string fileName in razorFiles)
                    {
                        try
                        {
                            m_engineService.Compile(FilePath.GetFileName(fileName), modelType);
                        }
                        catch (Exception ex)
                        {
                            if ((object)exceptionHandler != null)
                            {
                                exceptionHandler(new InvalidOperationException($"Failed to pre-compile razor template \"{fileName}\": {ex.Message}", ex));
                            }
                        }
                    }
                }
            }));
        }
Пример #12
0
        private string GetConfigurationFileName()
        {
            // Search through list of known source applications (faster than manual search)
            foreach (string sourceApp in new[] { "openHistorian", "openPDC" })
            {
                string absolutePath = FilePath.GetAbsolutePath($"{sourceApp}.exe.config");

                if (File.Exists(absolutePath))
                {
                    m_sourceApp = sourceApp;
                    return(absolutePath);
                }
            }

            // Fall back on manual search
            foreach (string configFile in FilePath.GetFileList($"{FilePath.AddPathSuffix(FilePath.GetAbsolutePath(""))}*.exe.config"))
            {
                try
                {
                    XDocument serviceConfig = XDocument.Load(configFile);

                    string applicationName = serviceConfig
                                             .Descendants("securityProvider")
                                             .SelectMany(systemSettings => systemSettings.Elements("add"))
                                             .Where(element => "ApplicationName".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                             .Select(element => (string)element.Attribute("value"))
                                             .FirstOrDefault();

                    if (string.IsNullOrWhiteSpace(applicationName))
                    {
                        continue;
                    }

                    if (applicationName.Trim().Equals(FilePath.GetFileNameWithoutExtension(FilePath.GetFileNameWithoutExtension(configFile)), StringComparison.OrdinalIgnoreCase))
                    {
                        m_sourceApp = applicationName;
                        return(configFile);
                    }
                }
                catch (Exception ex)
                {
                    m_log.Publish(MessageLevel.Warning, "GetConfigurationFileName", $"Failed parse config file \"{configFile}\".", exception: ex);
                }
            }

            m_sourceApp = "unknown";
            return("unknown");
        }
Пример #13
0
        /// <summary>
        /// Retrieves list of directories from specified <paramref name="rootFolder"/>.
        /// </summary>
        /// <param name="rootFolder">Folder to load directories from.</param>
        /// <param name="showHidden"><c>true</c> to show hidden directories; otherwise, <c>false</c>.</param>
        /// <returns>List of directories from specified <paramref name="rootFolder"/>.</returns>
        public static IEnumerable <string> LoadDirectories(string rootFolder, bool showHidden)
        {
            if (string.IsNullOrWhiteSpace(rootFolder))
            {
                return(Directory.GetLogicalDrives());
            }

            IEnumerable <string> directories = Directory.GetDirectories(rootFolder);

            if (!showHidden)
            {
                directories = directories.Where(path => !new DirectoryInfo(path).Attributes.HasFlag(FileAttributes.Hidden));
            }

            return(new[] { "..\\" }.Concat(directories.Select(path => FilePath.AddPathSuffix(FilePath.GetLastDirectoryName(path)))));
        }
        // Writes the file that contains the program startup code to the given path.
        private void WriteProgramTo(string path, string projectName, IEnumerable <UserDefinedType> inputTypeReferences, UserDefinedType outputMappingType)
        {
            // Determine the path to the file containing the program startup code
            string programPath = Path.Combine(Path.Combine(path, projectName), $"Program.{m_fileSuffix}");

            // Generate usings for the namespaces of the classes the user needs for their inputs and outputs
            string usings = string.Join(Environment.NewLine, inputTypeReferences.Concat(new[] { outputMappingType })
                                        .Select(ConstructUsing)
                                        .Distinct()
                                        .OrderBy(str => str));

            // Write the contents of the program startup class to the class file
            File.WriteAllText(programPath, GetTextFromResource($"ECAClientUtilities.Template.{m_subFolder}.ProgramTemplate.txt")
                              .Replace("{Usings}", usings)
                              .Replace("{ProjectPath}", FilePath.AddPathSuffix(path))
                              .Replace("{ProjectName}", m_projectName));
        }
Пример #15
0
        /// <summary>
        /// Creates a new <see cref="WebServer"/>.
        /// </summary>
        /// <param name="webRootPath">Root path for web server; defaults to template path for <paramref name="razorEngineCS"/>.</param>
        /// <param name="razorEngineCS">Razor engine instance for .cshtml templates; uses default instance if not provided.</param>
        /// <param name="razorEngineVB">Razor engine instance for .vbhtml templates; uses default instance if not provided.</param>
        public WebServer(string webRootPath = null, IRazorEngine razorEngineCS = null, IRazorEngine razorEngineVB = null)
        {
            bool releaseMode = !AssemblyInfo.EntryAssembly.Debuggable;

            m_razorEngineCS       = razorEngineCS ?? (releaseMode ? RazorEngine <CSharp> .Default : RazorEngine <CSharpDebug> .Default as IRazorEngine);
            m_razorEngineVB       = razorEngineVB ?? (releaseMode ? RazorEngine <VisualBasic> .Default : RazorEngine <VisualBasicDebug> .Default as IRazorEngine);
            m_webRootPath         = FilePath.AddPathSuffix(webRootPath ?? m_razorEngineCS.TemplatePath);
            m_etagCache           = new ConcurrentDictionary <string, uint>(StringComparer.InvariantCultureIgnoreCase);
            m_pagedViewModelTypes = new ConcurrentDictionary <string, Tuple <Type, Type> >(StringComparer.InvariantCultureIgnoreCase);

            m_fileWatcher = new SafeFileWatcher(m_webRootPath)
            {
                IncludeSubdirectories = true,
                EnableRaisingEvents   = true
            };

            m_fileWatcher.Changed += m_fileWatcher_FileChange;
            m_fileWatcher.Deleted += m_fileWatcher_FileChange;
            m_fileWatcher.Renamed += m_fileWatcher_FileChange;

            ClientCacheEnabled = true;
        }
Пример #16
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            try
            {
                string targetDir = FilePath.AddPathSuffix(Context.Parameters["DP_TargetDir"]).Replace("\\\\", "\\");

                if (!string.IsNullOrEmpty(ConfigurationName))
                {
                    // Open the configuration file as an XML document.
                    string configFilePath = targetDir + ConfigurationName;

                    if (File.Exists(configFilePath))
                    {
                        XmlDocument configurationFile = new XmlDocument();
                        configurationFile.Load(configFilePath);
                        XmlNode systemSettingsNode = configurationFile.SelectSingleNode("configuration/categorizedSettings/systemSettings");

                        // Allow user to add or update custom configuration settings if desired
                        if (systemSettingsNode != null)
                        {
                            OnSystemSettingsLoaded(configurationFile, systemSettingsNode);
                        }

                        // Save any updates to configuration file
                        configurationFile.Save(configFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                // Not failing install if we can't perform these steps...
                MessageBox.Show("There was an exception detected during the install process: " + ex.Message);
            }
        }
Пример #17
0
        // Static Methods

        /// <summary>
        /// Loads the <see cref="AdoSecurityCache"/> for the current local user.
        /// </summary>
        /// <returns>Loaded instance of the <see cref="AdoSecurityCache"/>.</returns>
        public static AdoSecurityCache GetCurrentCache()
        {
            AdoSecurityCache currentCache;
            AdoSecurityCache localSecurityCache = null;

            // Define default cache path
            string cachePath = null;

            try
            {
                // Attempt to retrieve configuration cache path as defined in the config file
                ConfigurationFile configFile = ConfigurationFile.Current;
                CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];
                CategorizedSettingsElement           configurationCachePathSetting = systemSettings["ConfigurationCachePath"];

                if ((object)configurationCachePathSetting != null)
                {
                    cachePath = FilePath.GetAbsolutePath(systemSettings["ConfigurationCachePath"].Value);
                }

                if (string.IsNullOrEmpty(cachePath))
                {
                    cachePath = string.Format("{0}{1}ConfigurationCache{1}", FilePath.GetAbsolutePath(""), Path.DirectorySeparatorChar);
                }
            }
            catch (ConfigurationErrorsException)
            {
                cachePath = string.Format("{0}{1}ConfigurationCache{1}", FilePath.GetAbsolutePath(""), Path.DirectorySeparatorChar);
            }

            string localCacheFileName = Path.Combine(cachePath, DefaultCacheFileName);

            try
            {
                // Make sure configuration cache path exists
                if (!Directory.Exists(cachePath))
                {
                    Directory.CreateDirectory(cachePath);
                }

                // Initialize local ADO security cache (application may only have read-only access to this cache)
                localSecurityCache = new AdoSecurityCache
                {
                    FileName       = localCacheFileName,
                    ReloadOnChange = false,
                    AutoSave       = false
                };

                // Load initial ADO security data set
                localSecurityCache.Load();

                // Validate that current user has write access to the local cache folder
                string tempFile = FilePath.GetDirectoryName(localCacheFileName) + Guid.NewGuid() + ".tmp";

                using (File.Create(tempFile))
                {
                }

                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }

                // No access issues exist, use local cache as the primary cache
                currentCache          = localSecurityCache;
                currentCache.AutoSave = true;
                localSecurityCache    = null;
            }
            catch (UnauthorizedAccessException)
            {
                // User does not have needed serialization access to common cache folder,
                // use a path where user will have rights
                string userCacheFolder   = FilePath.AddPathSuffix(FilePath.GetApplicationDataFolder());
                string userCacheFileName = userCacheFolder + FilePath.GetFileName(localCacheFileName);

                // Make sure user directory exists
                if (!Directory.Exists(userCacheFolder))
                {
                    Directory.CreateDirectory(userCacheFolder);
                }

                // Copy existing common cache if none exists
                if (File.Exists(localCacheFileName) && !File.Exists(userCacheFileName))
                {
                    File.Copy(localCacheFileName, userCacheFileName);
                }

                // Initialize primary cache within user folder
                currentCache = new AdoSecurityCache
                {
                    FileName       = userCacheFileName,
                    ReloadOnChange = false,
                    AutoSave       = true
                };

                // Load initial ADO security data set
                currentCache.Load();

                // Update user located security cache if locally located security cache is newer
                if ((object)localSecurityCache != null && File.Exists(localCacheFileName) && File.Exists(userCacheFileName) && File.GetLastWriteTime(localCacheFileName) > File.GetLastWriteTime(userCacheFileName))
                {
                    currentCache.DataSet = localSecurityCache.DataSet;
                }
            }

            if ((object)localSecurityCache != null)
            {
                localSecurityCache.Dispose();
            }

            return(currentCache);
        }
Пример #18
0
        private static string GetConfigurationFileName()
        {
            if (!string.IsNullOrWhiteSpace(s_hostConfigFileName) && File.Exists(s_hostConfigFileName))
            {
                return(s_hostConfigFileName);
            }

            string getConfigurationFileName()
            {
                Arguments arguments = new Arguments(Environment.CommandLine, true);

                if (arguments.Count > 0 && File.Exists(arguments["OrderedArg1"]))
                {
                    return(arguments["OrderedArg1"]);
                }

                // Will be faster to load known config file, try a few common ones first
                string[] knownConfigurationFileNames =
                {
                    "openPDC.exe.config",
                    "SIEGate.exe.config",
                    "openHistorian.exe.config",
                    "substationSBG.exe.config",
                    "openMIC.exe.config",
                    "PDQTracker.exe.config",
                    "openECA.exe.config"
                };

                // Search for the file name in the list of known configuration files
                foreach (string fileName in knownConfigurationFileNames)
                {
                    string absolutePath = FilePath.GetAbsolutePath(fileName);

                    if (File.Exists(absolutePath))
                    {
                        return(absolutePath);
                    }
                }

                // Fall back on manual search
                foreach (string configFile in FilePath.GetFileList($"{FilePath.AddPathSuffix(FilePath.GetAbsolutePath(""))}*.exe.config"))
                {
                    try
                    {
                        XDocument serviceConfig = XDocument.Load(configFile);

                        string applicationName = serviceConfig
                                                 .Descendants("securityProvider")
                                                 .SelectMany(systemSettings => systemSettings.Elements("add"))
                                                 .Where(element => "ApplicationName".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                                 .Select(element => (string)element.Attribute("value"))
                                                 .FirstOrDefault();

                        if (string.IsNullOrWhiteSpace(applicationName))
                        {
                            continue;
                        }

                        if (applicationName.Trim().Equals(FilePath.GetFileNameWithoutExtension(FilePath.GetFileNameWithoutExtension(configFile)), StringComparison.OrdinalIgnoreCase))
                        {
                            return(configFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Just move on to the next config file if XML parsing fails
                        Program.Log.Publish(MessageLevel.Warning, "GetConfigurationFileName", $"Failed parse config file \"{configFile}\".", exception: ex);
                    }
                }

                return(ConfigurationFile.Current.Configuration.FilePath);
            }

            return(s_hostConfigFileName = getConfigurationFileName());
        }
Пример #19
0
        public IEnumerable <string> LoadDirectories(string rootFolder, bool showHidden, bool showFiles)
        {
            if (string.IsNullOrWhiteSpace(rootFolder))
            {
                return(Directory.GetLogicalDrives());
            }

            IEnumerable <string> directories = Directory.GetDirectories(rootFolder);
            IEnumerable <string> files       = Directory.GetFiles(rootFolder);

            if (!showHidden)
            {
                directories = directories.Where(path => !new DirectoryInfo(path).Attributes.HasFlag(FileAttributes.Hidden));
            }

            IEnumerable <string> returnString = new[] { "..\\" }.Concat(directories.Select(path => FilePath.AddPathSuffix(FilePath.GetLastDirectoryName(path))));

            if (showFiles)
            {
                returnString = returnString.Concat(files.Select(file => file.Split('\\')[file.Split('\\').Count() - 1]));
            }

            return(returnString);
        }
Пример #20
0
        // Static Methods

        /// <summary>
        /// Loads the <see cref="UserRoleCache"/> for the current local user.
        /// </summary>
        /// <returns>Loaded instance of the <see cref="UserRoleCache"/>.</returns>
        public static UserRoleCache GetCurrentCache()
        {
            UserRoleCache currentCache;
            UserRoleCache localUserRoleCache;
            string        localCacheFileName = FilePath.GetAbsolutePath(DefaultCacheFileName);

            // Initialize local user role cache (application may only have read-only access to this cache)
            localUserRoleCache = new UserRoleCache
            {
                FileName = localCacheFileName,
#if DNF45 && !MONO
                ReloadOnChange = true,
#else
                // Reload on change is disabled to eliminate GC handle leaks on .NET 4.0, this prevents
                // automatic runtime reloading of key/iv data cached by another application.
                ReloadOnChange = false,
#endif
                AutoSave = false
            };

            // Load initial user roles
            localUserRoleCache.Load();

            try
            {
                // Validate that user has write access to the local cache folder
                string tempFile = FilePath.GetDirectoryName(localCacheFileName) + Guid.NewGuid() + ".tmp";

                using (File.Create(tempFile))
                {
                }

                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }

                // No access issues exist, use local cache as the primary cache
                currentCache          = localUserRoleCache;
                currentCache.AutoSave = true;
            }
            catch (UnauthorizedAccessException)
            {
                // User does not have needed serialization access to common cache folder,
                // use a path where user will have rights
                string userCacheFolder   = FilePath.AddPathSuffix(FilePath.GetApplicationDataFolder());
                string userCacheFileName = userCacheFolder + FilePath.GetFileName(localCacheFileName);

                // Make sure user directory exists
                if (!Directory.Exists(userCacheFolder))
                {
                    Directory.CreateDirectory(userCacheFolder);
                }

                // Copy existing common cache if none exists
                if (File.Exists(localCacheFileName) && !File.Exists(userCacheFileName))
                {
                    File.Copy(localCacheFileName, userCacheFileName);
                }

                // Initialize primary cache within user folder
                currentCache = new UserRoleCache
                {
                    FileName = userCacheFileName,
#if DNF45 && !MONO
                    ReloadOnChange = true,
#else
                    // Reload on change is disabled to eliminate GC handle leaks on .NET 4.0, this prevents
                    // automatic runtime reloading of key/iv data cached by another application.
                    ReloadOnChange = false,
#endif
                    AutoSave = true
                };

                // Load initial roles
                currentCache.Load();

                // Merge new or updated roles, protected folder roles taking precedence over user folder roles
                currentCache.MergeRight(localUserRoleCache);
            }

            return(currentCache);
        }
Пример #21
0
        /// <summary>
        /// Starts the fault location engine.
        /// </summary>
        public void Start()
        {
            // Make sure default service settings exist
            ConfigurationFile configFile = ConfigurationFile.Current;

            // System settings
            // TODO: Add description to system settings
            CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];

            systemSettings.Add("DeviceDefinitionsFile", "DeviceDefinitions.xml", "");
            systemSettings.Add("ProcessDelay", "15", "");
            systemSettings.Add("DropFolder", "Drop", "");
            systemSettings.Add("LengthUnits", "Miles", "");
            systemSettings.Add("DebugLevel", "1", "");
            systemSettings.Add("DebugFolder", "Debug", "");

            // Retrieve file paths as defined in the config file
            m_deviceDefinitionsFile = FilePath.GetAbsolutePath(systemSettings["DeviceDefinitionsFile"].Value);
            m_processDelay          = systemSettings["ProcessDelay"].ValueAs(m_processDelay);
            m_dropFolder            = FilePath.AddPathSuffix(FilePath.GetAbsolutePath(systemSettings["DropFolder"].Value));
            m_lengthUnits           = systemSettings["LengthUnits"].Value;
            m_debugLevel            = systemSettings["DebugLevel"].ValueAs(m_debugLevel);
            m_debugFolder           = FilePath.AddPathSuffix(FilePath.GetAbsolutePath(systemSettings["DebugFolder"].Value));

            // Load the fault results writer defined in systemSettings
            using (AdapterLoader <IFaultResultsWriter> resultsWriters = m_resultsWriters)
            {
                m_resultsWriters = new AdapterLoader <IFaultResultsWriter>();
                m_resultsWriters.AdapterCreated  += (sender, args) => args.Argument.PersistSettings = true;
                m_resultsWriters.AdapterLoaded   += (sender, args) => OnStatusMessage("{0} has been loaded", args.Argument.Name);
                m_resultsWriters.AdapterUnloaded += (sender, args) => OnStatusMessage("{0} has been unloaded", args.Argument.Name);
                m_resultsWriters.Initialize();
            }

            try
            {
                // Make sure file path directories exist
                if (!Directory.Exists(m_dropFolder))
                {
                    Directory.CreateDirectory(m_dropFolder);
                }

                if (m_debugLevel > 0 && !Directory.Exists(m_debugFolder))
                {
                    Directory.CreateDirectory(m_debugFolder);
                }
            }
            catch (Exception ex)
            {
                OnProcessException(new InvalidOperationException(string.Format("Failed to create directory due to exception: {0}", ex.Message), ex));
            }

            // Setup new simple file monitor - we do this since the .NET 4.0 FileWatcher has a bad memory leak :-(
            if ((object)m_fileMonitor == null)
            {
                m_fileMonitor           = new System.Timers.Timer();
                m_fileMonitor.Interval  = 1000;
                m_fileMonitor.AutoReset = false;
                m_fileMonitor.Elapsed  += FileMonitor_Elapsed;
            }

            // Start watching for files
            m_fileMonitor.Start();
        }