public override bool Execute() { BindingRedirectResolution.Enable(); SharpGenLogger = new Logger(new MSBuildSharpGenLogger(Log), null); var config = new ConfigFile { Files = ConfigFiles.Select(file => file.ItemSpec).ToList(), Id = "SharpGen-MSBuild" }; try { config = LoadConfig(config); if (SharpGenLogger.HasErrors) { return(false); } return(Execute(config)); } catch (CodeGenFailedException ex) { Log.LogError(ex.Message); return(false); } }
public T?Build() { string[] switchNames = typeof(T).GetProperties() .Where(x => x.PropertyType == typeof(bool)) .Select(x => x.Name) .ToArray(); string[] args = (Args ?? Array.Empty <string>()) .Select(x => switchNames.Contains(x, StringComparer.OrdinalIgnoreCase) ? x + "=true" : x) .ToArray(); if (EnableHelp) { var helpSignals = new[] { "?", "/?", "-?", "--?", "help", "-help", "--help" }; args = args.Select(x => helpSignals.Any(y => y == x) ? "help=true" : x).ToArray(); } string?environment = null; string?secretId = null; T option; while (true) { IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .Action(x => ConfigFiles?.ForEach(y => x.AddJsonFile(y))) .Func(x => GetEnvironmentConfig(environment) switch { Stream v => x.AddJsonStream(v), _ => x })
public T?Build() { if (Args == null || Args.Length == 0) { return(null); } string[] switchNames = typeof(T).GetProperties() .Where(x => x.PropertyType == typeof(bool)) .Select(x => x.Name) .ToArray(); string[] args = (Args ?? Array.Empty <string>()) .Select(x => switchNames.Contains(x, StringComparer.OrdinalIgnoreCase) ? x + "=true" : x) .ToArray(); string?environment = null; string?secretId = null; T option; while (true) { IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .Action(x => ConfigFiles?.ForEach(y => x.AddJsonFile(y))) .Func(x => GetEnvironmentConfig(environment) switch { Stream v => x.AddJsonStream(v), _ => x })
public void Validate() { var files = new ConfigFiles(this.configSet, this.serverRole); foreach (var fileToProcess in files.ConfigChanges) { var configFileNameTrimmed = fileToProcess.ConfigFileName.TrimEnd(ExampleFileExtension) .TrimEnd(DisabledFileExtension); var configPath = $"{webRoot}{fileToProcess.FilePath}{configFileNameTrimmed}"; try { if (fileToProcess.SearchProviderUsed == SearchProvider.All || fileToProcess.SearchProviderUsed == searchProvider) { ValidateFile(fileToProcess.ConfigSetting, configPath); } else { ValidateDisabledFile(configPath); } } catch (Exception e) { Log($"Failed to check [{configPath}], Exception [{e}]"); } } }
public static void Update_Hurricane_Details(bool isHurricaneSeason) { string configFilePaths = "C:/Users/tigershark2020/Documents/Credentials/Events/filePaths.json"; bool exists = File.Exists(configFilePaths); string json = null; try { json = System.IO.File.ReadAllText(configFilePaths, System.Text.Encoding.UTF8); } catch (Exception json_read) { Console.WriteLine(json_read.Message); } string[] basinArray = { "at", "ep", "cp" }; if (json != null) // Check That JSON String Read Above From File Contains Data { ConfigFiles jsonConfigPaths = new ConfigFiles(); jsonConfigPaths = JsonConvert.DeserializeObject <ConfigFiles>(json); List <Coordinates> shorelineCoordinatesList = Get_US_Shoreline_Coordinates_List(jsonConfigPaths); foreach (string basin in basinArray) { if (basin.Equals("ep")) { Process_NHC_Feed(jsonConfigPaths, basin, shorelineCoordinatesList); string event_list = "NHCAdvisory"; Generate_Google_Maps_Marker_File(event_list); } } } }
public override bool Execute() { PrepareExecute(); ExtensibilityDriver.Instance.LoadExtensions(SharpGenLogger, ExtensionAssemblies.Select(x => x.ItemSpec).ToArray()); var config = new ConfigFile { Files = ConfigFiles.Select(file => file.ItemSpec).ToList(), Id = "SharpGen-MSBuild" }; try { config = LoadConfig(config); return(!SharpGenLogger.HasErrors && Execute(config)); } catch (CodeGenFailedException ex) { SharpGenLogger.Fatal("Internal SharpGen exception", ex); return(false); } }
internal static void Postfix(ConfigFile __instance, BepInPlugin ownerMetadata) { CachedConfigFile cached = new(__instance, ownerMetadata); ConfigFiles.Add(cached); ConfigFileCreated?.Invoke(cached); }
public override bool Execute() { var debug = string.Equals("true", DebugTask?.Trim(), StringComparison.OrdinalIgnoreCase); var promptAuth = string.Equals("true", AlwaysPromptInteractiveAuth?.Trim(), StringComparison.OrdinalIgnoreCase); Config.Log.Information = x => Log.LogWarning(x); Config.Log.Error = (ex, m) => Log.LogError("Error while processing secrets from keyvault. " + Environment.NewLine + ex); try { if (debug && !Debugger.IsAttached) { Debugger.Launch(); Debugger.Break(); } if (promptAuth) { Log.LogWarning("KeyVaultBuildTask: Set to always prompting for auth information."); } var service = SecretServiceBuilder.Create() .AlwaysPromptInteractiveAuth(promptAuth) .WithDirectory(DirectoryId) .WithServicePrincipal(ClientId, Secret); if (!string.IsNullOrEmpty(VaultAliases)) { foreach (var alias in VaultAliases?.Trim().Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { var pair = alias.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); service.WithVaultAlias(pair.First(), pair.Last()); Log.LogWarning("Overriding vault '{0}' with '{1}'", pair.First(), pair.Last()); } } var transformKey = new TransformKeys(service.Build()); var files = ConfigFiles.Select(file => file.GetMetadata("Fullpath")).ToArray(); Parallel.ForEach(files, file => { transformKey.SaveAsFile(file); }); } catch (Exception ex) { TokenCache.DefaultShared.Clear(); Config.Log.Error(ex, "Error occured processing secrets. "); if (debug) { Debugger.Break(); } return(false); } return(true); }
public static void Add_Event_Notifications(ConfigFiles jsonConfigPaths, List <Event_Notification> eventNotificationList) { MySql.Data.MySqlClient.MySqlConnection conn; conn = new MySql.Data.MySqlClient.MySqlConnection(); MySqlConnectionStringBuilder conn_string_builder = new MySqlConnectionStringBuilder(); string json = System.IO.File.ReadAllText(jsonConfigPaths.mysqlCredentialsInsert_JsonFile); conn_string_builder = JsonConvert.DeserializeObject <MySqlConnectionStringBuilder>(json); conn = new MySqlConnection(conn_string_builder.ToString()); try { conn.Open(); } catch (Exception erro) { Console.WriteLine(erro); } foreach (Event_Notification eventNotification in eventNotificationList) { try { MySqlCommand cmd = conn.CreateCommand(); cmd.Connection = conn; cmd.CommandText = "INSERT INTO `geo_data`.`geo_events` (`geo_event_agency`,`geo_event_title`,`geo_event_url`,`geo_event_starttime`,`geo_event_category`,`geo_event_type`,`geo_event_ident`,`geo_event_location_latitude`,`geo_event_location_longitude`,`geo_event_notify`) VALUES (@event_notification_agency,@event_notification_title,@event_notification_url,FROM_UNIXTIME(@event_notification_datetime),@event_notification_category,@event_notification_type,@event_notification_ident,@event_notification_latitude,@event_notification_longitude,1);"; // cmd.Prepare(); cmd.Parameters.AddWithValue("@event_notification_agency", eventNotification.eventNotification_Agency); cmd.Parameters.AddWithValue("@event_notification_title", eventNotification.eventNotification_Title); cmd.Parameters.AddWithValue("@event_notification_url", eventNotification.eventNotification_URL); cmd.Parameters.AddWithValue("@event_notification_datetime", eventNotification.eventNotification_DatetimeEpoch); cmd.Parameters.AddWithValue("@event_notification_category", eventNotification.eventNotification_Category); cmd.Parameters.AddWithValue("@event_notification_type", eventNotification.eventNotification_Type); cmd.Parameters.AddWithValue("@event_notification_ident", eventNotification.eventNotification_UniqueID); cmd.Parameters.AddWithValue("@event_notification_latitude", eventNotification.eventNotification_Latitude); cmd.Parameters.AddWithValue("@event_notification_longitude", eventNotification.eventNotification_Longitude); cmd.ExecuteNonQuery(); } catch (MySqlException error_message) { int errorcode = error_message.Number; Console.WriteLine(errorcode + "\t" + error_message.Message); } catch (Exception e) { Console.WriteLine(e); } } conn.Close(); }
/// <summary> /// Registers a config file /// </summary> /// <param name="ConfigObject">Config object to register</param> public static void RegisterConfigFile(IConfig ConfigObject) { Contract.Requires <ArgumentNullException>(ConfigObject != null, "ConfigObject"); if (ConfigFiles.ContainsKey(ConfigObject.Name)) { return; } ConfigObject.Load(); ConfigFiles.Add(ConfigObject.Name, ConfigObject); }
/// <summary> /// Gets a specified config file /// </summary> /// <typeparam name="T">Type of the config object</typeparam> /// <param name="Name">Name of the config object</param> /// <returns>The config object specified</returns> public static T GetConfigFile <T>(string Name) { if (!ConfigFiles.ContainsKey(Name)) { throw new ArgumentException("The config object " + Name + " was not found."); } if (!(ConfigFiles[Name] is T)) { throw new ArgumentException("The config object " + Name + " is not the specified type."); } return((T)ConfigFiles[Name]); }
/// <summary> /// Gets a value from the config store. Returns default value if config value not defined /// </summary> /// <param name="key">The key of the configuration value to get</param> /// <param name="defaultValue">The default value to return, if configuration key is not present</param> /// <param name="dependencies">The dependencies of the configuration value</param> /// <typeparam name="T"></typeparam> /// <returns>The value of the requested config</returns> public T GetConfigValue <T>(string key, T defaultValue = default(T), params IConfigurationDependency[] dependencies) where T : IConvertible { var fileName = GetFileNameFromDependencies(dependencies); var configNotFound = false; var configFile = ConfigFiles.Find(x => string.Equals(x.Name, fileName, StringComparison.CurrentCultureIgnoreCase)); // if config file does not exist or is empty // return default value for the requested type (means config value is not set) if (configFile == null || configFile.Sections == null || configFile.Sections.Count == 0) { configNotFound = true; } if (!configNotFound) { if (dependencies == null || dependencies.Length == 0) { return(GetConfigValue <T>(configFile.Sections.First(), key, defaultValue)); } var dependenciesOrdered = dependencies.Where(x => x != null).OrderBy(x => x.ConfigOrder).ToList(); var curSection = configFile.Sections.Find(x => x.Id == dependenciesOrdered[0].ConfigId); if (dependenciesOrdered.Count == 1) { return(GetConfigValue <T>(curSection, key, defaultValue)); } // Find the config entry section foreach (var dependency in dependenciesOrdered.Skip(1)) { // Ignore null entries if (dependency == null) { continue; } // If section was not found, return default value (config value not set) if (curSection == null) { configNotFound = true; return(defaultValue); } curSection = curSection.SubSections.Find(x => x.Id == dependency.ConfigId); return(GetConfigValue <T>(curSection, key, defaultValue)); } } // If section was not found, return default value (config value not set) return(defaultValue); }
/// <summary> /// Registers a config file /// </summary> /// <param name="ConfigObject">Config object to register</param> public static void RegisterConfigFile(IConfig ConfigObject) { if (ConfigObject == null) { throw new ArgumentNullException("ConfigObject"); } if (ConfigFiles.ContainsKey(ConfigObject.Name)) { return; } ConfigObject.Load(); ConfigFiles.Add(ConfigObject.Name, ConfigObject); }
public ConcurrentFilesystemTraverser(string rootDirectoryPath) { directories = new Stack <Tuple <DirectoryInfo, DirectoryFingerprint> > (); files = new Queue <Tuple <FileInfo, DirectoryFingerprint> >(); // TBD: handle exceptions on root directory DirectoryInfo di = new DirectoryInfo(rootDirectoryPath); directories.Push(Tuple.Create <DirectoryInfo, DirectoryFingerprint>(di, null)); InitDirSkipList(rootDirectoryPath, ConfigFiles.GetDirectoriesFile()); InitFileSkipList(rootDirectoryPath, ConfigFiles.GetFilesIgnoreFile()); }
// Save the configuration file private void SaveConfig(ConfigFiles cf) { cf.fPath = System.AppDomain.CurrentDomain.BaseDirectory; string combinedConfigFile = System.IO.Path.Combine(cf.fPath, "KTestConfig.json"); JsonSerializer Jser = new JsonSerializer(); StreamWriter sw = new StreamWriter(combinedConfigFile); JsonTextWriter Jwrite = new JsonTextWriter(sw); Jser.NullValueHandling = NullValueHandling.Ignore; Jser.Formatting = Newtonsoft.Json.Formatting.Indented; Jser.Serialize(Jwrite, cf); sw.Close(); }
// copy a config file to the default config file private void btnConfig_Click(object sender, RoutedEventArgs e) { var openFile = new OpenFileDialog(); if (openFile.ShowDialog() == true) { JsonSerializer Jser = new JsonSerializer(); StreamReader sr = new StreamReader(openFile.FileName); JsonReader Jreader = new JsonTextReader(sr); CFiles = Jser.Deserialize <ConfigFiles>(Jreader); sr.Close(); SaveConfig(CFiles); } }
/// <summary> /// Parses the raw bytes of the .TRP file /// </summary> private void ParseFile() { // TODO: Add a warning here if (reader.ReadInt32() != magicNumber) { return; } // Read out the starting entry count reader.BaseStream.Seek(0x10, SeekOrigin.Begin); EntryCount = IPAddress.NetworkToHostOrder(reader.ReadInt32()); Start = IPAddress.NetworkToHostOrder(reader.ReadInt32()); reader.BaseStream.Seek(Start, SeekOrigin.Begin); long readerOffset = 0; fileNameToData = new Dictionary <string, byte[]>(); for (int i = 0; i < EntryCount; i++) { // Get our entry info string fileName = ReadNullTerminatedString(reader).ToLowerInvariant(); reader.BaseStream.Seek(Start + (i * 0x40) + 0x20, SeekOrigin.Begin); long offset = IPAddress.NetworkToHostOrder(reader.ReadInt64()); long size = IPAddress.NetworkToHostOrder(reader.ReadInt64()); readerOffset = reader.BaseStream.Position + 0x10; Console.WriteLine("Processing file [{0}]: {1}", (i + 1), fileName); reader.BaseStream.Seek(offset, SeekOrigin.Begin); byte[] fileData = reader.ReadBytes(Convert.ToInt32(size)); fileNameToData.Add(fileName, fileData); reader.BaseStream.Seek(readerOffset, SeekOrigin.Begin); } foreach (KeyValuePair <string, byte[]> z in fileNameToData.Where(x => x.Key.EndsWith(".png"))) { ImageFiles.Add(new PNGFile(z.Value, z.Key)); } foreach (KeyValuePair <string, byte[]> z in fileNameToData.Where(x => x.Key.EndsWith(".sfm") && !x.Key.Contains("tropconf.sfm"))) { ConfigFiles.Add(new SFMFile(z.Value, z.Key, ImageFiles)); } Console.WriteLine("Complete with parsing TRP file..."); }
public static List <Coordinates> Get_US_Shoreline_Coordinates_List(ConfigFiles jsonConfigPaths) { List <Coordinates> shoreLineCoordinatesList = new List <Coordinates>(); MySql.Data.MySqlClient.MySqlConnection conn; conn = new MySql.Data.MySqlClient.MySqlConnection(); MySqlConnectionStringBuilder conn_string_builder = new MySqlConnectionStringBuilder(); string json = System.IO.File.ReadAllText(jsonConfigPaths.mysqlCredentialsSelect_JsonFile); conn_string_builder = JsonConvert.DeserializeObject <MySqlConnectionStringBuilder>(json); conn = new MySqlConnection(conn_string_builder.ToString()); try { conn.Open(); } catch (Exception erro) { Console.WriteLine(erro); } MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT `NAME`,`latitude`,`longitude` FROM `geo_data`.`us_coastline`;"; try { MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Coordinates shorelineCoordinate = new Coordinates(); shorelineCoordinate.Name = reader[0].ToString(); shorelineCoordinate.Latitude = Double.Parse(reader[1].ToString()); shorelineCoordinate.Longitude = Double.Parse(reader[2].ToString()); shoreLineCoordinatesList.Add(shorelineCoordinate); } conn.Close(); } catch (Exception erro) { Console.WriteLine(erro); } return(shoreLineCoordinatesList); }
private static void LoadCategoryMap() { FileExtensionToCategoryMap = new Dictionary <string, string>(); HashSet <string> Categories = new HashSet <string>(); ConfigSettings[] extensionList = ConfigFileUtil.LoadConfigFile(ConfigFiles.GetCategoriesFile()); foreach (ConfigSettings settings in extensionList) { FileExtensionToCategoryMap.Add(settings.Value.ToLower(), settings.Category); Categories.Add(settings.Category); } Console.WriteLine(" Loaded {0} file extensions in {1} categories\n", FileExtensionToCategoryMap.Count, Categories.Count); }
/// <summary> /// Loads the config files from the ConfigFolder folder /// </summary> private void LoadConfigFiles() { // Create directory if it does not exist if (!Directory.Exists(ConfigFolder)) { Directory.CreateDirectory(ConfigFolder); } foreach (var jsonFile in Directory.GetFiles(ConfigFolder, "*.json")) { var parsedConfigFile = JsonConvert.DeserializeObject <ConfigFile>(File.ReadAllText(jsonFile)); parsedConfigFile.Name = Path.GetFileNameWithoutExtension(jsonFile); ConfigFiles.Add(parsedConfigFile); } }
public void Check_Calib_Files() { string c = CalibrationFiles.ToString(); string d = ConfigFiles.ToString(); proc(string.Format("adb shell ls {0}", con.Calib())); Thread.Sleep(500); Regex rx = new Regex("config.ini"); if (string.IsNullOrEmpty(Output)) { return; } Match matchCon = rx.Match(Output); if (matchCon.Success) { if (!d.Contains(matchCon.Value)) { ConfigFiles.Add(matchCon.Value); } } Regex rxDebug = new Regex("debugConfig.ini"); Match matchConDebug = rxDebug.Match(Output); if (matchConDebug.Success) { if (!d.Contains(matchConDebug.Value)) { ConfigFiles.Add(matchConDebug.Value); } } foreach (string cal in con.Get_Cal_Files()) { Regex rx_ = new Regex(cal); Match match = rx_.Match(Output); if (match.Success) { if (!c.Contains(match.Value)) { CalibrationFiles.Add(match.Value); } } } }
public static List <string> Get_Recent_Existing_Earthquake_IDs(ConfigFiles jsonConfigPaths) { List <string> existingEarthquakeList = new List <string>(); MySql.Data.MySqlClient.MySqlConnection conn; conn = new MySql.Data.MySqlClient.MySqlConnection(); MySqlConnectionStringBuilder conn_string_builder = new MySqlConnectionStringBuilder(); string json = System.IO.File.ReadAllText(jsonConfigPaths.mysqlCredentialsSelect_JsonFile); conn_string_builder = JsonConvert.DeserializeObject <MySqlConnectionStringBuilder>(json); conn = new MySqlConnection(conn_string_builder.ToString()); try { conn.Open(); } catch (Exception erro) { Console.WriteLine(erro); } MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT `geo_quake_id` FROM `geo_data`.`geo_quakes` WHERE FROM_UNIXTIME(`geo_quake_epoch`) > DATE_SUB(NOW(),INTERVAL 2 DAY);"; try { MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string geo_quake_id = reader[0].ToString(); existingEarthquakeList.Add(geo_quake_id); } conn.Close(); } catch (Exception erro) { Console.WriteLine(erro); } return(existingEarthquakeList); }
/// <summary> /// Gets a list of all currently set config values for given dependencies /// </summary> /// <param name="dependencies"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public IReadOnlyList <ConfigValue> GetAllConfigValues(params IConfigurationDependency[] dependencies) { var fileName = GetFileNameFromDependencies(dependencies); var configFile = ConfigFiles.Find(x => string.Equals(x.Name, fileName, StringComparison.CurrentCultureIgnoreCase)); // if config file does not exist or is empty // return default value for the requested type (means config value is not set) if (configFile == null || configFile.Sections == null || configFile.Sections.Count == 0) { return(new List <ConfigValue>()); } var curSection = GetConfigSectionOrNull(configFile, dependencies); return(curSection != null ? curSection.Config : new List <ConfigValue>()); }
public void Check_Config_Files_Etc() { string d = ConfigFiles.ToString(); proc(string.Format("adb shell ls {0}", con.Get_Etc_Iar_Path())); Thread.Sleep(500); Regex rx = new Regex("config.ini"); Match matchCon = rx.Match(Output); if (matchCon.Success) { if (!d.Contains(matchCon.Value)) { ConfigFiles.Add(string.Format(@"\etc\iar\{0}", matchCon.Value)); } } }
static void Main(string[] args) { Console.WriteLine("Earthquake Feed Reader"); string configFilePaths = "filePaths.json"; bool exists = File.Exists(configFilePaths); string json = null; try { json = System.IO.File.ReadAllText(configFilePaths, System.Text.Encoding.UTF8); } catch (Exception json_read) { Console.WriteLine(json_read.Message); } if (json != null) // Check That JSON String Read Above From File Contains Data { ConfigFiles jsonConfigPaths = new ConfigFiles(); jsonConfigPaths = JsonConvert.DeserializeObject <ConfigFiles>(json); List <string> existingEarthquakesList = Get_Recent_Existing_Earthquake_IDs(jsonConfigPaths); string earthquakes_json = Get_Earthquakes_JSON(); var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore }; EarthquakesResult recent_earthquakes = JsonConvert.DeserializeObject <EarthquakesResult>(earthquakes_json, settings); List <FeaturesItem> newEarthquakesList = new List <FeaturesItem>(); foreach (FeaturesItem earthquake in recent_earthquakes.features) { Boolean newEarthquake = Is_New_Earthquake(earthquake.id, existingEarthquakesList); if (newEarthquake == true) { newEarthquakesList.Add(earthquake); } } Add_New_Earthquakes_To_Database(jsonConfigPaths, newEarthquakesList); } }
protected override string GenerateCommandLineCommands() { var cmd = new CommandLineBuilder(); cmd.AppendSwitch("--quiet"); if (ConfigFiles != null && ConfigFiles.Any()) { var config = MergeConfigFiles(); var configPath = Path.Combine(IntermediateOutputPath, "lint.xml"); config.Save(configPath); cmd.AppendSwitchIfNotNull("--config ", configPath); } cmd.AppendSwitchIfNotNull("--enable ", EnabledIssues); cmd.AppendSwitchIfNotNull("--disable ", DisabledIssues); cmd.AppendSwitchIfNotNull("--check ", CheckIssues); foreach (var item in ResourceDirectories) { cmd.AppendSwitchIfNotNull("--resources ", item.ItemSpec); } foreach (var item in SourceDirectories) { cmd.AppendSwitchIfNotNull("--sources ", item.ItemSpec); } foreach (var item in ClassDirectories) { cmd.AppendSwitchIfNotNull("--classpath ", item.ItemSpec); } foreach (var item in ClassPathJars) { cmd.AppendSwitchIfNotNull("--classpath ", item.ItemSpec); } foreach (var item in LibraryDirectories) { cmd.AppendSwitchIfNotNull("--libraries ", item.ItemSpec); } foreach (var item in LibraryJars) { cmd.AppendSwitchIfNotNull("--libraries ", item.ItemSpec); } cmd.AppendFileNameIfNotNull(TargetDirectory); return(cmd.ToString()); }
/// <summary> /// Checks whether a given setting is defined /// </summary> /// <param name="key"></param> /// <param name="dependencies"></param> /// <returns></returns> public bool DoesConfigEntryWithKeyExist(string key, params IConfigurationDependency[] dependencies) { var fileName = GetFileNameFromDependencies(dependencies); // Get file, create it if it doesnt exist yet var configFile = ConfigFiles.Find(x => string.Equals(x.Name, fileName, StringComparison.CurrentCultureIgnoreCase)); if (configFile == null) { return(false); } var section = GetConfigSectionOrNull(configFile, dependencies); if (section == null) { return(false); } return(section.Config.Any(x => x.Key == key)); }
public static void Process_Applicable_Notification(ConfigFiles jsonConfigPaths, FeaturesItem earthquake) { List <Event_Notification> eventNotificationList = new List <Event_Notification>(); List <UserSite> userSiteList = new List <UserSite>(); string json = System.IO.File.ReadAllText(jsonConfigPaths.userSites_JsonFile); userSiteList = JsonConvert.DeserializeObject <List <UserSite> >(json); foreach (UserSite user_site in userSiteList) { double earthquake_latitude = earthquake.geometry.coordinates[1]; double earthquake_longitude = earthquake.geometry.coordinates[0]; double hq_distance = GetDistance(earthquake_latitude, earthquake_longitude, user_site.coordinates.latitude, user_site.coordinates.longitude); double magnitude = earthquake.properties.mag; if (((hq_distance < 50) || (earthquake.properties.tsunami.Equals(1)) || (magnitude >= 2 && hq_distance < 100) || (magnitude >= 3 && hq_distance < 250) || (magnitude >= 4 && hq_distance < 500) || (magnitude >= 5 && hq_distance < 1500) || (magnitude >= 6))) { if (earthquake.properties.tsunami.Equals(1)) { string notify_place = earthquake.properties.place + " Tsunami Evaluation Available"; earthquake.properties.place = notify_place; } Event_Notification eventNotification = new Event_Notification(); eventNotification.eventNotification_Agency = "48941"; eventNotification.eventNotification_Title = earthquake.properties.title; eventNotification.eventNotification_URL = earthquake.properties.url; eventNotification.eventNotification_DatetimeEpoch = (earthquake.properties.time / 1000); eventNotification.eventNotification_Category = "Earthquake"; eventNotification.eventNotification_Type = "Earthquake"; eventNotification.eventNotification_UniqueID = earthquake.id; eventNotification.eventNotification_Latitude = earthquake.geometry.coordinates[1]; eventNotification.eventNotification_Longitude = earthquake.geometry.coordinates[0]; Add_Event_Notification(jsonConfigPaths, eventNotification); } } }
/// <summary> /// Removes a given config entry /// </summary> /// <param name="key">The key of the configuration to remove</param> /// <param name="dependencies"></param> public void DeleteConfigEntry(string key, params IConfigurationDependency[] dependencies) { var fileName = GetFileNameFromDependencies(dependencies); // Get file, create it if it doesnt exist yet var configFile = ConfigFiles.Find(x => string.Equals(x.Name, fileName, StringComparison.CurrentCultureIgnoreCase)); if (configFile == null) { return; } var section = GetConfigSectionOrNull(configFile, dependencies); if (section == null) { return; } section.Config.RemoveAll(x => x.Key == key); SaveConfigFile(configFile); }
public Mod(string path) { Path = new DirectoryInfo(path); // Files = Path.GetFiles("*", SearchOption.AllDirectories).Select(t => t.GetRelativePathFrom(Path)).ToList(); Files = Path.GetFiles("*", SearchOption.AllDirectories).ToList(); foreach (var file in Files) { // System.Windows.Forms.MessageBox.Show(_file); if (file.Name.ToLower() == "mod.json") { if (file.Exists) { Manifest = JsonConvert.DeserializeObject <ModManifest>(file.ReadAllText()); Manifest.File = file; /*foreach (var property in GetType().GetProperties()) * if (property.GetCustomAttributes(typeof (XmlIgnoreAttribute), false).GetLength(0) == 0) * property.SetValue(this, property.GetValue(tmp, null), null);*/ } } else if (Stuff.ConfigExtensions.Any(x => file.Extension.ToLower() == x)) { ConfigFiles.Add(file); } else if (Stuff.ReadmeExtensions.Any(x => file.Extension.ToLower() == x)) { ReadmeFiles.Add(file); } else { var _rel = new FileInfo(file.GetRelativePathFrom(Path)); if (!Enabled && _rel.Exists && _rel.Length == file.Length) { Enabled = true; // Todo: Improve detection (maybe check all files and use real checksum?) } } } // ConfigFiles = Files.Where(t => Stuff.ConfigExtensions.Any(t => t.ToLower().EndsWith(".cfg")); }
internal override void Process(ProcessorArgs args) { Assert.ArgumentNotNull(args, "args"); var webConfig = args.Server.MapPath("/web.config"); var mimeTypes = args.Server.MapPath("/App_Config/MimeTypes.config"); var globalAsax = args.Server.MapPath("/global.asax"); { var webConfigNeeded = !File.Exists(webConfig); var appConfigNeeded = !File.Exists(mimeTypes); // if there is no MimeTypes then no other app_config files var globalAsaxNeeded = !File.Exists(globalAsax); if (!webConfigNeeded && !appConfigNeeded && !globalAsaxNeeded) { return; } args.WriteLine("Extracting config files..."); var release = args.Release; Assert.IsNotNull(release, "release"); var confiFilesUrl = release.Defaults.Configs.FilesUrl; var configFilesZip = new ConfigFiles(confiFilesUrl).Download(); using (var zip = new ZipFile(configFilesZip.FullName)) { foreach (var zipEntry in zip.Entries ?? new ZipEntry[0]) { if (zipEntry == null) { continue; } var virtualPath = zipEntry.FileName ?? string.Empty; if (webConfigNeeded && virtualPath.Equals("web.config", StringComparison.OrdinalIgnoreCase)) { using (var stream = File.OpenWrite(webConfig)) { zipEntry.Extract(stream); } continue; } if (globalAsaxNeeded && virtualPath.Equals("global.asax", StringComparison.OrdinalIgnoreCase)) { using (var stream = File.OpenWrite(globalAsax)) { zipEntry.Extract(stream); } continue; } if (appConfigNeeded && virtualPath.StartsWith("App_Config", StringComparison.OrdinalIgnoreCase)) { var filePath = args.Server.MapPath("/" + virtualPath.TrimStart('/')); if (!File.Exists(filePath)) { var dir = Path.GetDirectoryName(filePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } using (var stream = File.OpenWrite(filePath)) { zipEntry.Extract(stream); } } } } } } }