Exemplo n.º 1
0
        protected static Configuration GetCurrentConfiguration()
        {
            if (currentConfig == null)
            {
                //
                if (GetIsWeb())
                {
                    currentConfig = WebConfigurationManager.OpenWebConfiguration("~/");
                }
                else
                {
                    if (Assembly.GetEntryAssembly() == null || Assembly.GetEntryAssembly().EntryPoint == null) // If the entry point in DLL (it was called from an external programm)
                    {
                        var registryConfiguration = GetConfigurationPathFromRegistry();
                        if (string.IsNullOrWhiteSpace(registryConfiguration))
                        {
                            configurationFilePath = configurationFilePath ?? Assembly.GetExecutingAssembly().Location;
                            currentConfig         = ConfigurationManager.OpenExeConfiguration(configurationFilePath); //ConfigurationUserLevel.PerUserRoamingAndLocal
                        }
                        else
                        {
                            configurationFilePath = Path.Combine(registryConfiguration, configurationFileName);
                            if (File.Exists(configurationFilePath))
                            {
                                ConfigurationFileMap fl = new ConfigurationFileMap(configurationFilePath);
                                currentConfig = ConfigurationManager.OpenMappedMachineConfiguration(fl);
                            }
                            else
                            {
                                throw new FileNotFoundException($"The configuration file {configurationFilePath} doen't exist.");
                            }
                        }
                    }
                    else
                    {
                        currentConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    }
                }
            }

            return(currentConfig);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the module context section from the specified configuration file
        /// </summary>
        /// <param name="fileInfo">Specifies the location of the configuration file to be loaded</param>
        /// <returns>ModuleContextSection of current module</returns>
        public static ModuleContextSection GetModuleContextSection(FileInfo fileInfo)
        {
            Contract.Requires(null != fileInfo);
            Contract.Ensures(null != Contract.Result <ModuleContextSection>());

            var configurationFileMap = new ConfigurationFileMap(fileInfo.FullName);

            Contract.Assert(null != configurationFileMap, string.Format(Messages.ImportConfigurationConfigurationFileMapCreateFailed, fileInfo.FullName));

            var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configurationFileMap);

            Contract.Assert(null != configuration, string.Format(Messages.ImportConfigurationConfigurationOpenFailed, fileInfo.FullName));
            Contract.Assert(configuration.HasFile, string.Format(Messages.ImportConfigurationConfigurationHasFile, fileInfo.FullName));

            var moduleContextSection = configuration.GetSection(ModuleContextSection.SECTION_NAME) as ModuleContextSection;

            Contract.Assert(null != moduleContextSection, string.Format(Messages.ImportConfigurationSectionOpenFailed, fileInfo.FullName, ModuleContextSection.SECTION_NAME));

            return(moduleContextSection);
        }
        private static ClousotViaService()
        {
            var configFileName = "Microsoft.Research.CodeAnalysis.app.config";

            // It is not possible to load a resource as a configuration file
            // it has to be a real file on disk, that's why we use a temporary file
            var    assembly = Assembly.GetExecutingAssembly();
            string contents;

            using (var configFileReader = new StreamReader(assembly.GetManifestResourceStream(configFileName)))
                contents = configFileReader.ReadToEnd();
            var tempFileName = Path.GetTempFileName();

            using (var tempFileWriter = new StreamWriter(tempFileName))
                tempFileWriter.Write(contents);

            var configFileMap = new ConfigurationFileMap(tempFileName);

            configuration = ConfigurationManager.OpenMappedMachineConfiguration(configFileMap);
        }
Exemplo n.º 4
0
        ClientSettingsSection GetConfigurationSection()
        {
            //string targetDir = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\Outlook\Addins\FonlowSyncML.Addin", "TargetDir", String.Empty);
            //if (String.IsNullOrEmpty(targetDir))
            //{
            //    Trace.TraceWarning("Cannot locate TargetDir in key FonlowSyncML.Addin, and the plugin will might not be loaded properly.");
            //    return null;
            //}
            ConfigurationFileMap fileMap = new ConfigurationFileMap(UserConfigFilePath);

            System.Configuration.Configuration config = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

            UserSettingsGroup userSectionGroup = config.SectionGroups["userSettings"] as UserSettingsGroup;

            if (userSectionGroup == null)
            {
                Trace.TraceWarning("No userSettings found in {0}.", UserConfigFilePath);
                return(null);
            }
            return(userSectionGroup.Sections[SectionName] as ClientSettingsSection);
        }
