/// <summary> /// Loads/Reloads all settings from settings.ini file. /// </summary> public void ReloadSettings() { //Read the text file Config = ReadSettings(); //Reassign roles / Channels RoleChannelAssignments(); //Assign the rest of the variables VariableAssignment(); //Read in the search JSON data const string SEARCH_DATA_PATH = "searchData.json"; _searchData = JObject.Parse(File.ReadAllText(SEARCH_DATA_PATH)); _root = _searchData.ToObject <JsonRoot>(); _series = _root.series; //Read in the server JSON data const string SERVER_DATA_PATH = "servers.json"; _serverData = JObject.Parse(File.ReadAllText(SERVER_DATA_PATH)); _root = _serverData.ToObject <JsonRoot>(); _servers = _root.servers; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("SETTINGS HAVE BEEN LOADED\n"); Console.ResetColor(); }
public async void DownloadComics(int page) { var status = DownloadStatus.Success; Comics = new List <CommitStripItem>(); var s = new JsonRoot(); s.items = new List <JsonItem>(); s.items.Add(new JsonItem()); try { var url = Constants.ComicFeedPage(page, Settings.ComicLanguageSettings); Client.DefaultRequestHeaders.Clear(); Client.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", "USER_LANG=" + Settings.ComicLanguageSettings + ";"); var response = await Client.GetStringAsync(url); Comics = ParseRss(response); } catch (Exception e) { Debug.WriteLine(e.ToString()); status = DownloadStatus.NoMorePages; } DownloadHandler(new DownloadInformation(status)); }
public void Import(string filePath) { var files = Directory.GetFiles(filePath) .Where(x => x.EndsWith(".json")); var root = new JsonRoot(); foreach (var file in files) { var fileRoot = GetRoot(file); root.data.AddRange(fileRoot.data); } var planets = this.service.AddPlanets(this.GetPlanets(root)); var countries = this.service.AddCountries(this.GetCountries(root, planets)); var cities = this.service.AddCities(this.GetCities(root, countries)); var fractions = this.service.AddFractions(this.GetFractions(root)); var powers = this.service.AddPowers(this.GetPowers(root)); this.service.AddHeroes(this.GetHeroes(root, cities, fractions, powers)); this.service.LinkPlanetsWithFractions(); }
private IEnumerable <Fraction> GetFractions(JsonRoot root) { var fractionNames = new Dictionary <string, AlignmentType>(StringComparer.OrdinalIgnoreCase); foreach (var jsonHero in root.data) { if (jsonHero.fractions != null) { foreach (var jsonHeroFraction in jsonHero.fractions) { if (!fractionNames.ContainsKey(jsonHeroFraction)) { fractionNames.Add(jsonHeroFraction, jsonHero.alignment == "good" ? AlignmentType.Good : jsonHero.alignment == "bad" ? AlignmentType.Bad : AlignmentType.Evil); } } } } var fractions = fractionNames .Select(f => new Fraction { Name = f.Key, Alignment = f.Value }); return(fractions); }
public void TestNewJson() { var root = new JsonRoot() { Filename = "mypage.html", Id = "123", Title = "This is my page", Info = new Info() { description = new Description() { DateTimeValues = new object[] { DateTime.Now, DateTime.UtcNow }, FieldType = 1, LinkedComponentValues = new object[] { "ABC", "XYZ" }, Name = "MyInfo", NumericValues = new object[] { 1, 2, 3, 4, 5 }, Values = (new List<string> { "some values" }).ToArray(), }, title = new Title() { FieldType = 5, NumericValues = new object[] { 1, 2, 43 }, Values = new string[] { "sdfs", "dfgdf" }, Name = "Some name", LinkedComponentValues = new object[] {"34555", "678786"}, DateTimeValues = new object[] {DateTime.Now}, }, }, }; var json = JsonConvert.SerializeObject(root); Console.WriteLine(json); }
private JsonRoot UpdateJson(JsonRoot root, string directory, string filename, IFormCollection form, Source source, string SASToken) { // Variables prepare string baseRoute = $"https://soundbuttons.blob.core.windows.net/sound-buttons/{directory}/"; string group = form.GetFirstValue("group") ?? "未分類"; // Get ButtonGrop if exists, or new one ButtonGroup buttonGroup = null; foreach (var btg in root.buttonGroups) { try { var name = btg.name.ZhTw; if (group == name) { buttonGroup = btg; break; } } catch (InvalidCastException) { } } if (null == buttonGroup) { buttonGroup = new ButtonGroup { name = new Text(group, group), baseRoute = baseRoute, buttons = new List <Button>() }; root.buttonGroups.Add(buttonGroup); } // Prevent script injection source.videoId = System.Web.HttpUtility.UrlEncode(source.videoId); // Add button if (!float.TryParse(form.GetFirstValue("volume"), out float volume)) { volume = 1; } buttonGroup.buttons.Add(new Button( filename, new Text( form.GetFirstValue("nameZH") ?? "", form.GetFirstValue("nameJP") ?? "" ), volume, source, SASToken )); return(root); }
public void BuildFileInvalidTokenTest() { // Arrange IWriter Writer = new HPGLWriter(); JsonRoot json = new JsonRoot(); // Act // Assert }
private IEnumerable <Power> GetPowers(JsonRoot root) { return(root.data .SelectMany(p => p.powers) .Distinct() .Select(p => new Power { Name = p })); }
/// <summary> /// The WriteFile method writes the contents of a given file. /// </summary> /// <param name="root"> The root object is the JsonRoot item that commands are to be genereted from. </param> /// <param name="path"> The path object is the location where the file is to be written. </param> public void WriteFile(JsonRoot root, string @path) { // Instansiate a new HPGLWriter and use it to create a file. HPGLWriter writer = new HPGLWriter(); string towrite = writer.BuildFile(root); // If the file already exists clear it, then write the new one. ClearFile(@path); File.WriteAllText(path, towrite); }
private IEnumerable <Planet> GetPlanets(JsonRoot root) { return(root.data .Select(h => h.city.planet) .Distinct() .Select(p => new Planet { Name = p })); }
private static void SaveDependencies() { Objects = new List<KeyValuePair<string, string>>(); Dependencies = new List<KeyValuePair<string, List<string>>>(); foreach (var obj in Selection.objects) { List<string> deps = new List<string>(); string objPath = AssetDatabase.GetAssetPath(obj); objPath = objPath.Replace("Assets/Resources/", ""); int fileExtPos = objPath.LastIndexOf('.'); objPath = objPath.Substring(0, fileExtPos); Objects.Add(new KeyValuePair<string, string>(obj.name, objPath)); var dependencies = EditorUtility.CollectDependencies(new[] { obj }); foreach (var d in dependencies) { string path = AssetDatabase.GetAssetPath(d); if (path.Contains("Assets/Resources/")) { path = path.Replace("Assets/Resources/", ""); fileExtPos = path.LastIndexOf('.'); path = path.Substring(0, fileExtPos); if (d is Texture2D || d is Material || d is Shader) { deps.Add(path); } } } Dependencies.Add(new KeyValuePair<string, List<string>>(obj.name, deps)); } JsonRoot root = new JsonRoot(); int count = 0; foreach (var obj in Objects) { JsonClass jsonObject = new JsonClass(count.ToString()); jsonObject.AddObjects(new JsonValue(ObjectFromCache.JsonName, obj.Key)); jsonObject.AddObjects(new JsonValue(ObjectFromCache.JsonPath, obj.Value)); jsonObject.AddObjects(new JsonArray(ObjectFromCache.JsonDependencies, Dependencies.Find((d)=> obj.Key == d.Key).Value)); root.AddObjects(jsonObject); count++; } string filepath = EditorUtility.SaveFilePanel("Save dependencies for selected objects", "Assets", "Dependencies", "json"); File.WriteAllText(filepath, root.ToString(), Encoding.UTF8); }
/// <summary> /// The entrypoint for building an HPGL file. /// </summary> /// <param name="root"> The JsonRoot object that is used to generated the file. </param> public string BuildFile(JsonRoot root) { hpglbuilder.AppendLine(InitialiseFile()); string cmd = null; // For every token in the JsonRoot array foreach (SerialiseObject serialisedToken in root.tokenarray) { if (serialisedToken != null) { switch (serialisedToken.tokenID) { case (byte)SymbolTable.Circle: cmd = CircleCommand(serialisedToken); hpglbuilder.AppendLine(cmd); break; case (byte)SymbolTable.Rectangle: cmd = RectangleCommand(serialisedToken); hpglbuilder.AppendLine(cmd); break; case (byte)SymbolTable.Ellipse: EllipseCommand(serialisedToken); Console.WriteLine("Ellipses are not support at this time. Press any key to continue..."); Console.ReadKey(); break; case (byte)SymbolTable.Line: cmd = LineCommand(serialisedToken); hpglbuilder.AppendLine(cmd); break; case (byte)SymbolTable.Polyline: cmd = PolylineCommand(serialisedToken); hpglbuilder.AppendLine(cmd); break; case (byte)SymbolTable.Polygon: cmd = PolygonCommand(serialisedToken); hpglbuilder.AppendLine(cmd); break; default: // Fail silently. break; } } } return(hpglbuilder.ToString()); }
/// <summary> Loads in song list data from song_list.json </summary> /// <returns> /// Instance of JsonRoot, which contains all data from file. /// </returns> /// <exception cref="FileNotFoundException"> /// Raised if song_list.json does not exist in the program directory. /// <exception> /// <exception cref="JsonException"> /// Raised if there was an error reading in data from song_list.json. /// </exception> private static JsonRoot LoadJson() { using (StreamReader r = new StreamReader("song_list.json")) { string json = r.ReadToEnd(); JsonRoot jsonRoot = JsonConvert.DeserializeObject <JsonRoot>(json); if (jsonRoot.Entries == null) { jsonRoot.Entries = new List <Entry>(); } return(jsonRoot); } }
private async Task ProcessJsonFile(HttpRequest req, Source source, string directory, string filename, string fileExtension, string sasContainerToken) { // Get last json file CloudBlockBlob jsonBlob = cloudBlobContainer.GetBlockBlobReference($"{directory}/{directory}.json"); log.LogInformation("Read Json file {name}", jsonBlob.Name); JsonRoot root; // Read last json file using (Stream input = jsonBlob.OpenRead()) { root = await JsonSerializer.DeserializeAsync <JsonRoot>(input, new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, // For Unicode and '&' characters Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); } // Get new json file block CloudBlockBlob newjsonBlob = cloudBlobContainer.GetBlockBlobReference($"{directory}/UploadJson/{DateTime.Now:yyyy-MM-dd-HH-mm}.json"); newjsonBlob.Properties.ContentType = "application/json"; // Generate new json file JsonRoot json = UpdateJson(root, directory, filename + fileExtension, req.Form, source, sasContainerToken); byte[] result = JsonSerializer.SerializeToUtf8Bytes <JsonRoot>( json, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, WriteIndented = true }); log.LogInformation("Write Json {name}", jsonBlob.Name); log.LogInformation("Write Json backup {name}", newjsonBlob.Name); // Write new json file Task.WaitAll(newjsonBlob.UploadFromByteArrayAsync(result, 0, result.Length), jsonBlob.UploadFromByteArrayAsync(result, 0, result.Length)); }
private IEnumerable <Country> GetCountries(JsonRoot root, IEnumerable <Planet> planets) { return(root.data .Select(x => new { x.city.country, x.city.planet }) .GroupBy(x => x.country) .Select(g => g.First()) .Select(x => new Country { Name = x.country, PlanetId = planets.FirstOrDefault(p => p.Name.Equals(x.planet)).PlanetId })); }
private IEnumerable <City> GetCities(JsonRoot root, IEnumerable <Country> countries) { return(root.data .Select(x => new { x.city.country, x.city.name }) .GroupBy(x => x.name) .Select(g => g.First()) .Select(x => new City { CountryId = countries.FirstOrDefault(c => c.Name.Equals(x.country)).CountryId, Name = x.name })); }
/// <summary> /// Generate a launchSettings.json in a Properties subfolder of the csproj from the conf.CsprojUserFile /// </summary> /// <param name="builder">The builder to use</param> /// <param name="project">The project the conf belong to</param> /// <param name="projectPath">The path of the csproj</param> /// <param name="configurations">The list of configurations to lookup for CsprojUserFile</param> /// <param name="generatedFiles">Files written by the method</param> /// <param name="skipFiles">Files already up-to-date and skipped</param> /// <returns>The full path of the launchSettings.json</returns> public static string Generate( Builder builder, Project project, string projectPath, IEnumerable <Project.Configuration> configurations, IList <string> generatedFiles, IList <string> skipFiles ) { bool overwriteFile; var launchSettingsProfiles = GetLaunchSettingsFromCsprojUserFile(project, configurations, out overwriteFile); if (launchSettingsProfiles == null || !launchSettingsProfiles.Any()) { return(null); } var memoryStream = new MemoryStream(); var writer = new StreamWriter(memoryStream); var root = new JsonRoot { profiles = launchSettingsProfiles }; // Write the list of files. writer.Write(JsonSerializer.Serialize(root, GetJsonSerializerOptions())); writer.Flush(); //Skip overwriting user file if it exists already so he can keep his setup // unless the UserProjSettings specifies to overwrite var userFileInfo = new FileInfo(Path.Combine(projectPath, "Properties", FileName)); bool shouldWrite = !userFileInfo.Exists || overwriteFile; if (shouldWrite && builder.Context.WriteGeneratedFile(typeof(LaunchSettingsJson), userFileInfo, memoryStream)) { generatedFiles.Add(userFileInfo.FullName); } else { skipFiles.Add(userFileInfo.FullName); } return(userFileInfo.FullName); }
private IEnumerable <Superhero> GetHeroes( JsonRoot root, IEnumerable <City> cities, IEnumerable <Fraction> fractions, IEnumerable <Power> powers) { var heroes = new Collection <Superhero>(); foreach (var jsonHero in root.data) { var hero = new Superhero { Name = jsonHero.name, CityId = cities.FirstOrDefault(c => c.Name.Equals(jsonHero.city.name)).CityId, SecretIdentity = jsonHero.secretIdentity, Story = jsonHero.story, Alignment = (jsonHero.alignment == "good" ? AlignmentType.Good : jsonHero.alignment == "bad" ? AlignmentType.Bad : AlignmentType.Evil), }; hero.Powers = powers .Where(p => jsonHero.powers .Contains(p.Name)) .ToList(); if (jsonHero.fractions != null) { hero.Fractions = fractions .Where(f => jsonHero.fractions.Contains(f.Name)).ToList(); } heroes.Add(hero); } return(heroes .GroupBy(h => h.SecretIdentity) .Select(g => g.First())); }
public void ReadData() { config = ReadSettings(); RoleChannelAssignments(); VariableAssignment(); string searchDataPath = "searchData.json"; searchData = JObject.Parse(File.ReadAllText(searchDataPath)); root = searchData.ToObject <JsonRoot>(); series = root.series; string serverDataPath = "servers.json"; serverData = JObject.Parse(File.ReadAllText(serverDataPath)); root = serverData.ToObject <JsonRoot>(); servers = root.servers; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("SETTINGS HAVE BEEN LOADED\n"); Console.ResetColor(); }
/// <summary> /// Parse a given array of tokens. /// </summary> /// <param name="tokens">The tokens to be parsed.</param> public static void Parse(IToken[] tokens) { JsonRoot jsonRoot; SerialiseObject serialiseObject; // Set the Json intentation option to true. JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true }; // Instansiate a jsonroot object and set its internal array of tokens // to the number of tokens passed to it. jsonRoot = new JsonRoot(); jsonRoot.tokenarray = new SerialiseObject[tokens.Length]; // For each token. for (int i = 0; i < tokens.Length; i++) { // If it is not null if (tokens[i] != null) { // Set the serialiseObject to the values stored in the token. IToken token = tokens[i]; serialiseObject = new SerialiseObject(); serialiseObject.tokenID = token.GetID(); serialiseObject.attributes = token.GetNamedParameters(); // Style information goes here... // Add the serialiseObject representation of the token to the JsonRoot object. jsonRoot.tokenarray[i] = serialiseObject; } } // Serialise the JsonRoot object and write it. var Json = JsonSerializer.Serialize <JsonRoot>(jsonRoot, options); IRWriter.Write(Json, @path); }
/// <summary> /// The main method that the system performs. It is responsible for directing the /// operation of the entire compiler. /// </summary> /// <param name="input"> The input path that needs to be used. </param> /// <param name="output" The output path that needs to be used. ></param> /// <returns></returns> public static bool Compile(string @input, string @output) { // Try to validate that input path. try { ValidatePath(@input); } catch (FileNotFoundException exception) { // Show the exception and return with a flag of false. Console.WriteLine(exception); return(SuccessFlag); } // Instantiate the frontend and backends for the compiler, // this is where a programmer would add their own implementations. IFrontend frontend = new TinySvgFrontend(); IBackend backend = new HpglBackend(); // Get the statements from the input file using the appropriate reader. var statements = frontend.Read(input); // Tokenise the statements. var lexemes = frontend.Lex(statements); // Parse the tokens to an intermediate representation. frontend.Parse(lexemes); // Read the tokens from the IR file and pass it to the appropriate // backend writer file. JsonRoot s = IRReader.Read(); backend.WriteFile(s, output); // If all this has happened with no errors set the successflag to true. SuccessFlag = true; return(SuccessFlag); }
public static string ToDotNetSourceCode(this string json, string rootTypeName, SerializationModel serializetype = SerializationModel.DataContractJsonSerializer, string language = @"CS") { var sb = new StringBuilder(); if (!string.IsNullOrEmpty(json)) { var jtoken = JObject.Parse(json) as JToken; if (null != jtoken) { var root = JsonRoot.ParseJsonIntoDataContract(jtoken, rootTypeName); using (var stringWriter = new StringWriter(sb)) { JsonRootCompiler compiler = new JsonRootCompiler(language, serializetype); compiler.GenerateCode(root, stringWriter); } } } return(sb.ToString()); }
/// <summary> Adds newEntry to jsonRoot and saves data to file </summary> /// <param name="jsonRoot"> /// A reference to the instance of JsonRoot containing all song data /// </param> /// <param name="newEntry"> /// New instance of Entry that needs to be saved to file. /// </param> private static void SaveNewEntry(ref JsonRoot jsonRoot, in Entry newEntry)
public static void Main() { JsonRoot jsonRoot = null; try { jsonRoot = LoadJson(); } catch (FileNotFoundException) { Console.WriteLine("Error: song_list.json was not found in the program directory."); System.Environment.Exit(1); } catch (JsonException) { Console.WriteLine("Error: could not read data from song_list.json"); System.Environment.Exit(1); } List <Entry> entries = jsonRoot.Entries; Console.WriteLine("\nHello! Welcome to Song Tracker."); while (true) { Console.WriteLine("\nWhat would you like to do? (input a number)"); Console.WriteLine("1 - Add new entry\n2 - Search previous favourite songs\n3 - Info\n4 - Exit Program\n"); var input = Console.ReadLine(); switch (input) { case "1": Entry prevEntry = null; if (entries.Count > 0) { prevEntry = entries[entries.Count - 1]; } Entry newEntry = CreateNewEntry(prevEntry); if (newEntry != null && newEntry.Songs.Count > 0) { SaveNewEntry(ref jsonRoot, in newEntry); Console.WriteLine("\nNew Entry has been saved."); } else { Console.WriteLine("\nThere must be at least 1 song in the list to create a new entry."); } break; case "2": SearchFavourites(in entries); break; case "3": Info(); break; case "4": System.Environment.Exit(0); break; default: Console.WriteLine($"\n'{input}' is not a valid answer.\n"); break; } } }
public static void SaveData(string userIdentifier) { var root = new JsonRoot(); root.AddObjects(new JsonValue("MaxScore", MaxScore)); string saveString = root.ToString(); PlayerPrefs.SetString("login_type", _loginType.ToString()); PlayerPrefs.SetString(_saveName + "_" + userIdentifier, saveString); PlayerPrefs.SetString(GameController.UserIdentifier, GameController.UserIdentifier); OnDataSaved(); }
public static void SaveData() { var root = new JsonRoot(); root.AddObjects(new JsonValue("Sound", _sound)); root.AddObjects(new JsonValue("Music", _music)); root.AddObjects(new JsonValue("LoginType", _loginType)); root.AddObjects(new JsonValue("Gender", _gender)); root.AddObjects(new JsonValue("Language", _language)); string saveString = root.ToString(); var bf = new BinaryFormatter(); Debug.LogError("Save string = " + saveString); Debug.LogError(Application.persistentDataPath + _saveName); var file = File.Open(Application.persistentDataPath + _saveName, FileMode.Create); bf.Serialize(file, saveString); file.Close(); OnDataSaved(); }
internal static LatestMediaHandler.MQTTItem GetArtwork(this LatestMediaHandler.MQTTItem self, string mode) { string id = mode == "tv" ? GetTVID(self.Id) : self.Id; if (!string.IsNullOrEmpty(id)) { if (Utils.ImageCache == null) { Utils.ImageCache = new Hashtable(); } string key = "#" + mode + "#" + id; string json = Utils.ImageCache.Contains(key) ? (string)Utils.ImageCache[key] : Utils.DownloadJson(ApiURLTheMovieDB + mode + "/" + id + "/images?api_key=" + ApiKeyTheMovieDB); if (!string.IsNullOrEmpty(json)) { try { JsonRoot images = JsonConvert.DeserializeObject <JsonRoot>(json); // Poster string image = images.posters.Where(l => l.iso_639_1 == Utils.Language).OrderByDescending(x => x.vote_average).ThenByDescending(y => y.width).FirstOrDefault().file_path ?? string.Empty; if (!string.IsNullOrEmpty(image)) { self.Poster = ApiImageTheMovieDB + image; } else if (Utils.Language != "en") { image = images.posters.Where(l => l.iso_639_1 == "en").OrderByDescending(x => x.vote_average).ThenByDescending(y => y.width).FirstOrDefault().file_path ?? string.Empty; if (!string.IsNullOrEmpty(image)) { self.Poster = ApiImageTheMovieDB + image; } } // Background image = images.backdrops.Where(l => l.iso_639_1 == Utils.Language).OrderByDescending(x => x.vote_average).ThenByDescending(y => y.width).FirstOrDefault().file_path ?? string.Empty; if (!string.IsNullOrEmpty(image)) { self.Fanart = ApiImageTheMovieDB + image; } else if (Utils.Language != "en") { image = images.backdrops.Where(l => l.iso_639_1 == "en").OrderByDescending(x => x.vote_average).ThenByDescending(y => y.width).FirstOrDefault().file_path ?? string.Empty; if (!string.IsNullOrEmpty(image)) { self.Fanart = ApiImageTheMovieDB + image; } } // Cache if (!Utils.ImageCache.Contains(key)) { Utils.TVIDCache.Add(key, json); } } catch { } } // Poster if (!self.Poster.StartsWith("http")) { self.Poster = Utils.ImageToDataImage(self.Poster, 133, 200); } // Background if (!self.Fanart.StartsWith("http")) { self.Fanart = Utils.ImageToDataImage(self.Fanart, 444, 250); } } return(self); }
/// <summary> Writes data from jsonRoot into song_list.json </summary> /// <param name="jsonRoot"> /// The instance of jsonRoot containing the data to write to file. /// </param> /// <exception cref="JsonException"> /// Raised if there was an error writing data to song_list.json. /// </exception> private static void WriteJson(JsonRoot jsonRoot) { string jsonString = JsonConvert.SerializeObject(jsonRoot, Formatting.Indented); System.IO.File.WriteAllText("song_list.json", jsonString); }
public static JsonRoot Parse(string json) { JsonRoot m = JsonConvert.DeserializeObject <JsonRoot>(json, jsonSettings); return(m); }
public static JsonRoot GetJson() { var root = new JsonRoot(); root.AddObjects(new JsonValue("last_project", _lastProject)); return root; }