/// <summary> /// 从github获取配置信息,以字典形式返回 /// </summary> /// <returns></returns> public override Dictionary <string, object> GetConfigurations() { var confDic = new Dictionary <string, object>(); HttpClient client = new HttpClient(); client.MaxResponseContentBufferSize = 256000; //string url = "https://api.github.com/repos/factminr/webapi/contents/Factminr.WebApi/Factminr.WebApi/Web.config"; string url = string.Format("{0}/{1}/{2}/contents/{3}", ConfigBaseUrl, ConfigRepoOwner, ConfigRepo, ConfigPath.TrimStart('/')).TrimEnd('/', ' '); if (!string.IsNullOrEmpty(ConfigRepoBranch) && ConfigRepoBranch.ToLower() != "master") { url += string.Format("?ref={0}", ConfigRepoBranch); } HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Add("User-Agent", "Anything"); HttpResponseMessage response = client.SendAsync(request).Result; if (response.StatusCode != HttpStatusCode.OK) { return(confDic); } var responseStr = response.Content.ReadAsStringAsync().Result; confDic = ParseGithubResponse(responseStr); return(confDic); }
private void PutDeviceFile(bool running) { string statusPath = ConfigPath.GetConfigFilePath("status"); if (!Directory.Exists(statusPath)) { Directory.CreateDirectory(statusPath); } string relFileName = string.Format("status\\@{0}-running", this.deviceKey); string fileName = ConfigPath.GetConfigFilePath(relFileName); if (running) { try { using (File.Create(fileName)) { } } catch (Exception) { } } else { try { File.Delete(fileName); } catch (Exception) { } } }
public Settings() { // "Agent.Settings" string settingFileName = ConfigPath.GetConfigFilePath("mainvs.settings"); if (!File.Exists(settingFileName)) { return; } this.IsCAS = false; string cfg2FileName = ConfigPath.GetConfigFilePath("dsm2.cfg"); if (File.Exists(cfg2FileName)) { this.IsCAS = true; } doc.Load(settingFileName); var application = doc.SelectNodes("//application"); XmlNode appNode = application[0]; this.ApplicationName = this.GetAttribute(appNode, "title", "MainVision"); this.StationName = this.GetAttribute(appNode, "station", "????自动站"); this.Status = this.GetAttribute(appNode, "status", "试运行"); this.StationId = this.GetAttribute(appNode, "stationId", "00000000001"); this.Pos = this.GetAttribute(appNode, "pos", "未知GPS信息"); this.UserComp = this.GetAttribute(appNode, "usercomp", "未知用户单位"); this.AdminComp = this.GetAttribute(appNode, "admincomp", "未知运营单位"); this.BuildComp = this.GetAttribute(appNode, "buildcomp", "未知承建单位"); }
/// <summary> /// Set the target instance values reading from the passed configuration node. /// </summary> /// <typeparam name="T">Target Instance type</typeparam> /// <param name="parent">Configuration node instance</param> /// <param name="target">Target Type instance</param> /// <returns>Updated Target Type instance</returns> public static T Process <T>(AbstractConfigNode parent) { Preconditions.CheckArgument(parent); Type type = typeof(T); T target = default(T); ConfigPath path = (ConfigPath)Attribute.GetCustomAttribute(type, typeof(ConfigPath)); if (path != null) { AbstractConfigNode node = null; if (!String.IsNullOrWhiteSpace(path.Path)) { node = parent.Find(path.Path); } if ((!Conditions.NotNull(node) || node.GetType() != typeof(ConfigPathNode)) && path.Required) { throw new AnnotationProcessorException(String.Format("Annotation not found: [path={0}][type={1}]", path.Path, type.FullName)); } if (Conditions.NotNull(node) && node.GetType() == typeof(ConfigPathNode)) { target = CreateInstance <T>(type, (ConfigPathNode)node); } } return(target); }
private void SetWatcher() { if (ConfigPath == null) { ConfigDir = ThereIsConstants.Path.Here; ConfigPath = ConfigDir + Config_File_Name; } if (!File.Exists(ConfigPath.GetValue())) { var _f = File.Create(ConfigPath.GetValue()); _f.Dispose(); } File.WriteAllText(ConfigPath.GetValue(), DEFAULT_CONFIG_TEXT); #if __LINUX__ WatcherWorker ??= new Trigger(); WatcherWorker.Tick += Watcher_Worker; WatcherWorker.SetInterval(WORKER_INTERVAL); WatcherWorker.Start(); #elif __WINDOWS__ // create a new worker and start it up. // ReSharper disable once RedundantArgumentDefaultValue WatcherWorker = new Worker(Watcher_Worker, DEFAULT_Z_BASE); WatcherWorker.Start(); #endif }
private void InitMenuStatus() { string statusPath = ConfigPath.GetConfigFilePath("status"); if (Directory.Exists(statusPath)) { string[] filePaths = Directory.GetFiles(statusPath, @"@*"); var deviceKeys = filePaths.Select((string path) => { string fileName = Path.GetFileName(path); return(fileName.ToLower().Substring(1)); }); var menus = SettingsToolStripMenuItem.DropDownItems; foreach (ToolStripMenuItem m in menus) { string tag = m.Tag as string; if (string.IsNullOrEmpty(tag)) { continue; } m.Checked = false; tag = tag.ToLower(); foreach (var deviceKey in deviceKeys) { if (deviceKey == tag) { m.Checked = true; } } } } }
private void ExecSample24HourMeasure() { // 首先清除原有进程 try { Process[] processes = Process.GetProcesses(); foreach (Process process in processes) { if (process.ProcessName.ToLower() == "gv32") { process.Kill(); } } } catch (Exception e1) { string msg = string.Format("Kill GammaVision进程失败, 错误:{0}", e1.Message); RecordManager.DoSystemEventRecord(this, msg, RecordType.Event); return; } // 启动新的JOB文件 var bat = ConfigPath.GetConfigFilePath("devices/Scada.HPGE/0.9/script/SampleMeasure24.bat"); using (Process p = Process.Start(bat)) { } }
internal bool GetThreshold(string polId, out string th1, out string th2) { th1 = ""; th2 = ""; string settingFileName = ConfigPath.GetConfigFilePath("agent.settings"); if (File.Exists(settingFileName)) { doc.Load(settingFileName); } // Data Center var polNotes = doc.SelectNodes("//polId"); foreach (XmlNode polIdNode in polNotes) { var nameAttr = polIdNode.Attributes.GetNamedItem("name"); if (nameAttr != null) { string name = nameAttr.Value; if (name == polId) { th1 = polIdNode.Attributes.GetNamedItem("v1").Value; th2 = polIdNode.Attributes.GetNamedItem("v2").Value; return(true); } } } return(false); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Enabled != null) { hashCode = hashCode * 59 + Enabled.GetHashCode(); } if (ConfigPath != null) { hashCode = hashCode * 59 + ConfigPath.GetHashCode(); } if (FallbackPaths != null) { hashCode = hashCode * 59 + FallbackPaths.GetHashCode(); } if (ConfigCollectionInheritancePropertyNames != null) { hashCode = hashCode * 59 + ConfigCollectionInheritancePropertyNames.GetHashCode(); } return(hashCode); } }
/// <summary> /// Returns true if OrgApacheSlingCaconfigResourceImplDefDefaultConfigurationResourProperties instances are equal /// </summary> /// <param name="other">Instance of OrgApacheSlingCaconfigResourceImplDefDefaultConfigurationResourProperties to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrgApacheSlingCaconfigResourceImplDefDefaultConfigurationResourProperties other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Enabled == other.Enabled || Enabled != null && Enabled.Equals(other.Enabled) ) && ( ConfigPath == other.ConfigPath || ConfigPath != null && ConfigPath.Equals(other.ConfigPath) ) && ( FallbackPaths == other.FallbackPaths || FallbackPaths != null && FallbackPaths.Equals(other.FallbackPaths) ) && ( ConfigCollectionInheritancePropertyNames == other.ConfigCollectionInheritancePropertyNames || ConfigCollectionInheritancePropertyNames != null && ConfigCollectionInheritancePropertyNames.Equals(other.ConfigCollectionInheritancePropertyNames) )); }
/// <summary> /// Set the target instance values reading from the passed configuration node. /// </summary> /// <typeparam name="T">Target Instance type</typeparam> /// <param name="parent">Configuration node instance</param> /// <param name="target">Target Type instance</param> /// <param name="valuePaths">List of Value paths used</param> /// <returns>Updated Target Type instance</returns> public static T Process <T>(AbstractConfigNode parent, T target, out List <string> valuePaths) { Preconditions.CheckArgument(parent); Preconditions.CheckArgument(target); valuePaths = null; Type type = target.GetType(); ConfigPath path = (ConfigPath)Attribute.GetCustomAttribute(type, typeof(ConfigPath)); if (path != null) { AbstractConfigNode node = null; if (!String.IsNullOrWhiteSpace(path.Path)) { node = parent.Find(path.Path); } if ((!Conditions.NotNull(node) || node.GetType() != typeof(ConfigPathNode)) && path.Required) { throw new AnnotationProcessorException(String.Format("Annotation not found: [path={0}][type={1}]", path.Path, type.FullName)); } if (node != null && node.GetType() == typeof(ConfigPathNode)) { valuePaths = new List <string>(); target = ReadValues((ConfigPathNode)node, target, valuePaths); CallMethodInvokes((ConfigPathNode)node, target); } } return(target); }
private static string GetScadaSqlFile() { Type type = typeof(Program); string fn = type.Assembly.Location; string sqlFileName = ConfigPath.GetConfigFilePath("scada.sql"); return(sqlFileName); }
private void ExecSample24HourMeasure() { var bat = ConfigPath.GetConfigFilePath("devices/Scada.HPGE/0.9/script/SampleMeasure24.bat"); using (Process p = Process.Start(bat)) { } }
private bool RecoverCheck() { string statusPath = ConfigPath.GetConfigFilePath("status"); if (!Directory.Exists(statusPath)) { return(false); } string runningDevicesFile = Path.Combine(statusPath, "running.devices"); if (!File.Exists(runningDevicesFile)) { return(false); } try { using (FileStream fs = File.Open(runningDevicesFile, FileMode.Open)) { // Recover this.CheckAllDevices(false); long len = fs.Length; byte[] bytes = new byte[len]; fs.Read(bytes, 0, (int)len); StringReader sr = new StringReader(Encoding.ASCII.GetString(bytes)); string deviceKeyLine = sr.ReadLine(); while (deviceKeyLine != null) { string deviceKey = deviceKeyLine.ToLower().Trim(); if (!string.IsNullOrEmpty(deviceKey)) { foreach (ListViewItem item in this.deviceListView.Items) { string itemTextLower = item.Text.ToLower(); if (itemTextLower == deviceKey) { item.Checked = true; } } } deviceKeyLine = sr.ReadLine(); } return(true); } } catch (Exception) { } return(false); }
public override int GetHashCode() { unchecked { var hashCode = LeaseName.GetHashCode(); hashCode = (hashCode * 397) ^ ConfigPath.GetHashCode(); hashCode = (hashCode * 397) ^ ClientName.GetHashCode(); return(hashCode); } }
/// <summary> /// Get the Path attribute for this type. /// </summary> /// <param name="type">Type to get path for</param> /// <returns>Path attribute value</returns> public static string GetAnnotationPath(Type type) { ConfigPath path = (ConfigPath)Attribute.GetCustomAttribute(type, typeof(ConfigPath)); if (path != null) { return(path.Path); } return(null); }
private void LoadConfig() { string fileName = "dsm.cfg"; if (Settings.Instance.IsCAS) { fileName = "dsm2.cfg"; } string filePath = ConfigPath.GetConfigFilePath(fileName); Config.Instance().Load(filePath); }
private bool CheckDeviceFile() { string statusPath = ConfigPath.GetConfigFilePath("status"); if (!Directory.Exists(statusPath)) { Directory.CreateDirectory(statusPath); } string relFileName = string.Format("status\\@{0}-running", this.DeviceKey); string fileName = ConfigPath.GetConfigFilePath(relFileName); return(File.Exists(fileName)); }
public PluginConfigurator() { ConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PluginConfig.xml"); if (string.IsNullOrEmpty(ConfigPath)) { throw new Exception("无法找到组件配置信息。"); } if (!ConfigPath.Contains(":")) { ConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigPath); } }
private void BringDataUploadUI() { string dataUploadExe = "Scada.Data.Client.exe"; if (!File.Exists(ConfigPath.GetConfigFilePath("agent.http.settings"))) { dataUploadExe = "Scada.DataCenterAgent.exe"; } Process[] ps = Process.GetProcessesByName(dataUploadExe); if (ps == null || ps.Length == 0) { this.OpenProcessByName(dataUploadExe); } }
public static void Main(string[] args) { // Get the environment var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); // Temporarily use the appsettings.json file to get the log directory var bconfig = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) .AddJsonFile($"appsettings.{environment}.json") .Build(); // Now load the paths object and bind to a new configPath object var configPath = new ConfigPath(); bconfig.GetSection("Paths").Bind(configPath); // Set up the logger now that we have the log path string logPath = configPath.LogPath; Directory.CreateDirectory(logPath); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Debug() .WriteTo.File(logPath, rollingInterval: RollingInterval.Day, flushToDiskInterval: TimeSpan.FromSeconds(1), shared: true) .CreateLogger(); try { Log.Information("Starting web host"); BuildWebHost(args).Run(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); } finally { Log.CloseAndFlush(); } }
public static void SetDeviceConfigPath(string deviceName, bool hide) { string deviceConfigPath = ConfigPath.GetConfigFilePath(DevicePath); string devicePath1 = string.Format("{0}\\{1}", deviceConfigPath, deviceName); string devicePath2 = string.Format("{0}\\!{1}", deviceConfigPath, deviceName); if (hide && Directory.Exists(devicePath1)) { Directory.Move(devicePath1, devicePath2); // Rename(devicePath1, devicePath2); } else if (!hide && Directory.Exists(devicePath2)) { Directory.Move(devicePath2, devicePath1); } }
private void bbiClone_ItemClick(object sender, ItemClickEventArgs e) { GridView gv = this.gridView; if (gv.SelectedRowsCount == 0) { return; } int[] selectedRows = gv.GetSelectedRows( ); for (int i = 0; i < selectedRows.Length; i++) { ConfigPath row = gv.GetRow(selectedRows[i]) as ConfigPath; ConfigPath clone = new ConfigPath(row); this.cpColl.List.Add(clone); } }
private static AbstractDungeonStructure BuildFromConfigNode(ConfigNode dungeonStructureBaseNode, ConfigNode configRoot) { ISet <String> nestedDungeonNameCollector = new HashSet <string>(); Dictionary <string, AbstractDungeonStructure> nestedDungeons = new Dictionary <string, AbstractDungeonStructure>(); var firstElement = ReadElement(dungeonStructureBaseNode.Query(START_NODE).AsNode(), nestedDungeonNameCollector); BranchDataWrapper branchData = ReadBranchData(dungeonStructureBaseNode); if (branchData != null) { nestedDungeonNameCollector.UnionWith(branchData.BranchPrototypeNames); } var inlineDungeons = dungeonStructureBaseNode.TryQuery(INLINE_NESTED); if (inlineDungeons.IsPresent) { var inlineNode = inlineDungeons.Get().AsNode(); foreach (var name in inlineNode.GetKeys()) { nestedDungeons.Add(name, BuildFromConfigNode(inlineNode.Query(name).AsNode(), configRoot)); } } foreach (var nestedDungeonPath in nestedDungeonNameCollector) { if (!nestedDungeons.ContainsKey(nestedDungeonPath)) { var nestedDungeonConfigPath = new ConfigPath(nestedDungeonPath.Split('.')); nestedDungeons.Add(nestedDungeonPath, BuildFromConfig(nestedDungeonConfigPath, configRoot)); } } var structureMetaData = ReadStructureMetaData(dungeonStructureBaseNode); AddParentTagsRecursive(firstElement, structureMetaData.GlobalNodePropertyAndTagHolder.GetTags()); var abstractDungeonStructure = AbstractDungeonStructure.Builder .SetMetaData(structureMetaData) .SetEmbeddedDungeons(nestedDungeons) .SetBranchData(branchData) .SetStartElement(firstElement) .Build(); return(abstractDungeonStructure); }
internal void SetThreshold(string polId, string th1, string th2) { string settingFileName = ConfigPath.GetConfigFilePath("agent.settings"); if (File.Exists(settingFileName)) { doc.Load(settingFileName); } // Data Center var polNotes = doc.SelectNodes("//polId"); XmlNode thePolIdNode = null; foreach (XmlNode polIdNode in polNotes) { var nameAttr = polIdNode.Attributes.GetNamedItem("name"); if (nameAttr != null) { string name = nameAttr.Value; if (name == polId) { thePolIdNode = polIdNode; XmlAttribute v1Attr = (XmlAttribute)thePolIdNode.Attributes.GetNamedItem("v1"); v1Attr.Value = th1; XmlAttribute v2Attr = (XmlAttribute)thePolIdNode.Attributes.GetNamedItem("v2"); v2Attr.Value = th2; doc.Save(settingFileName); return; } } } if (thePolIdNode == null) { var thresholdNode = polNotes[0].ParentNode; thePolIdNode = doc.CreateElement("polId"); thresholdNode.AppendChild(thePolIdNode); this.AddAttribute(doc, thePolIdNode, "name", polId); this.AddAttribute(doc, thePolIdNode, "v1", th1); this.AddAttribute(doc, thePolIdNode, "v2", th2); doc.Save(settingFileName); } }
private void gridView_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e) { GridView view = sender as GridView; ConfigPath row = (ConfigPath)e.Row; row.Normalize( ); if (!row.IsValid) { e.Valid = false; { GridColumn col = view.Columns[ConfigPath.PATHDIR_DISPLAYNAME]; view.SetColumnError(col, "Invalid conbination [pathdir] or [basedir]"); } //{ // GridColumn col = view.Columns[ ConfigPath.BASEDIR_DISPLAYNAME ]; // view.SetColumnError( col, "Invalid combination [pathdir] or [basedir]" ); //} } }
public static void InitLogger() { string url = ConfigPath.ConvertToUrl(Application.streamingAssetsPath + "/" + ConfigPath.CLIENT_LOGGER_CONFIG); Console.WriteLine("Load client logger config: " + url); WWW www = new WWW(url); while (!www.isDone) { } if (!string.IsNullOrEmpty(www.error)) { Debug.LogError("Error loading logger config from: " + url + " Error: " + www.error); } else { LoggerProvider.LoadConfiguration(new MemoryStream(www.bytes)); } }
private void HandleCheckedChanged(string deviceKey, bool check) { string relFileName = string.Format("status\\@{0}", deviceKey); string fileName = ConfigPath.GetConfigFilePath(relFileName); if (check) { if (!File.Exists(fileName)) { using (File.Create(fileName)) { } } } else { if (File.Exists(fileName)) { File.Delete(fileName); } } }
private void SetWatcher() { if (ConfigPath == null) { ConfigDir = Directory.GetCurrentDirectory(); ConfigPath = ConfigDir + ThereIsConstants.Path.DoubleSlash + Config_File_Name; } if (!File.Exists(ConfigPath.GetValue())) { var _f = File.Create(ConfigPath.GetValue()); _f.Dispose(); } File.WriteAllText(ConfigPath.GetValue(), DEFAULT_CONFIG_TEXT); if (IsWindows) { // create a new worker and start it up. // ReSharper disable once RedundantArgumentDefaultValue WatcherWorker = new Worker(Watcher_Worker, DEFAULT_Z_BASE); WatcherWorker.Start(); } }
// to test; internal void AddNewIpAddress(string wireIp, string wirePort, string wirelessIp, string wirelessPort, bool country) { string settingFileName = ConfigPath.GetConfigFilePath(AgentXml); if (File.Exists(settingFileName)) { doc.Load(settingFileName); } // Data Center var dsNotes = doc.SelectNodes("//datacenter2"); var ds = dsNotes[0].ParentNode; XmlNode newDataCenterNode = doc.CreateElement("datacenter2"); ds.AppendChild(newDataCenterNode); this.AddAttribute(doc, newDataCenterNode, "ip", wireIp); this.AddAttribute(doc, newDataCenterNode, "port", wirePort); this.AddAttribute(doc, newDataCenterNode, "wirelessip", wirelessIp); this.AddAttribute(doc, newDataCenterNode, "wirelessport", wirelessPort); this.AddAttribute(doc, newDataCenterNode, "type", "3"); doc.Save(settingFileName); }
internal static string FindWebConfig (string path, out bool inAnotherApp) { inAnotherApp = false; if (String.IsNullOrEmpty (path)) return path; if (HostingEnvironment.VirtualPathProvider != null) { if (HostingEnvironment.VirtualPathProvider.DirectoryExists (path)) path = VirtualPathUtility.AppendTrailingSlash (path); } string rootPath = HttpRuntime.AppDomainAppVirtualPath; ConfigPath curPath; curPath = configPaths [path] as ConfigPath; if (curPath != null) { inAnotherApp = curPath.InAnotherApp; return curPath.Path; } HttpContext ctx = HttpContext.Current; HttpRequest req = ctx != null ? ctx.Request : null; string physPath = req != null ? VirtualPathUtility.AppendTrailingSlash (MapPath (req, path)) : null; string appDomainPath = HttpRuntime.AppDomainAppPath; if (physPath != null && appDomainPath != null && !physPath.StartsWith (appDomainPath, StringComparison.Ordinal)) inAnotherApp = true; string dir; if (inAnotherApp || path [path.Length - 1] == '/') dir = path; else { dir = VirtualPathUtility.GetDirectory (path, false); if (dir == null) return path; } curPath = configPaths [dir] as ConfigPath; if (curPath != null) { inAnotherApp = curPath.InAnotherApp; return curPath.Path; } if (req == null) return path; curPath = new ConfigPath (path, inAnotherApp); while (String.Compare (curPath.Path, rootPath, StringComparison.Ordinal) != 0) { physPath = MapPath (req, curPath.Path); if (physPath == null) { curPath.Path = rootPath; break; } if (WebConfigurationHost.GetWebConfigFileName (physPath) != null) break; curPath.Path = GetParentDir (rootPath, curPath.Path); if (curPath.Path == null || curPath.Path == "~") { curPath.Path = rootPath; break; } } if (String.Compare (curPath.Path, path, StringComparison.Ordinal) != 0) configPaths [path] = curPath; else configPaths [dir] = curPath; return curPath.Path; }