Exemplo n.º 5
0
        public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams)
        {
            bool                 useConfigMapPath = (bool)hostInitParams[0];
            IConfigMapPath       configMapPath    = (IConfigMapPath)hostInitParams[1];
            ConfigurationFileMap fileMap          = (ConfigurationFileMap)hostInitParams[2];
            string               appPath          = (string)hostInitParams[3];
            string               appSiteName      = (string)hostInitParams[4];
            string               appSiteID        = (string)hostInitParams[5];

            if (hostInitParams.Length > 6)
            {
                // If VS sent a 7th param, it is the .Net Framwework Target version moniker
                string fxMoniker = hostInitParams[6] as string;
                _machineConfigFile = GetMachineConfigPathFromTargetFrameworkMoniker(fxMoniker);
                if (!string.IsNullOrEmpty(_machineConfigFile))
                {
                    _rootWebConfigFile = Path.Combine(Path.GetDirectoryName(_machineConfigFile), "web.config");
                }
            }

            Debug.Assert(configMapPath == null || useConfigMapPath, "non-null configMapPath without useConfigMapPath == true");

            Host.Init(configRoot, hostInitParams);

            ChooseAndInitConfigMapPath(useConfigMapPath, configMapPath, fileMap);

            appPath      = UrlPath.RemoveSlashFromPathIfNeeded(appPath);
            _appPath     = VirtualPath.CreateAbsoluteAllowNull(appPath);
            _appSiteName = appSiteName;
            _appSiteID   = appSiteID;

            if (!String.IsNullOrEmpty(_appSiteID) && _appPath != null)
            {
                _appConfigPath = GetConfigPathFromSiteIDAndVPath(_appSiteID, _appPath);
            }

#if DBG
            _inited = true;
#endif
        }
