protected static Process Start <T>(string executableFileName, T parameter, SubprocessConfiguration configuration, Uri address) { var configPath = Path.Combine(TempDir, "C" + Interlocked.Increment(ref _AssemblyCount) + ".T" + DateTime.Now.Ticks + ".config"); var configDocument = new ConfigXmlDocument(); AppendConfig(configDocument, ConfigurationUserLevel.None); AppendConfig(configDocument, ConfigurationUserLevel.PerUserRoaming); AppendConfig(configDocument, ConfigurationUserLevel.PerUserRoamingAndLocal); if (configuration.ShouldCreateConfig) { if (configDocument.DocumentElement == null) { configDocument.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration></configuration>"); } configDocument.Save(configPath); configuration.RaiseConfigCreated(new ConfigCreatedEventArgs(configPath)); } else if (configDocument.DocumentElement != null) { configDocument.Save(configPath); } var psi = new ProcessStartInfo(executableFileName); var spp = new SubprocessArgument <T>(); spp.TemporaryDirectory = TempDir; spp.Address = address; spp.Parameter = parameter; spp.ParentProcessId = Process.GetCurrentProcess().Id; spp.IsStandalone = configuration.IsStandalone; if (configuration.AttachDebugger) { spp.DebuggerInfo = DebuggerInfoProvider.GetCurrent(); } var argFilePath = Path.Combine(TempDir, "A" + Interlocked.Increment(ref _AssemblyCount) + ".T" + DateTime.Now.Ticks + ".xml"); using (var fs = new FileStream(argFilePath, FileMode.Create)) { new DataContractSerializer(spp.GetType()).WriteObject(fs, spp); } psi.Arguments = configDocument.DocumentElement != null ? (argFilePath + " \"" + configPath + "\"") : argFilePath; var p = Process.Start(psi); return(p); }
public static bool SaveSection(string fileName, string name, MailerConfiguration section) { System.Configuration.ConfigXmlDocument doc = new ConfigXmlDocument(); try { doc.Load(fileName); XmlNode configNode = doc.ChildNodes[1]; foreach (XmlNode node in configNode.ChildNodes) { if (node.Name == name) { configNode.RemoveChild(node); } } XmlNode newNode = section.CreateNode(doc, name); configNode.AppendChild(newNode); doc.Save(fileName); return(true); } catch { return(false); } }
internal void SaveSettings() { // Load the web.config file var filename = HttpContext.Current.Server.MapPath("~/web.config"); var webconfig = new ConfigXmlDocument(); webconfig.Load(filename); var node = webconfig.SelectSingleNode("/configuration/connectionStrings/add[@name='RedisCachingProvider']"); SaveAttribute(node, "connectionString", ConnectionString); node = webconfig.SelectSingleNode("/configuration/dotnetnuke/caching"); SaveAttribute(node, "defaultProvider", CachingProviderEnabled ? "RedisCachingProvider" : "FileBasedCachingProvider"); node = webconfig.SelectSingleNode("/configuration/dotnetnuke/outputCaching"); SaveAttribute(node, "defaultProvider", OutputCachingProviderEnabled ? "RedisOutputCachingProvider" : "MemoryOutputCachingProvider"); node = webconfig.SelectSingleNode("/configuration/dotnetnuke/caching/providers/add[@name='RedisCachingProvider']"); SaveAttribute(node, "useCompression", UseCompression.ToString()); SaveAttribute(node, "silentMode", SilentMode.ToString()); SaveAttribute(node, "keyPrefix", KeyPrefix); node = webconfig.SelectSingleNode("/configuration/dotnetnuke/outputCaching/providers/add[@name='RedisOutputCachingProvider']"); SaveAttribute(node, "useCompression", UseCompression.ToString()); SaveAttribute(node, "silentMode", SilentMode.ToString()); SaveAttribute(node, "keyPrefix", KeyPrefix); webconfig.Save(filename); // Clear the cache DotNetNuke.Services.Cache.CachingProvider.Instance().PurgeCache(); }
/// <summary> /// Update RunTimeData custom configuration sections /// Edit an existing key's value /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void UpdateKeyConfigSectionData(string key, string value) { //First get the current environment from the appSettings section var environment = AppConfig.GetAppSettingsValue("Environment"); // Update custom configuration sections - Edit an existing key's value ConfigXmlDocument xmlDoc = new ConfigXmlDocument(); //this dir accesses the \bin runtime location //not the project app.config file //xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); //var projectDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName; //var fileDir = projectDir + @"\AcceptanceTests\DataFiles\"; //var xmlDir = fileDir + "RunTimeData.xml"; //Replace with get xmlDir Method() xmlDoc.Load(xmlDir); //Update the key value //xmlDoc.SelectSingleNode("//Local/add[@key='Test']").Attributes["value"].Value = "New Value6"; var node = "//" + environment + "/add[@key='" + key + "']"; xmlDoc.SelectSingleNode(node).Attributes["value"].Value = value; //xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); xmlDoc.Save(xmlDir); ConfigurationManager.RefreshSection("//" + environment); }
private void ModifyAppInsightsConfigFile(bool removeSettings = false) { var configFile = Server.MapPath("~/ApplicationInsights.config"); if (!File.Exists(configFile)) { File.Copy(Server.MapPath("~/DesktopModules/AppInsights/ApplicationInsights.config"), configFile); } // Load the ApplicationInsights.config file var config = new ConfigXmlDocument(); config.Load(configFile); var key = removeSettings ? string.Empty : ModuleSettings.GetValueOrDefault("InstrumentationKey", string.Empty); const string namespaceUri = "http://schemas.microsoft.com/ApplicationInsights/2013/Settings"; var nsmgr = new XmlNamespaceManager(config.NameTable); nsmgr.AddNamespace("nr", namespaceUri); // Change instrumentation key var keyNode = config.SelectSingleNode("//nr:InstrumentationKey", nsmgr); if (keyNode != null) { keyNode.InnerText = key; } // Save the modifications config.Save(configFile); }
/// <summary> /// Update RunTimeData appSettings sections /// Add a new key /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void AddKeyAppSettings(string key, string value) { //Update custom configuration sections - Add a new key ConfigXmlDocument xmlDoc = new ConfigXmlDocument(); //var projectDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName; //var fileDir = projectDir + @"\AcceptanceTests\DataFiles\"; //var xmlDir = fileDir + "RunTimeData.xml"; //Replace with get xmlDir Method() xmlDoc.Load(xmlDir); // create new node <add key="New Key" value="New Key Value1" /> var node = xmlDoc.CreateElement("add"); //node.SetAttribute("key", "New Key"); //node.SetAttribute("value", "New Key Value1"); node.SetAttribute("key", key); node.SetAttribute("value", value); xmlDoc.SelectSingleNode("//appSettings").AppendChild(node); //xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); xmlDoc.Save(xmlDir); ConfigurationManager.RefreshSection("//appSettings"); }
/// <summary> /// Update RunTimeData custom configuration sections /// Delete an existing key /// </summary> /// <param name="key"></param> public static void DeleteKeyConfigSectionData(string key) { //First get the current environment from the appSettings section var environment = AppConfig.GetAppSettingsValue("Environment"); //Update custom configuration sections - Add a new key ConfigXmlDocument xmlDoc = new ConfigXmlDocument(); //var projectDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName; //var fileDir = projectDir + @"\AcceptanceTests\DataFiles\"; //var xmlDir = fileDir + "RunTimeData.xml"; //Replace with get xmlDir Method() xmlDoc.Load(xmlDir); //XmlNode node = xmlDoc.SelectSingleNode("//Dev/add[@key='Key1']"); var nodeString = "//" + environment + "/add[@key='" + key + "']"; XmlNode node = xmlDoc.SelectSingleNode(nodeString); node.ParentNode.RemoveChild(node); //xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); xmlDoc.Save(xmlDir); ConfigurationManager.RefreshSection("//" + environment); }
private void CreateAddInConfigurationFile(string serviceDirectory) { string addInConfigurationFile; System.Configuration.Configuration config; System.Configuration.ConfigXmlDocument xml = new ConfigXmlDocument( ); XmlNodeList nodes; addInConfigurationFile = Path.Combine(serviceDirectory, "service.config"); config = ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); config.SaveAs(addInConfigurationFile); xml.Load(addInConfigurationFile); nodes = xml.GetElementsByTagName("appSettings"); if (nodes.Count > 0) { nodes [0].ParentNode.RemoveChild(nodes [0]); xml.Save(addInConfigurationFile); } }
protected virtual void Dispose(bool disposing) { if (disposing) { // Save the new .config file config.Save(filename); } }
/// <summary> /// Сохранить конфиг-файл. /// </summary> internal static void SaveXmlConfig() { string dirName = Config.LocalSettingFolder; string fileName = DefaultProgramFullFileName; if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } localParams.Save(fileName); }
private void change_net_settings_Click(object sender, EventArgs e) { //Tomo los valores de ambos cuadros de texto string IPstr = new_IP_txt.Text.Trim(); string PORTstr = new_PORT_txt.Text.Trim(); if (IPstr == "") { string message = "Changes cannot be applied - IP Address empty"; string title = "Error"; MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Close(); return; } if (PORTstr == "") { string message = "Changes cannot be applied - PORT empty"; string title = "Error"; MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Close(); return; } //Editar el App.config ConfigXmlDocument xmlDoc = new ConfigXmlDocument(); xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); foreach (System.Xml.XmlElement el in xmlDoc.DocumentElement) { if (el.Name.Equals("appSettings")) { foreach (System.Xml.XmlNode node in el.ChildNodes) { if (node.Attributes[0].Value == "IP_address") { node.Attributes[1].Value = IPstr; } if (node.Attributes[0].Value == "PORT") { node.Attributes[1].Value = PORTstr; } } } xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); ConfigurationManager.RefreshSection("appSettings"); } MessageBox.Show("Changes applied successfully"); this.Close(); }
/// <summary> /// Сохранить конфиг-файл. /// </summary> internal static void SaveXmlConfig() { string dirName = DefaultFormDirectory; string fileName = DefaultFormFullFileName; if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } programParams.Save(fileName); LocalConfiguration.SaveXmlConfig(); }
/// <summary> /// 创建默认的配置文件 /// </summary> private static void CreateDefaultConfigFile() { // 创建文件,写入默认值 XmlDocument xmlDoc = new ConfigXmlDocument(); // 根节点添加默认参数集 XmlElement elemParams = xmlDoc.CreateElement(RootNodeName); elemParams.AppendChild(xmlDoc.CreateSingleElement(@"PhotoCacheDir", DefaultConfig.PhotoCacheDir)); // 本地照片缓存路径 elemParams.AppendChild(xmlDoc.CreateSingleElement(@"ServerPhotoDir", DefaultConfig.ServerPhotoDir)); // 服务器照片存储路径 elemParams.AppendChild(xmlDoc.CreateSingleElement(@"ThumbSize", DefaultConfig.ThumbSize)); // 照片缩略图尺寸 elemParams.AppendChild(xmlDoc.CreateSingleElement(@"LargeSize", DefaultConfig.LargeSize)); // 照片大图尺寸 elemParams.AppendChild(xmlDoc.CreateSingleElement(@"ThumbShowSize", DefaultConfig.ThumbShowSize)); // 照片缩略图展示尺寸 xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration(@"1.0", @"gb2312", null)); xmlDoc.AppendChild(elemParams); xmlDoc.Save(ConfigFilePath); }
private void buttonSave_Click(object sender, EventArgs e) { string AK = this.textBoxAK.Text; string SK = this.textBoxSK.Text; string defaultbucket = this.comboBoxBuckets.SelectedItem.ToString(); ConfigXmlDocument xmlDoc = new ConfigXmlDocument(); string currentPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; // App.config所在路径 string configPath = currentPath.Substring(0, currentPath.Length - 10) + "App.config"; xmlDoc.Load(configPath); XmlElement xmlElementAK = (XmlElement)xmlDoc.SelectSingleNode("//appSettings/add[1]"); XmlElement xmlElementSK = (XmlElement)xmlDoc.SelectSingleNode("//appSettings/add[2]"); XmlElement xmlElementDefaultBucket = (XmlElement)xmlDoc.SelectSingleNode("//appSettings/add[last()]"); xmlElementAK.SetAttribute("value", AK); xmlElementSK.SetAttribute("value", SK); xmlElementDefaultBucket.SetAttribute("value", defaultbucket); xmlDoc.Save(configPath); }
/// <summary> /// プロパティを保存する処理 /// </summary> private void SaveProperties() { try { FileInfo fi = new System.IO.FileInfo(GetLocalConfigFilePath()); if (fi.Exists != true) { if (fi.Directory.Exists != true) { fi.Directory.Create(); } } ConfigXmlDocument cdoc = new ConfigXmlDocument(); var cfg = cdoc.CreateElement("configuration"); var apps = cdoc.CreateElement("settings"); Func <string, string, bool> addItem = (key, val) => { var node = cdoc.CreateElement("add"); var attrK = cdoc.CreateAttribute("key"); attrK.InnerText = key; var attrV = cdoc.CreateAttribute("value"); attrV.InnerText = string.IsNullOrWhiteSpace(val) ? string.Empty : val; node.Attributes.Append(attrK); node.Attributes.Append(attrV); apps.AppendChild(node); return(true); }; addItem("LoginCheck", this.ライセンス情報記憶.ToString()); addItem("TextUr", Utility.Encrypt(this.ユーザーID)); addItem("TextLr", Utility.Encrypt(this.パスワード)); cdoc.AppendChild(cfg); cfg.AppendChild(apps); cdoc.Save(fi.FullName); } catch (Exception) { } finally { } }
private void saveConfig(string key, string value) { ConfigXmlDocument doc = new ConfigXmlDocument(); string fileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; doc.Load(fileName); XmlNodeList nodes = doc.GetElementsByTagName("add"); for (int i = 0; i < nodes.Count; i++) { XmlAttribute att = nodes[i].Attributes["key"]; if (att.Value == key) { att = nodes[i].Attributes["value"]; att.Value = value; break; } } doc.Save(fileName); ConfigurationManager.RefreshSection("appSettings"); }
private bool ChangeConfig(ConfigXmlDocument doc) { foreach (XmlNode childNode in doc.SelectSingleNode("//connectionStrings").ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { XmlElement xmlElement = (XmlElement)childNode; string str = Utility.EnBase64(this.rtbConnectString.Text); xmlElement.SetAttribute("connectionString", str); } } try { doc.Save(this.webConfigPath); } catch (Exception ex) { int num = (int)MessageBox.Show(string.Format("更改配置失败:{0}", (object)ex)); return(false); } return(true); }
private string createId(int increase = 1) { ConfigXmlDocument doc = new ConfigXmlDocument(); doc.Load(ConstInfo.TicketID_Path); var date = doc.SelectSingleNode("TicketID/date").InnerText; string ticketId = ""; if (date != currentDate) { var dateNode = doc.SelectSingleNode("TicketID/date"); dateNode.InnerText = currentDate; ticketId = "0000"; } else { var id = doc.SelectSingleNode("TicketID/id").InnerText; var currentID = Convert.ToInt32(id) + increase; ticketId = currentID.ToString().PadLeft(4, '0'); } doc.SelectSingleNode("TicketID/id").InnerText = ticketId; doc.Save(ConstInfo.TicketID_Path); return(currentDate + "-" + ticketId); }
public static void Install(String machineConfigPath, String patchFileName) { ConfigXmlDocument machineConfig = new ConfigXmlDocument(); machineConfig.PreserveWhitespace = true; machineConfig.Load(machineConfigPath); XmlDocument patch = new XmlDocument(); patch.PreserveWhitespace = true; patch.Load(patchFileName); // Remove original <result type=""> node, replace by // comment. Only one <result> node allowed in machine.config. String resultPath = "/configuration/system.web/browserCaps/result"; String browserCapsPath = "/configuration/system.web/browserCaps"; XmlNode resultNode = machineConfig.SelectSingleNode(resultPath); XmlNode browserCapsNode = machineConfig.SelectSingleNode(browserCapsPath); XmlNode patchResultNode = patch.SelectSingleNode(resultPath); XmlNode patchBrowserCapsNode = patch.SelectSingleNode(browserCapsPath); XmlNode patchResultNodeClone = machineConfig.ImportNode(patchResultNode, true); patchBrowserCapsNode.RemoveChild(patchResultNode); ArrayList browserCapsLeadingWhitespace = new ArrayList(); foreach (XmlNode child in browserCapsNode.ChildNodes) { if (child.NodeType == XmlNodeType.Whitespace) { browserCapsLeadingWhitespace.Add(child); } else { break; } } StringBuilder commentText = new StringBuilder(); if (resultNode != null) { XmlTextWriter commentWriter = new XmlTextWriter(new StringWriter(commentText)); resultNode.WriteTo(commentWriter); browserCapsNode.RemoveChild(resultNode); } MergePrepend(machineConfig, patch, "/configuration/system.web/httpModules"); MergePrepend(machineConfig, patch, "/configuration/configSections/sectionGroup[@name='system.web']"); MergePrepend(machineConfig, patch, "/configuration/system.web/compilation/assemblies"); Merge(machineConfig, patch, "/configuration/system.web/browserCaps"); Insert(machineConfig, patch, "/configuration/system.web", "mobileControls"); Insert(machineConfig, patch, "/configuration/system.web", "deviceFilters"); // Prepend these nodes (in reverse order) so that they occur // before any other children. if (resultNode != null) { PrependComment(machineConfig, browserCapsNode, _removedEltEndComment); PrependComment(machineConfig, browserCapsNode, commentText.ToString()); PrependComment(machineConfig, browserCapsNode, _removedEltBeginComment); } PrependComment(machineConfig, browserCapsNode, _endComment); browserCapsNode.PrependChild(patchResultNodeClone); // Clone formatting for inserted node. foreach (XmlNode child in browserCapsLeadingWhitespace) { browserCapsNode.PrependChild(child.CloneNode(false /* deep */)); } PrependComment(machineConfig, browserCapsNode, _beginComment); // Clone formatting for uninstall. foreach (XmlNode child in browserCapsLeadingWhitespace) { browserCapsNode.PrependChild(child.CloneNode(false /* deep */)); browserCapsNode.RemoveChild(child); } RemoveExtraWhitespace(machineConfig); StreamWriter s = new StreamWriter(machineConfigPath); XmlIndentAttributeTextWriter writer = new XmlIndentAttributeTextWriter(s); writer.Formatting = Formatting.Indented; writer.Indentation = 4; machineConfig.Save(writer); writer.Flush(); writer.Close(); }