private static void ValidateSchema(SchemaValidationInfo validationInfo) { try { object entity = AutoFixture.Create(validationInfo.DataType); if (!File.Exists(validationInfo.SchemaFilePath)) { Assert.Fail($"Json Schema not found for type '{validationInfo.DataType.FullName}'.\n" + $"Expected to find file: {validationInfo.SchemaFilePath}"); } var schema = JsonSchema.FromFileAsync(validationInfo.SchemaFilePath).GetAwaiter().GetResult(); var json = JsonConvert.SerializeObject( entity, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); ICollection <ValidationError> errors = schema.Validate(json); Assert.IsTrue(errors.Count == 0, $"Json Schema validation failed for type '{validationInfo.DataType.FullName}'.\n" + $"Found {errors.Count} error(s). See schema file: {validationInfo.SchemaFilePath}"); } catch (Exception e) { Assert.Fail($"Error {validationInfo.DataType}: {e.Message}"); throw; } }
public async Task LoadRolesFromJsonAsync(string json) { IDictionary <string, Category> categories = await db.Categories.ToDictionaryAsync(x => x.Name); IDictionary <string, OperationKey> operationKeys = await db.OperationKeys.ToDictionaryAsync(x => x.Name); JsonSchema schema = await JsonSchema.FromFileAsync(RolesSchemaPath); RolesFromJsonLoader rolesFromJsonLoader = new RolesFromJsonLoader(categories, operationKeys, schema); rolesFromJsonLoader.Seed(json); try { db.BeginTransaction(); await UpdateRoles(rolesFromJsonLoader.roles); await ClearAccessesAsync(); await CopyToDb(rolesFromJsonLoader); db.CommitTransaction(); } catch (Exception e) { db.RollbackTransaction(); throw e; } }
static async Task Main(string[] args) { jsonBasepath = Path.GetFullPath("json"); var jsonDirs = Directory.GetDirectories(jsonBasepath); animation = JObject.Parse(File.ReadAllText("json\\animation.json")); animation["definitions"] = new JObject(); foreach (var dir in jsonDirs) { readDirectory(dir); } var json = animation.ToString(); foreach (JProperty definition in animation["definitions"]) { json = json.Replace(definition.Value["$id"].Value <string>(), $"#/definitions/{definition.Name}"); } File.WriteAllText(@"asdasd.json", json); var schema = await JsonSchema.FromFileAsync("asdasd.json"); var generator = new CSharpGenerator(schema); var file = generator.GenerateFile(); File.WriteAllText("generated.cs", file); }
private static bool ValidateJsonConfig(ILogger log, string configAsText) { if (!File.Exists(ConfigSchemaJsonLocation)) { log.Warning("JSON Schema not found -- skipping config validation."); return(true); } var result = JsonSchema.FromFileAsync(ConfigSchemaJsonLocation) .Result.Validate(configAsText); if (!result.Any()) { log.Information("Provided config passed validation without errors."); return(true); } log.Error("Validation of config failed against schema:"); foreach (var error in result) { log.Error(error.ToString()); } return(false); }
/// <summary> /// Prepare a JSON schema. /// </summary> protected override void BeginProcessing() { string resolvedpath = string.Empty; try { if (Schema != null) { try { _jschema = JsonSchema.FromJsonAsync(Schema).Result; } catch (AggregateException ae) { // Even if only one exception is thrown, it is still wrapped in an AggregateException exception // https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library ae.Handle(UnwrapException); } } else if (SchemaFile != null) { try { resolvedpath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(SchemaFile); _jschema = JsonSchema.FromFileAsync(resolvedpath).Result; } catch (AggregateException ae) { ae.Handle(UnwrapException); } } } catch (Exception e) when( // Handle exceptions related to file access to provide more specific error message // https://docs.microsoft.com/en-us/dotnet/standard/io/handling-io-errors e is IOException || e is UnauthorizedAccessException || e is NotSupportedException || e is SecurityException ) { Exception exception = new( string.Format( CultureInfo.CurrentUICulture, TestJsonCmdletStrings.JsonSchemaFileOpenFailure, resolvedpath), e); ThrowTerminatingError(new ErrorRecord(exception, "JsonSchemaFileOpenFailure", ErrorCategory.OpenError, resolvedpath)); } catch (Exception e) { Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); ThrowTerminatingError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, resolvedpath)); } }
static void Main(string[] args) { string json = "{\"tool\": [{\"Id\": 1,\"Code\": 1,\"Description\": \"Mill D.5 Pos.11\",\"DateLoaded\": \"2021-06-07T11:35:09.75425Z\",\"DateReplaced\": \"\",\"CurrentLife\": 476.0,\"ExpectedLife\": 360000.0},{\"Id\": 2,\"Code\": 2,\"Description\": \"Mill D.8 Pos.12\",\"DateLoaded\": \"2021-06-07T11:35:10.75425Z\",\"DateReplaced\": \"\",\"CurrentLife\": 911.0,\"ExpectedLife\": 360000.0}]"; json += ",\"info\": [{\"KeyId\": \"2021563044\",\"MachineSerial\": \"B0900001\",\"MachineCode\": 211,\"Product\": \"FSTLine4\",\"ProductVersion\": \"4.2.0.198\",\"FirmwareVersion\": \"1.7.2 - 8/11/2019\",\"PlcVersion\": \"1.6.3.0\",\"LoginDate\": \"2021-06-07T11:35:09.75425Z\",\"UTC\": 0}]}"; var schemaDataTool = JsonSchema.FromFileAsync(Path.Combine("C:\\JsonSchemas", "tool.json")).Result; var errorTool = schemaDataTool.Validate(json); }
/// <summary>Creates a new <see cref="JsonDocumentModel"/> based on a given schema file path. </summary> /// <param name="schemaPath">The schema file path. </param> /// <param name="dispatcher">The UI dispatcher. </param> /// <returns>The <see cref="JsonDocumentModel"/>. </returns> public static Task <JsonDocumentModel> CreateAsync(string schemaPath, IDispatcher dispatcher) { return(Task.Run(() => { var schema = JsonSchema.FromFileAsync(schemaPath).GetAwaiter().GetResult(); var data = JsonObjectModel.FromSchema(schema); var document = new JsonDocumentModel(); document.Initialize(data, dispatcher); return document; })); }
public async Task When_schema_references_external_schema_placed_in_directory_with_sharp_in_name() { //// Arrange var path = GetTestDirectory() + "/References/LocalReferencesTests/dir_with_#/first.json"; //// Act var schema = await JsonSchema.FromFileAsync(path); var json = schema.ToJson(); //// Assert Assert.Equal(JsonObjectType.Integer, schema.ActualTypeSchema.Type); }
public async Task When_document_has_indirect_external_ref_than_it_is_loaded() { //// Arrange var path = GetTestDirectory() + "/References/LocalReferencesTests/schema_with_indirect_reference.json"; //// Act var schema = await JsonSchema.FromFileAsync(path); var json = schema.ToJson(); //// Assert Assert.Equal(1, schema.Definitions.Count); }
private static async Task <(string name, string file)> GenerateSourceFromSchemaFileAsync(string path, string @namespace) { var name = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(path)); var schema = await JsonSchema.FromFileAsync(path); var settings = new CSharpGeneratorSettings { Namespace = @namespace }; var fileGenerator = new CSharpGenerator(schema, settings); string file = fileGenerator.GenerateFile(name); return(name, file); }
public override async Task <bool> Execute(GenerateInput input) { var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, Namespace = input.NamespaceFlag }; var codeDirectory = input.OutputDirectory.ToFullPath(); var system = new FileSystem(); if (!system.DirectoryExists(codeDirectory)) { Console.WriteLine("Creating directory " + codeDirectory); system.CreateDirectory(codeDirectory); } var files = system.FindFiles(input.SchemaDirectory, FileSet.Shallow("*.json")); var messages = files.Select(x => new GeneratedMessage(x)).ToArray(); var writer = new SourceWriter(); writer.Namespace(input.NamespaceFlag); foreach (var message in messages) { var schema = await JsonSchema.FromFileAsync(message.FilePath); var generator = new CSharpGenerator(schema, settings); var contents = generator.GenerateFile(message.ClassName); var codeFile = codeDirectory.AppendPath(message.ClassName + ".cs"); Console.WriteLine(codeFile); system.WriteStringToFile(codeFile, contents); message.WriteAnnotations(writer); } writer.FinishBlock(); var annotationFile = codeDirectory.AppendPath("MessageAnnotations.cs"); Console.WriteLine("Writing attribute annotations to " + annotationFile); system.WriteStringToFile(annotationFile, writer.Code()); return(true); }
/// <summary>Loads a <see cref="JsonDocumentModel"/> from a file path and schema path. </summary> /// <param name="filePath">The file path. </param> /// <param name="schemaPath">The schema path. </param> /// <param name="dispatcher">The UI dispatcher. </param> /// <returns>The <see cref="JsonDocumentModel"/>. </returns> public static Task <JsonDocumentModel> LoadAsync(string filePath, string schemaPath, IDispatcher dispatcher) { return(Task.Run(() => { var schema = JsonSchema.FromFileAsync(schemaPath).GetAwaiter().GetResult(); var data = JsonObjectModel.FromJson(File.ReadAllText(filePath, Encoding.UTF8), schema); var document = new JsonDocumentModel(); document.Initialize(data, dispatcher); document.FilePath = filePath; document.SchemaPath = schemaPath; return document; })); }
public async Task When_schema_references_external_schema_then_it_is_inlined_with_ToJson() { //// Arrange var path = GetTestDirectory() + "/References/LocalReferencesTests/schema_with_reference.json"; //// Act var schema = await JsonSchema.FromFileAsync(path); var json = schema.ToJson(); //// Assert Assert.True(schema.Definitions.ContainsKey("Animal")); Assert.Contains("\"$ref\": \"#/definitions/Animal\"", json); }
public async Task When_schema_references_collection_in_definitions_it_works() { //// Arrange var path = GetTestDirectory() + "/References/LocalReferencesTests/schema_with_collection_reference.json"; //// Act var schema = await JsonSchema.FromFileAsync(path); var json = schema.ToJson(); //// Assert Assert.Equal(JsonObjectType.Integer, schema.Properties["foo"].ActualTypeSchema.Type); Assert.Equal(1, schema.Definitions.Count); Assert.Equal("./collection.json", schema.Definitions["collection"].DocumentPath); }
private static async Task <GeneratedSchema> GenerateSchema(string path, string @namespace, CancellationToken cancellationToken) { var name = Path.GetFileNameWithoutExtension(path).Split('.')[0]; var generator = new CSharpGenerator(await JsonSchema.FromFileAsync(path, cancellationToken), new() { Namespace = @namespace, ClassStyle = CSharpClassStyle.Poco, SchemaType = SchemaType.JsonSchema, JsonLibrary = CSharpJsonLibrary.SystemTextJson, ArrayType = "System.Collections.Immutable.ImmutableArray", ArrayInstanceType = "System.Collections.Immutable.ImmutableArray" }); return(new(name, generator.GenerateFile(name))); }
public async Task When_ref_is_file_no_types_are_duplicated() { //// Arrange var path = GetTestDirectory() + "/References/A.json"; //// Act var schema = await JsonSchema.FromFileAsync(path); var generator = new CSharpGenerator(schema); //// Act var code = generator.GenerateFile("MyClass"); //// Assert Assert.Contains("public enum C", code); Assert.DoesNotContain("public enum C2", code); }
/// <summary> /// Loads the schema for the given specification id. Downloads the schema if it not already downloaded. /// </summary> /// <param name="specificationId"></param> /// <returns> /// The schema for the specification id. /// </returns> /// <exception cref="FileNotFoundException"> /// The given specification id does not exist /// </exception> public async Task <JsonSchema> LoadSchemaAsync(string specificationId) { var path = Path.Combine(_directory, specificationId); if (!File.Exists(path)) { throw new FileNotFoundException($"'{specificationId}' does not exist at {path}", path); } try { return(await JsonSchema.FromFileAsync(path).ConfigureAwait(false)); } catch (Exception e) { throw new JsonSchemaException($"Cannot load schema from path {path}, {e.Message}", e); } }
/// <summary> /// Loads configuration data from a JSON file located at <see cref="CONFIG_FILE"/>. /// </summary> /// <exception cref="ConfigurationSchemaException"> /// Thrown if the configuration data does not conform to the required schema. /// </exception> public async Task LoadAsync() { string json = File.ReadAllText(CONFIG_FILE); JsonSchema schema = await JsonSchema.FromFileAsync("Resources/ConfigurationSchema.json"); ICollection <ValidationError> errors = schema.Validate(json); if (errors.Count > 0) { throw new ConfigurationSchemaException( "Configuration data does not conform to the required schema: " + errors.ElementAt(0).ToString()); } dynamic jsonObject = JsonConvert.DeserializeObject <ExpandoObject>(json, new ExpandoObjectConverter()); var sensorsDict = (IDictionary <string, object>)jsonObject.sensors; if (sensorsDict.ContainsKey("satellite")) { var satelliteDict = (IDictionary <string, object>)sensorsDict["satellite"]; if (!satelliteDict.ContainsKey("windSpeed") && !satelliteDict.ContainsKey("windDir") && !satelliteDict.ContainsKey("sunDur")) { throw new ConfigurationSchemaException( "sensors.satellite must contain at least one of windSpeed, windDir or sunDur"); } } dataLedPin = (int)jsonObject.dataLedPin; errorLedPin = (int)jsonObject.errorLedPin; clockTickPin = (int)jsonObject.clockTickPin; position = jsonObject.position; position.timeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/London"); sensors = jsonObject.sensors; uploader = jsonObject.uploader; }
public async Task LoadRolesFromJsonAsync(string json) { IDictionary <string, Category> categories = await db.Categories.ToDictionaryAsync(x => x.Name); IDictionary <string, OperationKey> operationKeys = await db.OperationKeys.ToDictionaryAsync(x => x.Name); JsonSchema schema = await JsonSchema.FromFileAsync(RolesSchemaPath); RolesFromJsonLoader rolesFromJsonLoader; try { rolesFromJsonLoader = new RolesFromJsonLoader(categories, operationKeys, schema); rolesFromJsonLoader.Seed(json); } catch (Exception e) { throw new SunErrorException(new Error { Code = "PermissionsJsonUploadParseError", Description = "Error in parsing uploaded json", Message = e.Message, }); } try { db.BeginTransaction(); await UpdateRoles(rolesFromJsonLoader.roles); await ClearAccessesAsync(); CopyToDb(rolesFromJsonLoader); db.CommitTransaction(); } catch { db.RollbackTransaction(); throw; } }
private void SeedRoles() { Console.WriteLine("Roles"); string pathToUserGroupsConfig = Path.GetFullPath(Path.Combine(configDir, "Roles.json")); string pathToUserGroupsSchema = Path.GetFullPath("Resources/Roles.schema.json"); JsonSchema schema = JsonSchema.FromFileAsync(pathToUserGroupsSchema).GetAwaiter().GetResult(); RolesFromJsonLoader fromJsonLoader = new RolesFromJsonLoader(dataContainer.Categories.ToDictionary(x => x.Name), dataContainer.OperationKeys.ToDictionary(x => x.Name), schema); var json = File.ReadAllText(pathToUserGroupsConfig); fromJsonLoader.Seed(json); dataContainer.Roles = fromJsonLoader.roles; dataContainer.CategoryAccesses = fromJsonLoader.categoryAccesses; dataContainer.CategoryOperationAccesses = fromJsonLoader.categoryOperationAccesses; }
/// <exception cref="ArgumentException">The argument 'Input' was empty.</exception> protected async Task <JsonSchema> GetJsonSchemaAsync() { var input = Input.ToString(); if (string.IsNullOrEmpty(input)) { throw new ArgumentException("The argument 'Input' was empty."); } if (IsJson(input)) { return(await JsonSchema.FromJsonAsync(input).ConfigureAwait(false)); } if (DynamicApis.FileExists(input)) { return(await JsonSchema.FromFileAsync(input).ConfigureAwait(false)); } return(await JsonSchema.FromUrlAsync(input).ConfigureAwait(false)); }
private void SeedRoles() { Console.WriteLine("Roles"); string pathToUserGroupsConfig = Path.Combine(configInitDir, SeederPathsNames.RolesJsonFile); string resourcesPath = pathService.GetPath(PathNames.ResourcesDirName); string pathToUserGroupsSchema = Path.Combine(resourcesPath, SeederPathsNames.RolesSchemaJsonFile); JsonSchema schema = JsonSchema.FromFileAsync(pathToUserGroupsSchema).GetAwaiter().GetResult(); RolesFromJsonLoader fromJsonLoader = new RolesFromJsonLoader(dataContainer.Categories.ToDictionary(x => x.Name), dataContainer.OperationKeys.ToDictionary(x => x.Name), schema); var json = File.ReadAllText(pathToUserGroupsConfig); fromJsonLoader.Seed(json); dataContainer.Roles = fromJsonLoader.roles; dataContainer.CategoryAccesses = fromJsonLoader.categoryAccesses; dataContainer.CategoryOperationAccesses = fromJsonLoader.categoryOperationAccesses; }
private static async Task <(string csharpfile, string jsonschema)> GenerateFileContentFromSchema(string input, string @namespace) { var json = File.ReadAllText(input); JsonSchema schema; if (json.Contains("$schema")) { schema = await JsonSchema.FromFileAsync(input); } else { schema = JsonSchema.FromSampleJson(json); } var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { Namespace = @namespace, GenerateDataAnnotations = false }); var file = generator.GenerateFile(); return(file, schema.ToJson()); }
public async Task When_definitions_inherit_from_root_schema() { //// Arrange var path = GetTestDirectory() + "/References/Animal.json"; //// Act var schema = await JsonSchema.FromFileAsync(path); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Record }); //// Act var code = generator.GenerateFile(); //// Assert Assert.Contains("public abstract partial class Animal", code); Assert.Contains("public partial class Cat : Animal", code); Assert.Contains("public partial class PersianCat : Cat", code); Assert.Contains("[JsonInheritanceAttribute(\"Cat\", typeof(Cat))]", code); Assert.Contains("[JsonInheritanceAttribute(\"PersianCat\", typeof(PersianCat))]", code); }
public static async Task GenerateCSharpFileFromSchema(string filename, Args args) { Console.WriteLine($@"Generate from: {filename}"); var input = Path.GetFullPath(filename); Console.WriteLine($@"In: {input}"); var outFilename = $"{Path.GetFileNameWithoutExtension(filename)}.cs"; var output = Path.Combine((String.IsNullOrWhiteSpace(args.OutputDir) ? Path.GetDirectoryName(input) : Path.GetFullPath(args.OutputDir)) ?? String.Empty, outFilename); Console.WriteLine($@"Out: {output}"); var jsonSchema = await JsonSchema.FromFileAsync(input); var generator = new CSharpGenerator(jsonSchema, new CSharpGeneratorSettings() { Namespace = args.Namespace }); var generateFile = generator.GenerateFile(); generateFile = generateFile.Replace( @"[System.CodeDom.Compiler.GeneratedCode(""NJsonSchema"", ""10.1.21.0 (Newtonsoft.Json v9.0.0.0)"")]", String.Empty); await File.WriteAllTextAsync($"{output}", generateFile); }
public static async Task <JsonSchema> GetSchemaDefinition(string schema) => await JsonSchema.FromFileAsync($"{SchemaFolder}\\{schema}.json");
public bool Forward(string json, bool addToUnknown = true) { bool result = true; string type = ""; var pathSchemas = ConfigurationManager.AppSettings["PathSchemaLOLA"]; var schemaDataVariablesList = JsonSchema.FromFileAsync(Path.Combine(pathSchemas, "variablesList.json")).Result; var errorDataVariablesList = schemaDataVariablesList.Validate(json); if (!errorDataVariablesList.Any()) { type = "variablesList"; var data = JsonConvert .DeserializeObject <Mongo.Dto.VariablesList>(json); //controllo delle date obbligatorie if (!DateTimeLolaValid(data.info[0].LoginDate)) { result = false; } if (data.variablesList != null && data.variablesList.Any(v => !DateTimeLolaValid(v.UtcDateTime))) { result = false; } data.DateSendedQueue = DateTime.UtcNow; data.DateReceived = DateTime.UtcNow; _infoProducer.Send(new Info { InfoMachine = data.info }); _variablesGenericRepository.Create(data); _variablesProducer.Send(new VariablesList { ObjectId = data.Id, InfoMachine = data.info, VariablesListMachine = data.variablesList }); } var schemaDataMessages = JsonSchema.FromFileAsync(Path.Combine(pathSchemas, "messages.json")).Result; var errorMessages = schemaDataMessages.Validate(json); if (!errorMessages.Any()) { type = "messages"; var data = JsonConvert.DeserializeObject <Mongo.Dto.Message>(json); //controllo delle date obbligatorie if (!DateTimeLolaValid(data.info[0].LoginDate)) { result = false; } if (data.message != null && data.message.Any(m => !DateTimeLolaValid(m.Time))) { result = false; } data.DateSendedQueue = DateTime.UtcNow; data.DateReceived = DateTime.UtcNow; _infoProducer.Send(new Info { InfoMachine = data.info }); _messageGenericRepository.Create(data); _messageProducer.Send(new Message { ObjectId = data.Id, InfoMachine = data.info, MessageMachine = data.message }); } var schemaDataState = JsonSchema.FromFileAsync(Path.Combine(pathSchemas, "state.json")).Result; var errorStates = schemaDataState.Validate(json); if (!errorStates.Any()) { type = "state"; var data = JsonConvert.DeserializeObject <Mongo.Dto.State>(json); //controllo delle date obbligatorie if (!DateTimeLolaValid(data.info[0].LoginDate)) { result = false; } if (data.state != null && data.state.Any(m => !DateTimeLolaValid(m.StartTime) || !DateTimeLolaValid(m.EndTime))) { result = false; } data.DateSendedQueue = DateTime.UtcNow; data.DateReceived = DateTime.UtcNow; _infoProducer.Send(new Info { InfoMachine = data.info }); _stateGenericRepository.Create(data); data.DateReceived = DateTime.UtcNow; _stateProducer.Send(new State { ObjectId = data.Id, InfoMachine = data.info, StateMachine = data.state }); } var schemaDataTool = JsonSchema.FromFileAsync(Path.Combine(pathSchemas, "tool.json")).Result; var errorTool = schemaDataTool.Validate(json); if (!errorTool.Any()) { type = "tool"; var data = JsonConvert.DeserializeObject <Mongo.Dto.Tool>(json); if (!DateTimeLolaValid(data.info[0].LoginDate)) { result = false; } if (data.tool != null && data.tool.Any(m => !DateTimeLolaValid(m.DateLoaded) || (m.DateReplaced != null && !DateTimeLolaValid(m.DateReplaced)))) { result = false; } data.DateSendedQueue = DateTime.UtcNow; data.DateReceived = DateTime.UtcNow; _infoProducer.Send(new Info { InfoMachine = data.info }); _toolGenericRepository.Create(data); data.DateReceived = DateTime.UtcNow; _toolProducer.Send(new Tool { ObjectId = data.Id, InfoMachine = data.info, ToolMachine = data.tool }); } var schemaDataHistoryJobPieceBar = JsonSchema.FromFileAsync(Path.Combine(pathSchemas, "historyJobPieceBar.json")).Result; var errorHistoryJobPieceBar = schemaDataHistoryJobPieceBar.Validate(json); if (!errorHistoryJobPieceBar.Any()) { type = "historyJobPieceBar"; var data = JsonConvert .DeserializeObject <Mongo.Dto.HistoryJobPieceBar>(json); if (!DateTimeLolaValid(data.info[0].LoginDate)) { result = false; } if (data.bar != null && data.bar.Any(m => !DateTimeLolaValid(m.StartTime)) && data.bar.Any(m => !DateTimeLolaValid(m.EndTime))) { result = false; } if (data.piece != null && data.piece.Any(m => !DateTimeLolaValid(m.StartTime) || !DateTimeLolaValid(m.EndTime))) { result = false; } if (data.historyjob != null && data.historyjob.Any(m => !DateTimeLolaValid(m.Day))) { result = false; } data.DateSendedQueue = DateTime.UtcNow; data.DateReceived = DateTime.UtcNow; _infoProducer.Send(new Info { InfoMachine = data.info }); _historyJobPieceBarGenericRepository.Create(data); _historyJobPieceBarProducer.Send(new HistoryJobPieceBar { ObjectId = data.Id, InfoMachine = data.info, HistoryJobMachine = data.historyjob, PieceMachine = data.piece, BarMachine = data.bar }); } if (!addToUnknown || (type != "" && result)) { return(result); } var dataUnknown = JsonConvert.DeserializeObject <BaseModel>(json); var en = new Unknown(dataUnknown) { EntityUnknown = json, ErrorDataVariablesList = errorDataVariablesList.ToDictionary(mc => mc.Path, mc => mc.Kind.ToString(), StringComparer.OrdinalIgnoreCase), ErrorMessages = errorMessages.ToDictionary(mc => mc.Path, mc => mc.Kind.ToString(), StringComparer.OrdinalIgnoreCase), ErrorHistoryJobPieceBar = errorHistoryJobPieceBar.ToDictionary(mc => mc.Path, mc => mc.Kind.ToString(), StringComparer.OrdinalIgnoreCase), ErrorStates = errorStates.ToDictionary(mc => mc.Path, mc => mc.Kind.ToString(), StringComparer.OrdinalIgnoreCase), ErrorTool = errorTool.ToDictionary(mc => mc.Path, mc => mc.Kind.ToString(), StringComparer.OrdinalIgnoreCase) }; _unknownGenericRepository.Create(en); return(result); }