Exemplo n.º 6
0
        public static ActionResult BeforeUninstall(Session session)
        {
            session.Log("Begin BeforeUninstall");

            try
            {
                System.Configuration.Configuration config = ConfigurationManager.OpenMachineConfiguration();
                Debug.Assert(config != null, "Machine.Config returned null");

                MachineConfigManager.RemoveMachineConfigurationInfo(config);

                if (System.Environment.Is64BitOperatingSystem)
                {
                    //For 64-Bit operating system there should be updated the 64-bit machine config as well
                    string machineConfigPathFor64Bit = System.Runtime.InteropServices.RuntimeEnvironment
                                                       .GetRuntimeDirectory().Replace("Framework", "Framework64");

                    ConfigurationFileMap configMap = new ConfigurationFileMap(
                        System.IO.Path.Combine(machineConfigPathFor64Bit,
                                               "Config", "machine.config"));

                    config = ConfigurationManager.OpenMappedMachineConfiguration(configMap);
                    Debug.Assert(config != null, "Machine.Config for 64-bit returned null");

                    MachineConfigManager.RemoveMachineConfigurationInfo(config);
                }

                session.Log("End BeforeUninstall with success.");

                return(ActionResult.Success);
            }
            catch (Exception ex)
            {
                session.Log("Error while removing adapter configuration information" + ex.Message);
                session.Log("End BeforeUninstall with error.");

                return(ActionResult.Failure);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 保存配置
        /// </summary>
        public void SaveConfig()
        {
            string configpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "user.config");

            ConfigurationFileMap map        = new ConfigurationFileMap(configpath);
            Configuration        userconfig = ConfigurationManager.OpenMappedMachineConfiguration(map);

            AppSettingsSection appsetting = userconfig.AppSettings;

            //获取改变目录前数据存储路径
            string previewdatapath = string.Empty;

            if (!appsetting.Settings.AllKeys.Contains("DataFolderPath"))
            {
                previewdatapath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
            }
            else
            {
                previewdatapath = appsetting.Settings["DataFolderPath"].Value;
            }

            appsetting.Settings.Remove("DataFolderPath");
            appsetting.Settings.Add("DataFolderPath", DataFolderPath);

            #region 数据移动
            if (Directory.Exists(DataFolderPath))
            {
                Directory.Delete(DataFolderPath);
            }
            if (Directory.Exists(previewdatapath))
            {
                Directory.CreateDirectory(previewdatapath).MoveTo(DataFolderPath);
                //Directory.Move(previewdatapath, DataFolderPath);
            }
            #endregion

            userconfig.Save();
        }
Exemplo n.º 8
0
        public static void SetTraceLogPath(string prefix)
        {
            var logFilePath   = DocumentPath + "\\" + prefix + "_trace.log";
            var objConfigPath = new ConfigurationFileMap();
            var appPath       = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

            try
            {
                objConfigPath.MachineConfigFilename = appPath;
                var entLibConfig                 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var loggingSettings              = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
                var traceListenerData            = loggingSettings.TraceListeners.Get("Flat File Trace Listener");
                var objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData;
                if (objFlatFileTraceListenerData != null)
                {
                    objFlatFileTraceListenerData.FileName = logFilePath;
                }
                entLibConfig.Save();
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Resolve内部猜测,不对,不知道
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve1 <T>()
        {
            //配置文件中AppSetting节点匹配T类型的Name,返回service
            //<component id="supplierAccountDao" service="PCMS.Core.IDao.ISupplierAccountDao, PCMS.Core" type="PCMS.Core.Dao.SupplierAccountDao, PCMS.Core"></component>
            //service="PCMS.Core.IDao.ISupplierAccountDao, PCMS.Core";
            XmlNode     service = (XmlNode)System.Configuration.ConfigurationManager.GetSection("castle");
            XmlNodeList list    = service.ChildNodes;

            foreach (XmlNode xn in list)
            {
                ConfigurationFileMap cfm = new ConfigurationFileMap("file://Castle.Services.Core.config");
                //ConfigurationFileMap uri =xn.Attributes["uri"] as ConfigurationFileMap;
                //XmlNode namespaceURI =xn.OuterXml as XmlNode;
                System.Configuration.Configuration con = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(cfm);
            }
            //string service1 = service.Split(',')[1];
            //string service0 = service.Split(',')[0];
            //Assembly assembly = Assembly.Load(service1);
            //Type type = assembly.GetType(service0);
            ////利用反射创建实现类
            //return (T)Activator.CreateInstance(type);
            return((T) new object());
        }
        private string GetMachineKeySectionXmlFromMachineConfig()
        {
            // Get the machine.config file.
            Configuration machineConfig =
                ConfigurationManager.OpenMachineConfiguration();
            // Get the machine.config file path.
            ConfigurationFileMap configFile =
                new ConfigurationFileMap(machineConfig.FilePath);

            // Map the application configuration file to the machine
            // configuration file.
            Configuration config =
                ConfigurationManager.OpenMappedMachineConfiguration(
                    configFile);

            MachineKeySection machineKeySection = (MachineKeySection)config.GetSection("machineKey");

            if (machineKeySection == null)
            {
                return(null);
            }
            return(machineKeySection.SectionInformation.GetRawXml());
        }
Exemplo n.º 11
0
    // </Snippet7>

    // <Snippet4>
    // Access the machine configuration file using mapping.
    // The function uses the OpenMappedMachineConfiguration
    // method to access the machine configuration.
    public static void MapMachineConfiguration()
    {
        // Get the machine.config file.
        Configuration machineConfig =
            ConfigurationManager.OpenMachineConfiguration();
        // Get the machine.config file path.
        ConfigurationFileMap configFile =
            new ConfigurationFileMap(machineConfig.FilePath);

        // Map the application configuration file to the machine
        // configuration file.
        Configuration config =
            ConfigurationManager.OpenMappedMachineConfiguration(
                configFile);

        // Get the AppSettings section.
        AppSettingsSection appSettingSection =
            (AppSettingsSection)config.GetSection("appSettings");

        appSettingSection.SectionInformation.AllowExeDefinition =
            ConfigurationAllowExeDefinition.MachineToRoamingUser;

        // Display the configuration file sections.
        ConfigurationSectionCollection sections =
            config.Sections;

        Console.WriteLine();
        Console.WriteLine("Using OpenMappedMachineConfiguration.");
        Console.WriteLine("Sections in machine.config:");

        // Get the sections in the machine.config.
        foreach (ConfigurationSection section in sections)
        {
            string name = section.SectionInformation.Name;
            Console.WriteLine("Name: {0}", name);
        }
    }
Exemplo n.º 12
0
        static void InitUserConfig()
        {
            string configpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "user.config");

            if (!File.Exists(configpath))
            {
                Configuration temp = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                temp.SaveAs(configpath);
            }

            ConfigurationFileMap map        = new ConfigurationFileMap(configpath);
            Configuration        userconfig = ConfigurationManager.OpenMappedMachineConfiguration(map);

            if (userconfig.AppSettings == null)
            {
                userconfig.Sections.Add("appSettings", new AppSettingsSection());
                userconfig.Save();
            }
            AppSettingsSection appsetting = userconfig.AppSettings;

            if (appsetting.Settings.AllKeys.Contains("DataFolderPath"))
            {
                Current.DataFolderPath = appsetting.Settings["DataFolderPath"].Value;
            }

            if (!Directory.Exists(Current.DataFolderPath))
            {
                string datapath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
                appsetting.Settings.Remove("DataFolderPath");
                appsetting.Settings.Add("DataFolderPath", datapath);
                userconfig.Save();

                Current.DataFolderPath = datapath;
                Directory.CreateDirectory(Current.DataFolderPath);
            }
        }
	public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap) {}
Exemplo n.º 14
0
 public UserMapPath(ConfigurationFileMap fileMap) : this(fileMap, true)
 {
 }
Exemplo n.º 15
0
 //
 // Summary:
 //     Opens the machine configuration file as a System.Configuration.Configuration
 //     object that uses the specified file mapping.
 //
 // Parameters:
 //   fileMap:
 //     An System.Configuration.ExeConfigurationFileMap object that references configuration
 //     file to use instead of the application default configuration file.
 //
 // Returns:
 //     A System.Configuration.Configuration object.
 //
 // Exceptions:
 //   T:System.Configuration.ConfigurationErrorsException:
 //     A configuration file could not be loaded.
 public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
 {
     return(ConfigurationManager.OpenMappedMachineConfiguration(fileMap));
 }
 public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
 {
 }
Exemplo n.º 17
0
        public static System.Configuration.Configuration OpenConfigurationFromFile(string configFilePath)
        {
            var fileMap = new ConfigurationFileMap(configFilePath);

            return(ConfigurationManager.OpenMappedMachineConfiguration(fileMap));
        }
Exemplo n.º 18
0
 public static _Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
 {
     return(ConfigurationFactory.Create(typeof(WebConfigurationHost), fileMap));
 }
Exemplo n.º 19
0
        /// <summary>
        /// Log.config
        /// </summary>
        private void ReadXml()
        {
            XmlNode root = null;

            try
            {
                root = ConfigurationManager.GetSection(SectionName) as XmlNode;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
            if (root == null)
            {
                string file = AppDomain.CurrentDomain.BaseDirectory + "Log.config";
                Debug.WriteLine(file);
                if (!File.Exists(file))
                {
                    root = Factory.GetConfig();
                }
                else
                {
                    ConfigurationFileMap fileMap       = new ConfigurationFileMap(file);
                    Configuration        configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
                    ConfigurationSection section       = configuration.GetSection(SectionName);
                    string rawxml = section.SectionInformation.GetRawXml();
                    Debug.WriteLine(rawxml);
                    XmlDocument document = new XmlDocument();
                    document.LoadXml(rawxml);
                    root = document.FirstChild;
                    if (root == null)
                    {
                        root = Factory.GetConfig();
                    }
                }
            }
            if (root == null)
            {
                return;
            }
            if (!_appSettings.Contains(cLogLevel))
            {
                //level
                Debug.WriteLine(string.Format("{0}={1}", cLogLevel, root.Attributes[clevel].Value));
                _appSettings.Add(cLogLevel, root.Attributes[clevel].Value);
            }
            for (int i = 0, t = root.ChildNodes.Count; i < t; i++)
            {
                string key   = root.ChildNodes[i].Name;
                string value = root.ChildNodes[i].InnerText;
                //file
                if (key == cLogFile && !_appSettings.ContainsKey(cLogFile))
                {
                    _appSettings.Add(key, value);
                    if (!_appSettings.ContainsKey(cKeyFileLogEnabled))
                    {
                        if (root.ChildNodes[i].Attributes.Count != 0)
                        {
                            _appSettings.Add(cKeyFileLogEnabled, root.ChildNodes[i].Attributes[cEnabled].Value);
                            Debug.WriteLine(string.Format("{0}={1}", cKeyFileLogEnabled, root.ChildNodes[i].Attributes[cEnabled].Value));
                        }
                    }
                }
                //XML
                else if (key == cXmlLog && !_appSettings.Contains(cXmlLog))
                {
                    _appSettings.Add(key, value);
                    Debug.WriteLine(string.Format("{0}={1}", key, value));
                    if (!_appSettings.ContainsKey(cKeyXmlLogEnabled))
                    {
                        if (root.ChildNodes[i].Attributes.Count != 0)
                        {
                            _appSettings.Add(cKeyXmlLogEnabled, root.ChildNodes[i].Attributes[cEnabled].Value);
                        }
                    }
                }
                //ColorConsole
                else if (key == cLogConsole && !_appSettings.Contains(cLogConsole))
                {
                    _appSettings.Add(key, value);
                    Debug.WriteLine(string.Format("{0}={1}", key, value));
                    if (!_appSettings.ContainsKey(cLen))
                    {
                        if (root.ChildNodes[i].Attributes.Count != 0)
                        {
                            _appSettings.Add(cLen, root.ChildNodes[i].Attributes[cLen].Value);
                        }
                    }
                }
                //other
                else if (!_appSettings.Contains(key))
                {
                    Debug.WriteLine(string.Format("{0}={1}", key, value));
                    _appSettings.Add(key, value);
                }
            }
        }
Exemplo n.º 20
0
        // Choose the implementation of IConfigMapPath to use
        // in cases where it is not provided to us.
        void ChooseAndInitConfigMapPath(bool useConfigMapPath, IConfigMapPath configMapPath, ConfigurationFileMap fileMap)
        {
            if (useConfigMapPath)
            {
                _configMapPath = configMapPath;
            }
            else if (fileMap != null)
            {
                _configMapPath = new UserMapPath(fileMap);
            }
            else if (HostingEnvironment.IsHosted)
            {
                _configMapPath = HostingPreferredMapPath.GetInstance();
            }
            else
            {
                _configMapPath = IISMapPath.GetInstance();
            }

            // see if it supports IConfigMapPath2
            _configMapPath2 = _configMapPath as IConfigMapPath2;
        }
Exemplo n.º 21
0
        internal static System.Configuration.Configuration OpenConfiguration(WebLevel webLevel, ConfigurationFileMap fileMap, VirtualPath path, string site, string locationSubPath, string server, string userName, string password, IntPtr tokenHandle)
        {
            if (!IsValidSiteArgument(site))
            {
                throw System.Web.Util.ExceptionUtil.ParameterInvalid("site");
            }
            locationSubPath = ConfigurationFactory.NormalizeLocationSubPath(locationSubPath, null);
            if ((((!string.IsNullOrEmpty(server) && (server != ".")) && (!System.Web.Util.StringUtil.EqualsIgnoreCase(server, "127.0.0.1") && !System.Web.Util.StringUtil.EqualsIgnoreCase(server, "::1"))) && !System.Web.Util.StringUtil.EqualsIgnoreCase(server, "localhost")) && !System.Web.Util.StringUtil.EqualsIgnoreCase(server, Environment.MachineName))
            {
                object[] hostInitConfigurationParams = new object[9];
                hostInitConfigurationParams[0] = webLevel;
                hostInitConfigurationParams[2] = VirtualPath.GetVirtualPathString(path);
                hostInitConfigurationParams[3] = site;
                hostInitConfigurationParams[4] = locationSubPath;
                hostInitConfigurationParams[5] = server;
                hostInitConfigurationParams[6] = userName;
                hostInitConfigurationParams[7] = password;
                hostInitConfigurationParams[8] = tokenHandle;
                return(ConfigurationFactory.Create(typeof(RemoteWebConfigurationHost), hostInitConfigurationParams));
            }
            if (string.IsNullOrEmpty(server))
            {
                if (!string.IsNullOrEmpty(userName))
                {
                    throw System.Web.Util.ExceptionUtil.ParameterInvalid("userName");
                }
                if (!string.IsNullOrEmpty(password))
                {
                    throw System.Web.Util.ExceptionUtil.ParameterInvalid("password");
                }
                if (tokenHandle != IntPtr.Zero)
                {
                    throw System.Web.Util.ExceptionUtil.ParameterInvalid("tokenHandle");
                }
            }
            if (fileMap != null)
            {
                fileMap = (ConfigurationFileMap)fileMap.Clone();
            }
            WebConfigurationFileMap map = fileMap as WebConfigurationFileMap;

            if ((map != null) && !string.IsNullOrEmpty(site))
            {
                map.Site = site;
            }
            return(ConfigurationFactory.Create(typeof(WebConfigurationHost), new object[] { webLevel, fileMap, VirtualPath.GetVirtualPathString(path), site, locationSubPath }));
        }
Exemplo n.º 22
0
 /// <summary>
 /// Opens the machine configuration file as a System.Configuration.Configuration object that uses the specified file mapping.
 /// </summary>
 /// <param name="fileMap">An System.Configuration.ExeConfigurationFileMap object that references configuration
 /// file to use instead of the application default configuration file.</param>
 /// <returns>
 /// A System.Configuration.Configuration object.
 /// </returns>
 public System.Configuration.Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
 {
     return(ConfigurationManager.OpenMappedMachineConfiguration(fileMap));
 }
        private static System.Configuration.Configuration OpenWebConfigurationImpl(WebLevel webLevel, ConfigurationFileMap fileMap, string path, string site, string locationSubPath, string server, string userName, string password, IntPtr userToken)
        {
            VirtualPath path2;

            if (HostingEnvironment.IsHosted)
            {
                path2 = VirtualPath.CreateNonRelativeAllowNull(path);
            }
            else
            {
                path2 = VirtualPath.CreateAbsoluteAllowNull(path);
            }
            return(WebConfigurationHost.OpenConfiguration(webLevel, fileMap, path2, site, locationSubPath, server, userName, password, userToken));
        }
Exemplo n.º 24
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            string targetDir  = Context.Parameters[Argument.TargetDir].TrimEnd('\\');
            string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config");

            System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile);

            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args)
            {
                return(Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll")));
            });

            UhuruSection section = (UhuruSection)config.GetSection("uhuru");

            this.SetMsSqlStorageOptions(section);

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.BaseDir]))
            {
                section.Service.BaseDir = Context.Parameters[Argument.BaseDir];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Index]))
            {
                section.Service.Index = int.Parse(Context.Parameters[Argument.Index], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.StatusPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Argument.StatusPort], CultureInfo.InvariantCulture);
                section.Service.StatusPort = port;
                FirewallTools.OpenPort(port, "MsSqlNode Status");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.LocalDb]))
            {
                section.Service.LocalDB = Context.Parameters[Argument.LocalDb];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.LocalRoute]))
            {
                section.Service.LocalRoute = Context.Parameters[Argument.LocalRoute];
            }
            else
            {
                string ip = string.Empty;
                foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip = address.ToString();
                        break;
                    }
                }

                section.Service.LocalRoute = ip;
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.MaxDbSize]))
            {
                section.Service.MSSql.MaxDBSize = long.Parse(Context.Parameters[Argument.MaxDbSize], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.MaxLongQuery]))
            {
                section.Service.MSSql.MaxLengthyQuery = int.Parse(Context.Parameters[Argument.MaxLongQuery], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.MaxLongTx]))
            {
                section.Service.MSSql.MaxLengthTX = int.Parse(Context.Parameters[Argument.MaxLongTx], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Mbus]))
            {
                section.Service.MBus = Context.Parameters[Argument.Mbus];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.MigrationNfs]))
            {
                section.Service.MigrationNFS = Context.Parameters[Argument.MigrationNfs];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.NodeId]))
            {
                section.Service.NodeId = Context.Parameters[Argument.NodeId];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.ZInterval]))
            {
                section.Service.ZInterval = int.Parse(Context.Parameters[Argument.ZInterval], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Host]))
            {
                section.Service.MSSql.Host = Context.Parameters[Argument.Host];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Password]))
            {
                section.Service.MSSql.Password = Context.Parameters[Argument.Password];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.Port]))
            {
                section.Service.MSSql.Port = int.Parse(Context.Parameters[Argument.Port], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Argument.User]))
            {
                section.Service.MSSql.User = Context.Parameters[Argument.User];
            }

            section.DEA = null;
            config.Save();
        }
