public void GenerateJsonSchema() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(JoinGroupMessageContent)); Console.WriteLine(schema); }
public override JSchema GetSchema(JSchemaTypeGenerationContext context) { var type = context.ObjectType; JSchema schema = null; var generator = new JSchemaGenerator(); Console.WriteLine(type.Name); var isObject = type.Namespace != "System"; if (isObject) { if (SkipType == type.Name) { return(null); } this.SkipType = type.Name; generator.GenerationProviders.Add(this); } schema = generator.Generate(type); return(ModifySchema(schema, context)); }
private string _gerarJson() { var schemaGenerator = new JSchemaGenerator(); var schema = schemaGenerator.Generate(typeof(AutenticarUsuarioQuery)); return(""); }
private static string GetOrSaveSchemaReference(Type type) { string key = type.FullName; if (SchemaCache.Cache.ContainsKey(key)) { return(key); } JSchemaGenerator generator = new JSchemaGenerator { SchemaIdGenerationHandling = SchemaIdGenerationHandling.FullTypeName, SchemaReferenceHandling = SchemaReferenceHandling.None }; JSchema schema = generator.Generate(type); // I didn't find the way how to disallow JSchemaGenerator to use nullable types, swagger doesn't work with them string tmp = schema.ToString(); string s = @"\""type\"":[\s\n\r]*\[[\s\n\r]*\""(\w+)\"",[\s\n\r]*\""null\""[\s\n\r]*\]"; tmp = Regex.Replace(tmp, s, "\"type\": \"$1\""); SchemaCache.Cache[key] = JSchema.Parse(tmp); return(key); }
public SchemaGenerator() { this.generator = new JSchemaGenerator(); //ED: Comment me out //generator.GenerationProviders.Add(new GuidSchemaGenerationProvider()); }
static void Main(string[] args) { var generator = new JSchemaGenerator(); var schema = generator.Generate(typeof(Something)); File.WriteAllText("R:/schema.json", schema.ToString()); }
static void Main(string[] args) { Console.WriteLine(RemoveDuplicates(new int[] { 1, 1, 2, 2, 3, 3 })); JSchemaGenerator generator = new JSchemaGenerator(); generator.DefaultRequired = Required.DisallowNull; JSchema schema = generator.Generate(typeof(PostalAddress)); Console.WriteLine(schema.ToString()); var cancelTokenSource = new CancellationTokenSource(); Task.Factory.StartNew(() => { while (!cancelTokenSource.IsCancellationRequested) { Console.WriteLine(DateTime.Now); Thread.Sleep(1000); } }, cancelTokenSource.Token); Console.WriteLine("Press any key to cancel"); Console.ReadLine(); cancelTokenSource.Cancel(); Console.WriteLine("Done"); Console.ReadLine(); Console.WriteLine("Hello World!"); }
public static Dataset <TData> CreateDataset(string apiToken, string name, string datasetId, string origUrl, string description = "", string sourceCodeUrl = "", bool betaVersion = true, bool allowWriteAccess = false, string[,] orderList = null, V2.CoreApi.Model.Template searchResultTemplate = null, V2.CoreApi.Model.Template detailTemplate = null, bool hidden = false) { var jsonGen = new JSchemaGenerator { DefaultRequired = Newtonsoft.Json.Required.Default }; var reg = new V2.CoreApi.Model.Registration() { Name = name, DatasetId = datasetId, OrigUrl = origUrl, Description = description, SourcecodeUrl = sourceCodeUrl, Betaversion = betaVersion, AllowWriteAccess = allowWriteAccess, OrderList = orderList, SearchResultTemplate = searchResultTemplate, DetailTemplate = detailTemplate, Hidden = hidden, JsonSchema = jsonGen.Generate(typeof(TData)).ToString() }; return(CreateDataset(apiToken, reg)); }
/// <summary> /// 型引数からJSchemaを生成します。 /// </summary> public static JSchema generateSchema <T>() { var gen = new JSchemaGenerator(); gen.DefaultRequired = Required.DisallowNull; return(gen.Generate(typeof(T))); }
private static void Main() { // Call: dotnet user-secrets set AuthKey YOUR_AUTH_KEY Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddUserSecrets <Program>() .Build(); var generator = new JSchemaGenerator { ContractResolver = new DocumentCollectionContractResolver() }; generator.GenerationProviders.Add(new StringEnumGenerationProvider()); JSchema schema = generator.Generate(typeof(DocumentCollection)); Console.WriteLine(schema.ToString()); File.WriteAllText(@"C:\temp\collection-schema.json", schema.ToString()); CreateCollection().Wait(); Console.WriteLine("OK"); }
public void Example() { #region Usage JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(User)); // { // "type": "object", // "properties": { // "name": { // "type": "string" // }, // "role": { // "type": [ // "string", // "null" // ] // } // }, // "required": [ // "name" // ] // } #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); }
public void Example() { #region Usage JSchemaGenerator generator = new JSchemaGenerator(); // types with no defined ID have their type name as the ID generator.UndefinedSchemaIdHandling = JSchemaUndefinedIdHandling.UseTypeName; JSchema schema = generator.Generate(typeof(Person)); // { // "id": "Person", // "type": "object", // "properties": { // "name": { // "type": [ "string", "null" ] // }, // "age": { "type": "integer" } // }, // "required": [ "name", "age" ] // } #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); Assert.AreEqual("Newtonsoft.Json.Schema.Tests.Documentation.Samples.Generation.GenerateWithJSchemaUndefinedIdHandling+Person", schema.Id.OriginalString); }
public static JSchema getJsonSchema() { /* manually generated by hand */ /* * return JSchema.Parse(@"{ * 'type': 'object', * 'properties': { * 'rects': {'type': 'array', * 'items': { * 'type': 'object', * 'properties': { * 'x': {'type': 'integer'}, * 'y': {'type': 'integer'}, * 'delta_x': {'type': 'integer'}, * 'delta_z': {'type': 'integer'}, * }, * 'required': ['x','y','delta_x','delta_y'] * } * } * }, * 'required': ['rects'] * }"); */ JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(RectanglesDTO)); return(schema); }
private static async Task <string> ValidateResponse <T>(string restRequest, string id) { restRequest += "/" + id; UriBuilder.Path = restRequest; var schemaGenerator = new JSchemaGenerator(); schemaGenerator.GenerationProviders.Add(new StringEnumGenerationProvider()); var schema = schemaGenerator.Generate(typeof(T)); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync(UriBuilder.Uri)) { response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); var obj = JObject.Parse(content); IList <ValidationError> errors; if (!obj.IsValid(schema, out errors)) { return(errors.Select(e => string.Format("{0}, value is {1}", e.Message, e.Value)).Aggregate((buf, next) => buf + "\n" + next)); } return(null); } } }
public IList <TemplateSetting> GetTemplateSettings(string path, bool verbose) { var generator = new JSchemaGenerator(); if (!File.Exists(path)) { throw new IOException(String.Concat("The specified template settings path does not exist: ", path)); } var schema = generator.Generate(typeof(Templates)); var json = String.Join("", File.ReadAllLines(path)); var errors = ValidateJSON(json, schema); if (errors.Count != 0) { Console.WriteLine(String.Concat("Ivalid dvgen configuration file : ", path)); foreach (var e in errors) { Console.WriteLine(e); } // TODO: This should be handled by caller throw new Exception(String.Concat("Ivalid template-settings.json configuration file : ", path)); } else { var templates = JsonConvert.DeserializeObject <Templates> (json); // TODO: Can you deserialize directly to a Collection? return(templates.Settings); } }
public void SchemaIdGenerationHandlingTest() { #region SchemaIdGenerationHandling JSchemaGenerator generator = new JSchemaGenerator(); // types with no defined ID have their type name as the ID generator.SchemaIdGenerationHandling = SchemaIdGenerationHandling.TypeName; JSchema schema = generator.Generate(typeof(Person)); //{ // "id": "Person", // "type": "object", // "properties": { // "name": { // "type": [ "string", "null" ] // }, // "age": { "type": "integer" } // }, // "required": [ "name", "age" ] //} #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); Assert.AreEqual("Person", schema.Id.OriginalString); }
public void CircularReferenceWithMixedRequires() { JSchemaGenerator generator = new JSchemaGenerator(); generator.UndefinedSchemaIdHandling = JSchemaUndefinedIdHandling.UseTypeName; JSchema schema = generator.Generate(typeof(CircularReferenceClass), true); string json = schema.ToString(); Tests.StringAssert.AreEqual(@"{ ""id"": ""Newtonsoft.Json.Schema.Tests.TestObjects.CircularReferenceClass"", ""type"": [ ""object"", ""null"" ], ""properties"": { ""Name"": { ""type"": ""string"" }, ""Child"": { ""$ref"": ""#"" } }, ""required"": [ ""Name"" ] }", json); }
public async System.Threading.Tasks.Task ObjNodeTestAsync() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(Account)); var node = new ObjectNode(); node.InPorts = new List <INode>(); node.LogicPath = true; node.Schema = schema.ToString(); var account = new Account { Email = "*****@*****.**", Name = "Johe Doe", Age = 20, DateBrith = new DateTimeOffset(1980, 1, 1, 12, 1, 2, new TimeSpan(-6, 0, 0)), Address = new Address { Line1 = "Mobile AL" }, Duration = new TimeSpan(12, 0, 1), LastLogin = DateTime.Now }; node.JsonString = JsonConvert.SerializeObject(account); await node.Init(new PadExecutionContext() { Pad = new Pad(Engine.Enums.ExecutionMode.Normal) { Nodes = new List <INode>() } }); await node.Execute(node.Context); Assert.NotNull(node.ObjectValue); }
public void SerializeDeserialize_FromGeneratedSchemas_SchemasAreKeept(string json) { JSchema schema = new JSchemaGenerator().Generate(JObject.Parse(json)); JSchema deserialized = JsonConvert.DeserializeObject <JSchema>(JsonConvert.SerializeObject(schema)); Assert.That(deserialized, ObjectHas.Properties.EqualTo(schema)); }
public void Generate_DefaultValueAttributeTestClass() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass)); string json = schema.ToString(); Console.WriteLine(json); StringAssert.AreEqual(@"{ ""type"": ""object"", ""additionalProperties"": false, ""properties"": { ""TestField1"": { ""type"": ""integer"", ""default"": 21 }, ""TestProperty1"": { ""type"": [ ""string"", ""null"" ], ""default"": ""TestProperty1Value"" } }, ""required"": [ ""TestField1"", ""TestProperty1"" ] }", json); }
public void GenerateSchemaWithStringEnum() { JSchemaGenerator generator = new JSchemaGenerator(); generator.GenerationProviders.Add(new StringEnumGenerationProvider { CamelCaseText = true }); JSchema schema = generator.Generate(typeof(Y)); string json = schema.ToString(); StringAssert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""y"": { ""type"": ""string"", ""enum"": [ ""no"", ""asc"", ""desc"" ] } }, ""required"": [ ""y"" ] }", json); }
protected virtual void InitJsonSchema() { JSchemaGenerator generator = new JSchemaGenerator(); _schemas.Add(generator.Generate(typeof(JoinGroupMessageContent)), typeof(JoinGroupMessageContent)); _schemas.Add(generator.Generate(typeof(HomeworkMessageContent)), typeof(HomeworkMessageContent)); }
public void StringAttributeOptionsTest() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(StringAttributeOptions)); JSchema string1 = schema.Properties["String1"]; JSchema string2 = schema.Properties["String2"]; JSchema string3 = schema.Properties["String3"]; Assert.AreEqual(JSchemaType.String, string1.Type); Assert.AreEqual("[A-Z]", string1.Pattern); Assert.AreEqual(JSchemaType.String, string2.Type); Assert.AreEqual("date", string2.Format); Assert.AreEqual(JSchemaType.String, string3.Type); Assert.AreEqual("uri", string3.Format); Assert.AreEqual("date-time", schema.Properties["String4"].Format); Assert.AreEqual("time", schema.Properties["String5"].Format); Assert.AreEqual("email", schema.Properties["String6"].Format); Assert.AreEqual("uri", schema.Properties["String7"].Format); Assert.AreEqual("phone", schema.Properties["String8"].Format); Assert.AreEqual("phone", schema.Properties["String9"].Format); Assert.AreEqual("email", schema.Properties["String10"].Format); Assert.AreEqual(0, schema.Properties["String11"].MinimumLength); Assert.AreEqual(50, schema.Properties["String11"].MaximumLength); Console.WriteLine(schema.ToString()); }
public static void GetSchema() { //using Newtonsoft.Json; //using Newtonsoft.Json.Schema; //using Newtonsoft.Json.Schema.Generation; //using Newtonsoft.Json.Serialization; JSchemaGenerator generator = new JSchemaGenerator(); //Generator settings generator.GenerationProviders.Add(new StringEnumGenerationProvider()); generator.DefaultRequired = Required.Default; generator.SchemaLocationHandling = SchemaLocationHandling.Inline; generator.SchemaReferenceHandling = SchemaReferenceHandling.All; generator.SchemaIdGenerationHandling = SchemaIdGenerationHandling.TypeName; generator.ContractResolver = new CamelCasePropertyNamesContractResolver(); //Kratos JSchema schema = generator.Generate(typeof(Kratos)); string json = schema.ToString(); System.Diagnostics.Debug.WriteLine(json); //Person schema = generator.Generate(typeof(Person)); json = schema.ToString(); System.Diagnostics.Debug.WriteLine(json); }
public static string ObjectModelToSchema() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(FilteredMappings)); return(schema.ToString()); }
public static void Run(string optionsPath) { var timer = new Stopwatch(); timer.Start(); _options = JsonConvert.DeserializeObject <Options>(File.ReadAllText(optionsPath)); var entryModels = GetModelsFromSource(_options.Source); Console.WriteLine($"Found {entryModels.Count} entry Models."); if (_options.Verbose) { Console.WriteLine($"\t{String.Join(", ", entryModels.Select(i => i.Name))}"); } var implementingModels = new HashSet <Type>(entryModels.SelectMany(GetModelsFromImplementingType)); if (_options.Verbose) { Console.WriteLine($"Found {implementingModels.Count} used Models."); } if (_options.Verbose) { Console.WriteLine($"\t{String.Join(", ", implementingModels.Select(i => i.Name))}"); } var allModels = GetAllModelsToGenerate(implementingModels); Console.WriteLine($"Generating {allModels.Count} Models."); var generator = new JSchemaGenerator(); var schema = new HashSet <JSchema>(allModels.Select(generator.Generate)); File.WriteAllText(_options.Destination, JsonConvert.SerializeObject(schema)); timer.Stop(); Console.WriteLine($"Completed in {timer.ElapsedMilliseconds}ms."); }
public void Generate_Person() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(Person)); string json = schema.ToString(); Tests.StringAssert.AreEqual(@"{ ""id"": ""Person"", ""title"": ""Title!"", ""description"": ""JsonObjectAttribute description!"", ""type"": ""object"", ""properties"": { ""Name"": { ""type"": [ ""string"", ""null"" ] }, ""BirthDate"": { ""type"": ""string"" }, ""LastModified"": { ""type"": ""string"" } }, ""required"": [ ""Name"", ""BirthDate"", ""LastModified"" ] }", json); }
/// <summary> /// Create schema and save file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnGenerateJsonSchema_Click(object sender, EventArgs e) { // Generate Json Schema of Students(= List<StudentSchema>) var generator = new JSchemaGenerator(); generator.GenerationProviders.Add(new StringEnumGenerationProvider()); _studentsSchema = generator.Generate(typeof(List <Student>)); var path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), STUDENTS_SCHEMA_FILE); // Save File to Schema using (var streamWriter = new StreamWriter(path, false, Encoding.UTF8)) { // @ If use JSchema.WriteTo, // @ schema file is without indentation. // @ So used JSchema.ToString and wrote to file. //using ( var writer = new JsonTextWriter( streamWriter ) ) { // _studentsSchema.WriteTo( writer ); //} streamWriter.Write(_studentsSchema.ToString()); } // Update Display richTextBox1.Clear(); richTextBox1.Text = @"Created and Saved Schema."; }
public Task<JSchema> GetSchemaFromTemplateAsync(TemplateInfo template) { // TODO: use async var type = _modelTypeRepository.GetModelTypeFromTemplate(template); var schemaGenerator = new JSchemaGenerator(); return Task.FromResult(schemaGenerator.Generate(type)); }
public void Example() { #region Usage JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(Computer)); //{ // "type": "object", // "properties": { // "DiskIds": { // "type": "array", // "items": { // "type": "string", // }, // "uniqueItems": true // }, // "ScreenIds": { // "type": "array", // "items": { // "type": "string", // }, // "uniqueItems": true // } // } //} #endregion Assert.IsTrue(schema.Properties["DiskIds"].UniqueItems); #if !NET35 Assert.IsTrue(schema.Properties["ScreenIds"].UniqueItems); #endif }
private (ConcreteLoanResult, ConcreteLoanInput) GetLoanInput(string source) { var generator = new JSchemaGenerator { ContractResolver = new CamelCasePropertyNamesContractResolver() }; JSchema schema = generator.Generate(typeof(ConcreteLoanRequest)); JObject jsonObject; try { jsonObject = JObject.Parse(source); } catch { return(ConcreteLoanResult.Error, null); } if (!jsonObject.IsValid(schema) || !Regex.IsMatch(jsonObject["interest"].Value <string>(), @"^[0-9]+(\.[0-9][0-9]?)?\%$")) { return(ConcreteLoanResult.BadFormat, null); } return(ConcreteLoanResult.Ok, JsonConvert.DeserializeObject <ConcreteLoanInput>(source)); }
static void Main(string[] args) { JSchemaGenerator generator = new JSchemaGenerator(); var sschema = generator.Generate(typeof(Dictionary <object, int>)); var s = new Dictionary <int, int>(); s.Add(1, 1); s.Add(2, 2); var json = JsonConvert.SerializeObject(s); Console.ForegroundColor = ConsoleColor.Blue; Console.OutputEncoding = System.Text.Encoding.GetEncoding(28591); Console.WriteLine(json); Console.WriteLine("Ultramarine SchemaBuilder"); Console.ResetColor(); Console.Write(sschema.ToString()); generator.GenerationProviders.Add(new TaskProvider()); var schema = generator.Generate(typeof(Generator)); Console.Write(schema.ToString()); Console.ReadLine(); }
public static void LoadConfiguration(string configFile) { JsonTextReader reader = new JsonTextReader(File.OpenText(configFile)); JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader); JSchemaGenerator generator = new JSchemaGenerator(); validatingReader.Schema = generator.Generate(typeof(ConfigurationJson)); JsonSerializer serializer = new JsonSerializer(); configJson = serializer.Deserialize<ConfigurationJson>(validatingReader); ConfigFileName = configFile; }
public void BasicGeneration() { #region BasicGeneration JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(Person)); //{ // "type": "object", // "properties": { // "Name": { // "type": [ "string", "null" ] // }, // "Age": { "type": "integer" } // }, // "required": [ "Name", "Age" ] //} #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); }
public void Example() { #region Usage JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(Building)); // { // "type": "object", // "properties": { // "Name": { // "type": "string", // "maxLength": 100 // }, // "PhoneNumber": { // "type": "string", // "format": "phone" // }, // "Zone": { // "type": "string", // "enum": [ // "Residential", // "Commercial", // "Industrial" // ] // } // }, // "required": [ // "Name", // "PhoneNumber", // "Zone" // ] // } #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); }
public void IContractResolver() { #region IContractResolver JSchemaGenerator generator = new JSchemaGenerator(); // change contract resolver so property names are camel case generator.ContractResolver = new CamelCasePropertyNamesContractResolver(); JSchema schema = generator.Generate(typeof(Person)); //{ // "type": "object", // "properties": { // "name": { // "type": [ "string", "null" ] // }, // "age": { "type": "integer" } // }, // "required": [ "name", "age" ] //} #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); Assert.AreEqual(true, schema.Properties.ContainsKey("name")); }
public void ReadAsDecimalFailure() { ExceptionAssert.Throws<JSchemaException>(() => { JSchema s = new JSchemaGenerator().Generate(typeof(decimal)); s.MultipleOf = 1; JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"5.5"))) { Schema = s }; reader.ReadAsDecimal(); }, "Float 5.5 is not a multiple of 1. Path '', line 1, position 3."); }
public void ReadAsBytes() { JSchema s = new JSchemaGenerator().Generate(typeof(byte[])); byte[] data = Encoding.UTF8.GetBytes("Hello world"); JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"""" + Convert.ToBase64String(data) + @""""))) { Schema = s }; byte[] bytes = reader.ReadAsBytes(); CollectionAssert.AreEquivalent(data, bytes); }
public void ReadAsBoolean_Failure() { ExceptionAssert.Throws<JSchemaException>(() => { JSchema s = new JSchemaGenerator().Generate(typeof(bool)); s.Enum.Add(new JValue(false)); JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"true"))) { Schema = s }; reader.ReadAsBoolean(); }, "Value true is not defined in enum. Path '', line 1, position 4."); }
public void ReadAsInt32Failure() { ExceptionAssert.Throws<JSchemaException>(() => { JSchema s = new JSchemaGenerator().Generate(typeof(int)); s.Maximum = 2; JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"5"))) { Schema = s }; reader.ReadAsInt32(); }, "Integer 5 exceeds maximum value of 2. Path '', line 1, position 1."); }
public void ReadAsDouble() { JSchema s = new JSchemaGenerator().Generate(typeof(double)); JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"1.0"))) { Schema = s }; double? d = reader.ReadAsDouble(); Assert.AreEqual(1d, d); }
public void ReadAsDoubleFailure() { ExceptionAssert.Throws<JSchemaException>(() => { JSchema s = new JSchemaGenerator().Generate(typeof(double)); s.Maximum = 2; JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"5.0"))) { Schema = s }; reader.ReadAsDouble(); }, "Float 5.0 exceeds maximum value of 2. Path '', line 1, position 3."); }
public void ReadAsDecimal() { JSchema s = new JSchemaGenerator().Generate(typeof(decimal)); JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"1.5"))) { Schema = s }; decimal? d = reader.ReadAsDecimal(); Assert.AreEqual(1.5m, d); }
public void JSchemaGenerationProvider() { #region JSchemaGenerationProvider JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(BuildingReport)); //{ // "type": "object", // "properties": { // "Date": { // "type": "string" // }, // "Zone": { // "type": "integer", // "enum": [ 0, 1, 2 ] // } // }, // "required": [ "Date", "Zone" ] //} // change Zone enum to generate a string property JSchemaGenerator stringEnumGenerator = new JSchemaGenerator(); stringEnumGenerator.GenerationProviders.Add(new StringEnumGenerationProvider()); JSchema stringEnumSchema = stringEnumGenerator.Generate(typeof(BuildingReport)); //{ // "type": "object", // "properties": { // "Date": { // "type": "string" // }, // "Zone": { // "type": "string", // "enum": [ "Residential", "Commercial", "Industrial" ] // } // }, // "required": [ "Date", "Zone" ] //} #endregion Console.WriteLine(stringEnumSchema.ToString()); Assert.AreEqual(JSchemaType.Object, schema.Type); }
public void ReadAsBoolean() { JSchema s = new JSchemaGenerator().Generate(typeof (bool)); JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"true"))) { Schema = s }; bool? b = reader.ReadAsBoolean(); Assert.AreEqual(true, b); }
public static void Compile(FileInfo skinFileInfo, DirectoryInfo steamDirectoryInfo, DirectoryInfo baseDirectoryInfo = null) { if (!FreeImage.IsAvailable()) throw new Exception("FreeImage.dll not found"); if (!skinFileInfo.Exists) throw new Exception("Definition file doesn't exist"); if (!steamDirectoryInfo.Exists) throw new Exception("Steam directory doesn't exist"); Dictionary<string, KeyValue> skinKeyValueList = new Dictionary<string, KeyValue>(); JSchemaGenerator schemaGenerator = new JSchemaGenerator(); JsonTextReader reader = new JsonTextReader(new StringReader(File.ReadAllText(skinFileInfo.FullName))); JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader); validatingReader.Schema = schemaGenerator.Generate(typeof(SkinFile)); SkinFile skinFile = new JsonSerializer().Deserialize<SkinFile>(validatingReader); string skinSourcePath; if (skinFile.metadata.template.skinBase == defaultSkinBaseName) skinSourcePath = steamDirectoryInfo.FullName + "/"; else { string baseDirectory; if (baseDirectoryInfo != null) baseDirectory = baseDirectoryInfo.FullName + "/" + skinFile.metadata.template.skinBase; else baseDirectory = steamDirectoryInfo.FullName + "/" + defaultSkinFolderName + "/" + skinFile.metadata.template.skinBase; skinSourcePath = baseDirectory + "/"; } /// TODO: Make copy of 3rd party skin and use it as a base if (!Directory.Exists(skinSourcePath)) throw new Exception("Skin source '" + skinSourcePath + "' directory doesn't exist"); if (skinFile.files != null) { // iterate through files foreach (KeyValuePair<string, SkinFile.File> f in skinFile.files) { string path = skinSourcePath + f.Key; if (!File.Exists(path)) { StreamWriter writer = File.CreateText(path); writer.WriteLine('"' + f.Key + '"'); writer.WriteLine('{'); writer.WriteLine('}'); writer.Close(); } KeyValue kv = KeyValue.LoadFromString(KeyValue.NormalizeFileContent(path)); if (f.Value.remove is JArray) { foreach (JToken node in f.Value.remove.Children()) RemoveNode(kv, node); } if (f.Value.add is JObject) { foreach (JProperty node in f.Value.add.Children()) kv.Children.Add(CreateNode(kv, node)); } if (f.Value.change is JObject) { // recursively iterate through sections and change all found keys ChangeNode(kv, new JProperty(f.Key, f.Value.change), false); } skinKeyValueList.Add(f.Key, kv); } } //if (skinFile.metadata.folderName == null) throw new Exception("Undefined skin folder name"); string folderName = skinFile.metadata.template.name; if (skinFile.metadata.skin.name != null && skinFile.metadata.skin.author != null) folderName = skinFile.metadata.skin.name + " #" + skinFile.metadata.skin.id; string destinationPath = steamDirectoryInfo.FullName + "/" + defaultSkinFolderName + "/" + folderName; try { if (Directory.Exists(destinationPath)) { if (backupEnabled) { string backupDirectoryName = destinationPath + " - Backup (" + DateTime.Now.ToString("yyyyMMddHHmmss") + ")"; if (Directory.Exists(backupDirectoryName)) Directory.Delete(backupDirectoryName, true); Directory.Move(destinationPath, backupDirectoryName); } else Directory.Delete(destinationPath, true); } Directory.CreateDirectory(destinationPath); /// NOTE: Copy base directory prior to writing modified files if (skinFile.metadata.template.skinBase != defaultSkinBaseName) DirectoryCopy(skinSourcePath, destinationPath, true); foreach (KeyValuePair<string, KeyValue> kv in skinKeyValueList) { if (Directory.CreateDirectory(destinationPath + "/" + Path.GetDirectoryName(kv.Key)).Exists) kv.Value.SaveToFile(destinationPath + "/" + kv.Key, false); } } catch (Exception e) { throw e; } if (skinFile.attachments != null) { foreach (SkinFile.Attachment attachment in skinFile.attachments) { string type = (attachment.type != null) ? attachment.type : "image"; switch (type.ToLower()) { case "image": { using (Base64Image image = new Base64Image(attachment.data)) { string graphicsDirPath = destinationPath + "/" + Path.GetDirectoryName(attachment.path); string extension = Path.GetExtension(attachment.path); if (extension.Length == 0) extension = "tga"; else extension = extension.Substring(1); if (!Directory.Exists(graphicsDirPath)) Directory.CreateDirectory(graphicsDirPath); if (attachment.filters != null) image.ApplyFilters(attachment.filters); if (attachment.spritesheet == null) { if (attachment.transform != null) image.Transform(attachment.transform); image.Save(graphicsDirPath + "/" + Path.GetFileNameWithoutExtension(attachment.path) + "." + extension); } else // has defined spritesheet { string spritePath, finalPath = null; foreach (KeyValuePair<int, int[]> spriteDefinition in attachment.spritesheet) { if (spriteDefinition.Value.Length == 4) { if (attachment.spritesheetFiles.TryGetValue(spriteDefinition.Key, out spritePath)) { string dir = destinationPath + "/" + Path.GetDirectoryName(spritePath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); finalPath = dir + "/" + Path.GetFileNameWithoutExtension(spritePath) + "." + extension; } else finalPath = graphicsDirPath + "/" + Path.GetFileNameWithoutExtension(attachment.path) + spriteDefinition.Key + "." + extension; if (finalPath != null) image.SaveSprite(finalPath, spriteDefinition.Value); } } } } break; } } } } // write metadata //string iniTemplateSection = "Template", // iniSkinSection = "Skin"; Ini.IniFile metadataIni = new Ini.IniFile(destinationPath + "/metadata.ini"); foreach (PropertyInfo metadata in skinFile.metadata.GetType().GetProperties()) { char[] arr = metadata.Name.ToCharArray(); arr[0] = char.ToUpperInvariant(arr[0]); string sectionName = new string(arr); PropertyInfo sectionInfo = skinFile.metadata.GetType().GetProperty(metadata.Name); if (sectionInfo != null) { object section = sectionInfo.GetValue(skinFile.metadata, null); foreach (PropertyInfo property in section.GetType().GetProperties()) { arr = property.Name.ToCharArray(); arr[0] = char.ToUpperInvariant(arr[0]); string propertyName = new string(arr); object val = property.GetValue(section, null); string propertyValue = (val == null) ? "" : property.GetValue(section, null).ToString(); switch (property.Name) { case "revision": { if (Convert.ToInt32(propertyValue) > 0) metadataIni.IniWriteValue(sectionName, propertyName, propertyValue); break; } case "primaryColor": case "primaryTextColor": case "accentColor": case "accentTextColor": { if (propertyValue.Length > 0) metadataIni.IniWriteValue(sectionName, propertyName, "0x" + propertyValue); break; } case "thumbnail": { try { string fileName = "thumb.jpg"; using (Base64Image image = new Base64Image(propertyValue)) { if (image.Save(destinationPath + "/" + fileName, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB)) metadataIni.IniWriteValue(sectionName, propertyName, fileName); } } catch { } break; } default: { if (propertyValue.Length > 0) metadataIni.IniWriteValue(sectionName, propertyName, propertyValue); break; } } } } //Console.WriteLine(skinFile.metadata.GetType().GetProperty(metadata.Name).Name); /* foreach (PropertyInfo field in skinFile.metadata.GetType().GetField(metadata.Name).GetType().GetProperties()) { Console.WriteLine(field); } */ } /* metadataIni.IniWriteValue(iniTemplateSection, "Version", skinFile.metadata.template); metadataIni.IniWriteValue(iniTemplateSection, "Name", skinFile.metadata.name); metadataIni.IniWriteValue(iniTemplateSection, "Author", skinFile.metadata.author); metadataIni.IniWriteValue(iniTemplateSection, "AuthorUrl", skinFile.metadata.authorUrl != null ? skinFile.metadata.authorUrl : ""); metadataIni.IniWriteValue(iniTemplateSection, "SkinURL", skinFile.metadata.skinURL != null ? skinFile.metadata.skinURL : ""); metadataIni.IniWriteValue(iniTemplateSection, "Description", skinFile.metadata.description != null ? skinFile.metadata.description : ""); metadataIni.IniWriteValue(iniTemplateSection, "Color", skinFile.metadata.color != null ? skinFile.metadata.color : "0x1E1E1E"); */ // activate skin File.Delete(steamDirectoryInfo.FullName + "/" + defaultSkinFolderName + "/.active"); if (activateSkin) File.WriteAllText(steamDirectoryInfo.FullName + "/" + defaultSkinFolderName + "/.active", folderName); // print debug if (debugMode) { string buffer = ""; buffer += "Steam Customizer compiler debug log @ " + DateTime.Now.ToString() + "\r\n"; buffer += "Schema list:\r\n"; foreach (Type t in new Type[] { typeof(SkinFile) }) { buffer += "\r\n" + t.ToString() + ":\r\n"; buffer += schemaGenerator.Generate(t).ToString(); buffer += "\r\n"; } File.WriteAllText("debug.log", buffer); } }
public void ReadAsInt32() { JSchema s = new JSchemaGenerator().Generate(typeof(int)); JsonReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(@"1"))) { Schema = s }; int? i = reader.ReadAsInt32(); Assert.AreEqual(1, i); }
private static string GetOrSaveSchemaReference(Type type) { string key = type.FullName; if (SchemaCache.Cache.ContainsKey(key)) { return key; } JSchemaGenerator generator = new JSchemaGenerator { SchemaIdGenerationHandling = SchemaIdGenerationHandling.FullTypeName, SchemaReferenceHandling = SchemaReferenceHandling.None }; JSchema schema = generator.Generate(type); // I didn't find the way how to disallow JSchemaGenerator to use nullable types, swagger doesn't work with them string tmp = schema.ToString(); string s = @"\""type\"":[\s\n\r]*\[[\s\n\r]*\""(\w+)\"",[\s\n\r]*\""null\""[\s\n\r]*\]"; tmp = Regex.Replace(tmp, s, "\"type\": \"$1\""); SchemaCache.Cache[key] = JSchema.Parse(tmp); return key; }