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 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 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 static List <CLRCIDefinition> StripLogsFromFile(string inputPath) { Debug.Assert(File.Exists(inputPath)); var fullDefs = new List <HelixTestDefinition>(); var strippedDefs = new List <CLRCIDefinition>(); JSchemaGenerator jsonGenerator = new JSchemaGenerator(); JSchema testDefinitionSchema = jsonGenerator.Generate(typeof(IList <HelixTestDefinition>)); var validationMessages = new List <string>(); using (var sr = new StreamReader(inputPath)) using (var jsonReader = new JsonTextReader(sr)) using (var jsonValidationReader = new JSchemaValidatingReader(jsonReader)) { // Create schema validator jsonValidationReader.Schema = testDefinitionSchema; jsonValidationReader.ValidationEventHandler += (o, a) => validationMessages.Add(a.Message); JsonSerializer serializer = new JsonSerializer(); fullDefs = serializer.Deserialize <List <HelixTestDefinition> >(jsonValidationReader); } return(MinifyDefList(fullDefs)); }
/// <summary> /// Validate the received JSON string against the our object structure. If it's valid /// then create and populate the <see cref="Owner"/> and <see cref="Pet"/> objects. /// </summary> /// <param name="jsonString">Received JSON string.</param> /// <exception cref="System.Exception">Thrown if the response is invalid JSON or mandatory data is missing.</exception> /// <returns>List of <see cref="Owner"/> objects.</returns> private List <Owner> ValidateAndParseResponse(string jsonString) { var generator = new JSchemaGenerator(); var parsedSchema = generator.Generate(typeof(List <Owner>)); var reader = new JsonTextReader(new StringReader(jsonString)); var validatingReader = new JSchemaValidatingReader(reader) { Schema = parsedSchema }; var messages = new List <string>(); validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message); try { JsonSerializer serializer = new JsonSerializer(); var owners = serializer.Deserialize <List <Owner> >(validatingReader); if (messages.Count > 0) { var exception = new Exception("Invalid Response : Missing Mandatory Data"); exception.Data.Add("ValidationErrors", messages); throw exception; } return(owners); } catch (JsonReaderException ex) { throw new Exception("Invalid Response : Invalid Json", ex); } }
public static JSchema CreateSchema(Type type) { var generator = new JSchemaGenerator(); var schema = generator.Generate(type); return(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)); }
private string GetJsonSchema() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(ProductType)); return(schema.ToString()); }
public static string GetClassSchema(Type t) { var generator = new JSchemaGenerator(); var schema = generator.Generate(t); var json = GetJSchema(schema); return(json); }
/// <summary> /// Templorary helper method used to generate validation schema. Can be expanded with setting and re-used. Ideally on runtime. /// </summary> private void GenerateSchemaForInput() { JSchemaGenerator generator = new JSchemaGenerator(); generator.DefaultRequired = Required.AllowNull; generator.ContractResolver = new CamelCasePropertyNamesContractResolver(); JSchema jSchema = generator.Generate(typeof(Drug)); }
static void Main(string[] args) { var api = new API(); JSchemaGenerator generator = new JSchemaGenerator(); JSchema schemaCust = generator.Generate(typeof(Customer)); JSchema schemaInv = generator.Generate(typeof(SalesInvoiceLine)); JSchema schemaReceipt = generator.Generate(typeof(Sage50Connector.Models.Data.Receipt)); Sage.Peachtree.API.Vendor v; var companies = api.CompaniesList(); //var companyId = companies.SingleOrDefault(c => c.CompanyName == "Chase Ridge Holdings"); api.OpenCompany(companies[1]); var list = api.PaymentList(); list.Load(); var r_list = api.ReceiptList(); r_list.Load(); var i_list = api.InvoicesList(); i_list.Load(); foreach (var item in list) { System.Console.WriteLine("At: {0}", item.LastSavedAt); } System.Console.WriteLine("Count: {0}", list.Count); list.ListChanged += (sender, eventArgs) => { Debugger.Launch(); }; dynamic actionsJson = JsonConvert.DeserializeObject("[{\"_id\": \"5a3b9a673f04681b7b3e9eb9\",\"source\": \"Qualer\",\"type\": \"UpsertInvoice\",\"payload\": {\"invoice\": {\"grandTotal\": 330.5,\"customer\": {\"name\": \"Southeastern Freight Lines (Tpa)\",\"externalId\": \"4274\",\"phoneNumbers\": null,\"shipToContact\": {\"email\": \"\",\"address\": {\"zip\": 28804,\"country\": \"United States\",\"state\": \"NC\",\"address1\": \"275 Aiken Road\",\"city\": \"Asheville\",\"address2\": \"\"},\"lastName\": \"\",\"firstName\": \"\",\"phoneNumbers\": [{\"key\": \"PhoneNumber1\",\"number\": \"828-658-2711\"}],\"companyName\": \"Southeastern Freight Lines (Tpa)\"},\"billToContact\": {\"email\": \"\",\"address\": {\"zip\": 28804,\"country\": \"United States\",\"state\": \"NC\",\"address1\": \"275 Aiken Road\",\"city\": \"Asheville\",\"address2\": \"\"},\"lastName\": \"\",\"firstName\": \"\",\"phoneNumbers\": [{\"key\": \"PhoneNumber1\",\"number\": \"828-658-2711\"}],\"companyName\": \"Southeastern Freight Lines (Tpa)\"}},\"date\": \"2017-10-06T12:53:47.67\",\"referenceNumber\": \"173929\",\"dateDue\": \"2017-10-24T00:00:00\",\"shipToAddress\": {\"address\": {\"zip\": 28804,\"country\": \"United States\",\"state\": \"NC\",\"address1\": \"275 Aiken Road\",\"city\": \"Asheville\",\"address2\": null}},\"shippingFee\": null,\"salesLines\": [{\"description\": \"The new scale was calibrated and tested.\nAll test are in tolerance.\nNew Scale, No As Found Data 10-9-17\",\"amount\": 330,\"unitPrice\": 330,\"quantity\": 1,\"salesTaxType\": 1}]},\"CompanyName\": \"Southeastern Freight Lines (Tpa)\"},\"mainLogId\": \"5a3b99cc38e9a4000fab2e8b\",\"userId\": 1281,\"triggerId\": \"5a2911e7ceb87200047c046a\",\"clientId\": \"greenville-scale-sage-1\",\"createdAt\": \"2017-12-21T11:20:10.363Z\",\"processed\": false}]"); var strings = (actionsJson.Root as Newtonsoft.Json.Linq.JArray)?.Select(i => i.ToString()).ToArray()[0]; var action = new Sage50Connector.Processing.Actions.SageActions.Factory.SageActionFromJsonFactory().Create(strings); new UpsertInvoiceSageActionHandler().Handle((UpsertInvoiceSageAction)action); }
public IActionResult GetSchema() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(AggrConfig)); return(Json(schema.ToString())); }
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 SchemaFileMatchesModel() { var generator = new JSchemaGenerator(); var schemaFromModel = generator.Generate(typeof(Component)); var schemaFromFile = JSchema.Parse(Encoding.UTF8.GetString(FileResources.Schema)); Assert.AreEqual(schemaFromModel.ToString(), schemaFromFile.ToString()); }
private bool IsValidCharacterJson(JObject characterJson, out IList <string> messages) { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(CharacterViewModel)); // IList<string> messages; return(characterJson.IsValid(schema, out messages)); }
public void Generate_UserNullable() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(UserNullable)); string json = schema.ToString(); Tests.StringAssert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""Id"": { ""type"": ""string"" }, ""FName"": { ""type"": [ ""string"", ""null"" ] }, ""LName"": { ""type"": [ ""string"", ""null"" ] }, ""RoleId"": { ""type"": ""integer"" }, ""NullableRoleId"": { ""type"": [ ""integer"", ""null"" ] }, ""NullRoleId"": { ""type"": [ ""integer"", ""null"" ] }, ""Active"": { ""type"": [ ""boolean"", ""null"" ] } }, ""required"": [ ""Id"", ""FName"", ""LName"", ""RoleId"", ""NullableRoleId"", ""NullRoleId"", ""Active"" ] }", json); }
/// <summary> /// Generate a JSON schema from the C# model instance type /// </summary> /// <param name="modelType">Type of the C# model instance</param> /// <returns><see cref="GenerationResult"/></returns> public static GenerationResult Generate(Type modelType) { var schemaAttribute = modelType.GetCustomAttribute <ConiziSchemaAttribute>(); if (schemaAttribute == null) { throw new InvalidOperationException("Class is no valid conizi model!"); } var generator = new JSchemaGenerator { DefaultRequired = Newtonsoft.Json.Required.DisallowNull, SchemaIdGenerationHandling = SchemaIdGenerationHandling.None, SchemaReferenceHandling = SchemaReferenceHandling.Objects, SchemaPropertyOrderHandling = SchemaPropertyOrderHandling.Default, SchemaLocationHandling = SchemaLocationHandling.Definitions, ContractResolver = new ConiziDefaultResolver() }; generator.GenerationProviders.Add(new ConiziDefaultGenerationProvider()); generator.GenerationProviders.Add(new StringEnumGenerationProvider()); JSchema schema = generator.Generate(modelType); schema.SchemaVersion = new Uri("http://json-schema.org/draft-07/schema#"); var baseUri = "https://model.conizi.io/"; // Get model shortcut from model id var model = Regex.Replace(schemaAttribute.Id, baseUri + "(v([0-9]|\\.)+/)|(\\.json)", String.Empty); if (string.IsNullOrEmpty(model)) { throw new InvalidOperationException($"Model could not be extracted from {schemaAttribute.Id}!"); } var match = Regex.Match(schemaAttribute.Id, "(?<version>(v([0-9]|[0-9]\\.)+))"); var version = match.Groups["version"]?.Value; if (string.IsNullOrEmpty(version)) { throw new InvalidOperationException($"Version could not be extracted from {schemaAttribute.Id}!"); } var result = new GenerationResult { Id = schemaAttribute.Id, Title = schema.Title, Description = schema.Description, Model = model, JSchema = schema, File = schemaAttribute.FileName, Version = version }; return(result); }
private static void LoadData() { string json; JObject jsobj; JSchemaGenerator generator; JSchema schema; json = File.ReadAllText(ConfigFile); Config config = new Config(); config = JsonConvert.DeserializeObject <Config>(json); CurProfileName = config.CurProfileName; // Load profiles List <string> files = Directory.GetFiles(ProfileDir, "*.spprofile").ToList <string>(); foreach (string s in files) { try { json = File.ReadAllText(s); jsobj = JObject.Parse(json); generator = new JSchemaGenerator(); schema = generator.Generate(typeof(Profile)); if (jsobj.IsValid(schema)) { Profile newProfile = new Profile(Path.GetFileNameWithoutExtension(s)); newProfile = JsonConvert.DeserializeObject <Profile>(json); Console.WriteLine(json); Console.WriteLine("\n"); Profiles.Add(newProfile); } } catch (Exception) {} } // Load last opened profile Profile prof = Profiles.Find(p => p.Name == CurProfileName); if (prof != null) { CurProfile = prof; } else { config.CurProfileName = "Default"; CurProfileName = "Default"; if (Profiles.Find(p => p.Name == "Default") != null) { CurProfile = Profiles.Find(p => p.Name == "Default"); } else { MessageBox.Show("Can't find any profile.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(1); } } }
private static void Main(string[] args) { if (args is null) { throw new ArgumentNullException(nameof(args)); } TableCollection tc = new TableCollection(); tc.tables.Add(new Table() { a = 1 }); tc.tables.Add(new Table() { a = 2 }); var xmlSerializer = new XmlSerializer(tc.tables.GetType()); var str = new StringBuilder(); xmlSerializer.Serialize(new StringWriter(str), tc.tables); var xml = str.ToString(); File.WriteAllText("tables.xml", xml); Console.WriteLine("xml----------\n" + xml); string json = JsonConvert.SerializeObject(tc.tables); File.WriteAllText("tables.json", json); Console.WriteLine("json----------\n" + json); //XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json); //doc.Save("tables.xml"); //string json2 = JsonConvert.SerializeXmlNode(doc); //Console.WriteLine("json2----------\n" + json2); JSchemaGenerator gen = new JSchemaGenerator(); JSchema schema = gen.Generate(typeof(TableCollection)); using (StreamWriter sw = new StreamWriter("tables.schema")) { using (JsonWriter writer = new JsonTextWriter(sw)) { schema.WriteTo(writer); } } Console.WriteLine("tables.schema----------\n" + schema.ToString()); Console.WriteLine("Hello World!"); }
public static string GenerateSchema <TObject>() where TObject : class { // Generate schema JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(TObject)); string jSchema = schema.ToString(); return(jSchema); }
public override string Format(object input) { dynamic inp = input; var res = inp.result; JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(res.GetType()); return(schema.ToString()); }
/// <summary> /// Generates the schema. /// </summary> /// <param name="configuration">The configuration.</param> /// <returns></returns> public string GenerateSchema(IConfiguration configuration) { var generator = new JSchemaGenerator(); var schema = generator.Generate(typeof(Configuration), false); schema.Title = typeof(Configuration).Name; return(schema.ToString()); }
public async Task <CompanyData> InsertCompanyIntoDb(CompanyData company) { //Number of pages company.CompanyState = CompanyState.Processing; await _dbContext.SaveChangesAsync(); var counter = 1; var page = await _browsingContextService.OpenPageAsync(company.Url.Replace(".html", $";{counter}.html")); //Get all pages for current company while (page.Url != company.Url || counter == 1) { var products = CompanyParsingService.ParseCompanyProducts(company, page).ToArray(); company.Products.AddRange(products); await TaskQueue.QueueBackgroundWorkItemsRangeAsync(products); _logger.LogInformation($"CompanyService new products of {company.Name} company, data-chunk was added"); counter++; Thread.Sleep(5000); page = await _browsingContextService.OpenPageAsync(company.Url.Replace(".html", $";{counter}.html")); if (page != null) { continue; } company.CompanyState = CompanyState.Failed; await _dbContext.SaveChangesAsync(); return(company); } company.CompanyState = CompanyState.Success; company.SyncDate = DateTime.Now; var jsonCompanyDat = new CompanyJson { ExternalId = company.ExternalId, PortalPageUrl = company.Url, SyncDate = company.SyncDate, Name = company.Name }; var generator = new JSchemaGenerator(); var fullCategorySchema = generator.Generate(typeof(CompanyJson)).ToString(); var fullCategoryJson = JsonConvert.SerializeObject(jsonCompanyDat); company.JsonData = fullCategoryJson; company.JsonDataSchema = fullCategorySchema; await _dbContext.SaveChangesAsync(); return(company); }
private async void GenerateSchema(MainWindow mainWindow) { void ShowError() { _windowService.ShowDialogWindow(mainWindow, new DialogViewModel() { Title = "Class not found", MessageText = "Please provide a valid C# class", ButtonText = "OK", }); } try { if (string.IsNullOrWhiteSpace(Class)) { ShowError(); return; } var matches = Regex.Matches(Class, ClassRegex, RegexOptions.Multiline); if (matches.Count == 1) { var firstMatch = matches[0]; if (firstMatch.Groups.Count >= 2) { var className = firstMatch.Groups[1]; var classType = await CSharpScript.EvaluateAsync <Type>(Class + $" return typeof({className});", ScriptOptions.Default .WithReferences(typeof(System.ComponentModel.DataAnnotations.RequiredAttribute).Assembly) .WithImports("System.Collections.Generic", "System.ComponentModel.DataAnnotations") ); var generator = new JSchemaGenerator(); var schema = generator.Generate(classType); Schema = schema.ToString(); } else { ShowError(); } } else { ShowError(); } } catch (Exception e) { _windowService.ShowDialogWindow(mainWindow, new DialogViewModel() { Title = "Error", MessageText = e.ToString(), ButtonText = "OK", }); } }
public MarketPlaceHeadersHandler(MarketPlaceHttpHeaders marketPlaceHttpHeaders) { JSchemaGenerator generator = new JSchemaGenerator(); _schema = generator.Generate(typeof(MarketPlaceError)); _marketPlaceHttpHeaders = marketPlaceHttpHeaders; InnerHandler = new HttpClientHandler(); }
internal static T TryParse <T>(string jsonData) where T : new() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema parsedSchema = generator.Generate(typeof(T)); JObject jObject = JObject.Parse(jsonData); return(jObject.IsValid(parsedSchema) ? JsonConvert.DeserializeObject <T>(jsonData) : default(T)); }
public void GetJSON() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(JobListingEntity)); Console.WriteLine(schema.ToString()); Assert.IsTrue(true); }
public override JSchema GetSchema(JSchemaTypeGenerationContext context) { var generator = new JSchemaGenerator(); var schema = generator.Generate(context.ObjectType); schema.Properties["Path"].Pattern = @"(\b\.)+"; return(schema); }
public void Test() { JSchemaGenerator generator = new JSchemaGenerator(); JSchema s = generator.Generate(typeof(HttpBrokeredMessage)); Assert.AreEqual(null, s.Properties[nameof(HttpBrokeredMessage.BrokerProperties)].AdditionalProperties.Type); Assert.AreEqual(null, s.Properties[nameof(HttpBrokeredMessage.UserProperties)].AdditionalProperties.Type); }
private JSchema CreateSchemaWithFormat(Type type, Required required, string format) { var generator = new JSchemaGenerator(); var schema = generator.Generate(type, required != Required.Always); schema.Format = format; return(schema); }
private JSchema createSchemaForType(Type snapshotType) { var generator = new JSchemaGenerator { DefaultRequired = Required.Default }; generator.GenerationProviders.Add(new StringEnumGenerationProvider()); return(generator.Generate(snapshotType)); }
public static bool CanBeConverted <T>(this object value) where T : class { var jsonData = JsonConvert.SerializeObject(value); var generator = new JSchemaGenerator(); var parsedSchema = generator.Generate(typeof(T)); var jObject = JObject.Parse(jsonData); return(jObject.IsValid(parsedSchema)); }
public void Run() { JSchema schema = generator.Generate(typeof(TestClass)); JsonTextReader reader = new JsonTextReader(new System.IO.StringReader("{field: 2}")); JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader); validatingReader.Schema = schema; TestClass res = serializer.Deserialize <TestClass>(validatingReader); }
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 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 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); }
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 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 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); }