Exemplo n.º 25
0
        // same stack trace for OpenWebConfiguration_siteNull2_absolutePath.
        public void OpenMappedMachineConfiguration_absolute()
        {
            ConfigurationFileMap map = new ConfigurationFileMap();

            WebConfigurationManager.OpenMappedMachineConfiguration(map, "/clientTest");
        }
Exemplo n.º 26
0
        public static void ConnDevice()
        {
            //util.Connect();
            //XmlConfigurator.Configure();//Log4N 需要
            var configFile = Directory.GetCurrentDirectory() + "\\" + "Device.config";
            ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile);
            DeviceConfiguration  config  = ConfigurationManager.OpenMappedMachineConfiguration(fileMap).GetSection("deviceSettingGroup/deviceConfig") as DeviceConfiguration;

            Console.WriteLine();
            deviceMap.Clear();

            runMode = RunMode.Normal;
            foreach (DeviceSettingElement foo in config.DeviceSettings)
            {
                IDevice dvcCtrl;

                if (!foo.Enable.Equals("1"))
                {
                    Console.WriteLine("---Device:" + foo.Name + " is disabled !-------------------");
                    continue;
                }
                DeviceConfig dc = new DeviceConfig();
                dc.DeviceName     = foo.Name;
                dc.ConnectionType = foo.Conn_Type;
                dc.Vendor         = foo.Vendor;
                if (foo.Conn_Type.Equals("Socket"))
                {
                    dc.IPAdress = foo.Conn_Address;
                    dc.Port     = Int32.Parse(foo.Conn_Port);
                    dvcCtrl     = new DeviceController(dc);
                    dvcCtrl.AssignedRecevicedEvent(ReceivedEventMessage);
                    dvcCtrl.start();

                    Marco.deviceMap.Add(foo.Name, dvcCtrl);
                }
                else if (foo.Conn_Type.Equals("ComPort"))
                {
                    if (foo.Conn_Address.Equals(""))
                    {
                        string[] ports = SerialPort.GetPortNames();
                        if (ports.Count() == 0)
                        {
                            dc.PortName = "";
                        }
                        else
                        {
                            dc.PortName = ports[0];
                        }
                    }
                    else
                    {
                        dc.PortName = foo.Conn_Address;
                    }
                    dc.BaudRate  = foo.Com_Baud_Rate;
                    dc.DataBits  = foo.Com_Data_Bits;
                    dc.ParityBit = foo.Com_Parity_Bit;
                    dc.StopBit   = foo.Com_Stop_Bit;
                    dvcCtrl      = new DeviceController(dc);
                    dvcCtrl.AssignedRecevicedEvent(ReceivedEventMessage);
                    dvcCtrl.start();
                    Marco.deviceMap.Add(foo.Name, dvcCtrl);
                }
                else if (foo.Conn_Type.Equals("ICPDeviceNet"))
                {
                    if (foo.Conn_Address.Equals(""))
                    {
                        string[] ports = SerialPort.GetPortNames();
                        if (ports.Count() == 0)
                        {
                            dc.PortName = "";
                        }
                        else
                        {
                            dc.PortName = ports[0];
                        }
                    }
                    else
                    {
                        dc.PortName = foo.Conn_Address;
                    }

                    //暫時固定路徑
                    if (machineType == MachineType.Normal)
                    {
                        dc.File = "mini_18port.xls";
                    }
                    else
                    {
                        dc.File = "mini.xls";
                    }
                    //dc.File = foo.File;
                    dvcCtrl = new I7565DNM(dc);
                    if (!dvcCtrl.start() && foo.Conn_Address.Equals(""))
                    {
                        string[] ports = SerialPort.GetPortNames();

                        for (int i = 1; i < ports.Count(); i++)
                        {
                            dc.PortName = ports[i];
                            //dvcCtrlarray[].= ports[0];
                            dvcCtrl = new I7565DNM(dc);

                            if (dvcCtrl.start())
                            {
                                Marco.deviceMap.Add(foo.Name, dvcCtrl);
                                break;
                            }
                        }
                    }
                    else
                    {
                        Marco.deviceMap.Add(foo.Name, dvcCtrl);
                    }
                }
            }
            ////設定停用
            //var xmlDoc = new XmlDocument();
            //xmlDoc.Load(configFile);
            //xmlDoc.SelectSingleNode("//deviceSettingGroup/deviceConfig/devices/device[@name='Robot02']").Attributes["enable"].Value = "0";
            //xmlDoc.Save(configFile);
            //ConfigurationManager.RefreshSection("deviceSettingGroup/deviceConfig");
        }
Exemplo n.º 27
0
        // Create an instance of a Configuration object.
        // Used by design-time API to open a Configuration object.
        static internal Configuration OpenConfiguration(
            WebLevel webLevel, ConfigurationFileMap fileMap, VirtualPath path, string site, string locationSubPath,
            string server, string userName, string password, IntPtr tokenHandle)
        {
            Configuration configuration;

            if (!IsValidSiteArgument(site))
            {
                throw ExceptionUtil.ParameterInvalid("site");
            }

            locationSubPath = ConfigurationFactory.NormalizeLocationSubPath(locationSubPath, null);

            bool isRemote = !String.IsNullOrEmpty(server) &&
                            server != "." &&
                            !StringUtil.EqualsIgnoreCase(server, "127.0.0.1") &&
                            !StringUtil.EqualsIgnoreCase(server, "::1") &&
                            !StringUtil.EqualsIgnoreCase(server, "localhost") &&
                            !StringUtil.EqualsIgnoreCase(server, Environment.MachineName);


            if (isRemote)
            {
                configuration = ConfigurationFactory.Create(typeof(RemoteWebConfigurationHost),
                                                            webLevel, null, VirtualPath.GetVirtualPathString(path), site, locationSubPath, server, userName, password, tokenHandle);
            }
            else
            {
                if (String.IsNullOrEmpty(server))
                {
                    if (!String.IsNullOrEmpty(userName))
                    {
                        throw ExceptionUtil.ParameterInvalid("userName");
                    }

                    if (!String.IsNullOrEmpty(password))
                    {
                        throw ExceptionUtil.ParameterInvalid("password");
                    }

                    if (tokenHandle != (IntPtr)0)
                    {
                        throw ExceptionUtil.ParameterInvalid("tokenHandle");
                    }
                }

                // Create a copy of the fileMap, so that it cannot be altered by
                // its creator once we start using it.
                if (fileMap != null)
                {
                    fileMap = (ConfigurationFileMap)fileMap.Clone();
                }

                WebConfigurationFileMap webFileMap = fileMap as WebConfigurationFileMap;
                if (webFileMap != null && !String.IsNullOrEmpty(site))
                {
                    webFileMap.Site = site;
                }

                configuration = ConfigurationFactory.Create(typeof(WebConfigurationHost),
                                                            webLevel, fileMap, VirtualPath.GetVirtualPathString(path), site, locationSubPath);
            }

            return(configuration);
        }
Exemplo n.º 28
0
 public static _Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap,
                                                             string locationSubPath)
 {
     return(OpenMappedMachineConfiguration(fileMap));
 }
Exemplo n.º 29
0
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            string targetDir  = Context.Parameters[Arguments.TargetDir].TrimEnd('\\');
            string configFile = Path.Combine(targetDir, Assembly.GetExecutingAssembly().Location + ".config");

            System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(configFile);
            System.Configuration.Configuration        config  = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(delegate(object sender, ResolveEventArgs args)
            {
                return(Assembly.LoadFile(Path.Combine(targetDir, args.Name + ".dll")));
            });

            UhuruSection section = (UhuruSection)config.GetSection("uhuru");

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.BaseDir]))
            {
                section.DEA.BaseDir = Context.Parameters[Arguments.BaseDir];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.EnforceUlimit]))
            {
                section.DEA.EnforceUsageLimit = Convert.ToBoolean(Context.Parameters[Arguments.EnforceUlimit], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.FilerPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.FilerPort], CultureInfo.InvariantCulture);
                section.DEA.FilerPort = port;
                FirewallTools.OpenPort(port, "DEA FileServer");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.StatusPort]))
            {
                int port = Convert.ToInt32(Context.Parameters[Arguments.StatusPort], CultureInfo.InvariantCulture);
                section.DEA.StatusPort = port;
                FirewallTools.OpenPort(port, "DEA Status");
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.ForceHttpSharing]))
            {
                section.DEA.ForceHttpSharing = Convert.ToBoolean(Context.Parameters[Arguments.ForceHttpSharing], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.HeartBeatInterval]))
            {
                section.DEA.HeartbeatInterval = Convert.ToInt32(Context.Parameters[Arguments.HeartBeatInterval], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.LocalRoute]))
            {
                section.DEA.LocalRoute = Context.Parameters[Arguments.LocalRoute];
            }
            else
            {
                string ip = string.Empty;
                foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip = address.ToString();
                        break;
                    }
                }

                section.DEA.LocalRoute = ip;
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MaxMemory]))
            {
                section.DEA.MaxMemory = Convert.ToInt32(Context.Parameters[Arguments.MaxMemory], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MessageBus]))
            {
                section.DEA.MessageBus = Context.Parameters[Arguments.MessageBus];
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.MultiTenant]))
            {
                section.DEA.Multitenant = Convert.ToBoolean(Context.Parameters[Arguments.MultiTenant], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrEmpty(Context.Parameters[Arguments.Secure]))
            {
                section.DEA.Secure = Convert.ToBoolean(Context.Parameters[Arguments.Secure], CultureInfo.InvariantCulture);
            }

            section.Service = null;
            config.Save();

            using (ServerManager serverManager = new ServerManager())
            {
                Microsoft.Web.Administration.Configuration authenticationConfig = serverManager.GetApplicationHostConfiguration();

                Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = authenticationConfig.GetSection("system.webServer/security/authentication/anonymousAuthentication");
                anonymousAuthenticationSection["enabled"]     = true;
                anonymousAuthenticationSection["userName"]    = string.Empty;
                anonymousAuthenticationSection["password"]    = string.Empty;
                anonymousAuthenticationSection["logonMethod"] = @"ClearText";

                serverManager.CommitChanges();
            }
        }
 public void SaveMappedMachineConfiguration(ConfigurationFileMap fileMap)
 => SaveConfiguration(ConfigurationManager.OpenMappedMachineConfiguration(fileMap));
 public static System.Configuration.Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap, string locationSubPath)
 {
     return(OpenWebConfigurationImpl(WebLevel.Machine, fileMap, null, null, locationSubPath, null, null, null, IntPtr.Zero));
 }