/// <summary> /// Creates a new generic instance of the collection operation by type. /// </summary> /// <param name="config">Json configuration of current collection</param> /// <returns>Returns a instance of the GenericCollectionOperator which fits the configuration type.</returns> private dynamic CreateOperationInstance(JToken config) { string dbCollectionName = JsonOperations.TryGetValue <string>(config, "collectionName"); _logger.LogDebug("Name of collection: " + dbCollectionName); string typeName = JsonOperations.TryGetValue <string>(config, "typeName"); _logger.LogDebug("Name of type: " + typeName); Type genericeType = GetTypeByName(typeName); if (!genericeType.IsPublic) { _logger.LogError(typeName + " is not public. Only public classes are supported."); throw new ApplicationException(typeName + " is not public. Only public classes are supported."); } _logger.LogDebug("Collection at data context found."); var operationType = typeof(GenericCollectionOperator <>); var genericInstanceHandler = operationType.MakeGenericType(genericeType); dynamic instance = Activator.CreateInstance(genericInstanceHandler, new object[] { GetCollectionByTypeInstance(genericeType, dbCollectionName), config, _updateOperationHandler, _logger }); _logger.LogDebug("Collection operator created for collection " + dbCollectionName); return(instance); }
public void Invalid_JSON_Update_Message_With_TimeStamp() { string message = File.ReadAllText("./InputFiles/Invalid_FixedDesign_SimulationResults.json"); JsonOperations jsonOperations = new JsonOperations(); string updatedMessage = jsonOperations.UpdateInputMessageJsonField(message); Assert.True(string.IsNullOrEmpty(updatedMessage)); }
public void Add_Output_Message_JSON_Field() { string message = File.ReadAllText("./InputFiles/FixedDesign_Simulation.json"); JsonOperations jsonOperations = new JsonOperations(); string updatedMessage = jsonOperations.AddOutputMessageJsonField(message); Assert.True(!string.IsNullOrEmpty(updatedMessage)); }
public void Invalid_JSON_Find_Engine_Name() { string message = File.ReadAllText("./InputFiles/Invalid_FixedDesign_SimulationResults.json"); JsonOperations jsonOperations = new JsonOperations(); string engineName = jsonOperations.FindEngineName(message); Assert.True(string.IsNullOrEmpty(engineName)); }
public void Find_Engine_Name_From_JSON() { string message = File.ReadAllText("./InputFiles/FixedDesign_Simulation.json"); JsonOperations jsonOperations = new JsonOperations(); string engineName = jsonOperations.FindEngineName(message); Assert.True(!string.IsNullOrEmpty(engineName)); }
public void Update_Engine_Stage_To_JSON() { string message = File.ReadAllText("./InputFiles/FixedDesign_Simulation.json"); JsonOperations jsonOperations = new JsonOperations(); string engineName = "2-arm-TimeToEvent-FixedDesign"; string outputMessage = jsonOperations.UpdateEngineStageJsonField(message, engineName); Assert.True(!string.IsNullOrEmpty(outputMessage)); }
public void Invalid_Add_Output_Summary_JSON_Field() { string message = File.ReadAllText("./InputFiles/Invalid_FixedDesign_SimulationResults.json"); string engineOutput = File.ReadAllText("./InputFiles/FixedDesign_Simulation.json"); JsonOperations jsonOperations = new JsonOperations(); string updatedMessage = jsonOperations.AddEngineOutputSummary(message, engineOutput); Assert.True(string.IsNullOrEmpty(updatedMessage)); }
public void Invalid_JSON_Add_Engine_Stage_Field() { string message = File.ReadAllText("./InputFiles/Invalid_FixedDesign_SimulationResults.json"); JsonOperations jsonOperations = new JsonOperations(); string engineName = "2-arm-TimeToEvent-FixedDesign"; string outputMessage = jsonOperations.AddEngineStageJsonField(message, engineName); Assert.True(string.IsNullOrEmpty(outputMessage)); }
public void Execute_Should_Launch_File_When_Only_User_Lock_Present() { FileSystem.AddFile(TestFileName, new Bogus.Faker().Lorem.Paragraphs(3)); var launchLock = new Library.LaunchLock() { IsValid = true, FileName = $"{TestFileName}.{Guid.NewGuid()}.launchlock", Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name, LockTime = DateTime.Now }; var launchLockJson = JsonOperations.Serialize(launchLock); FileSystem.AddFile(launchLock.FileName, launchLockJson); LaunchLockProcess.Execute(new string[] { TestFileName }); Communicator.Messages.Should().Contain("Launching file."); }
/// <summary> /// Validates the json configration. /// </summary> /// <param name="configuration">Json configuration content</param> /// <returns>Returns true if the configuration is valid.</returns> private bool ValidateConfiguration(JObject configuration) { if (string.IsNullOrEmpty(JsonOperations.TryGetValue <string>(configuration, "version"))) { _logger.LogError("version element is missing at json configuration."); return(false); } if (JsonOperations.TryGetValue <object>(configuration, "data") == null) { _logger.LogError("data element is missing at json configuration."); return(false); } foreach (var element in configuration["data"]) { if (string.IsNullOrEmpty(JsonOperations.TryGetValue <string>(element, "collectionName"))) { _logger.LogError("collectionName element is missing at json configuration."); return(false); } if (string.IsNullOrEmpty(JsonOperations.TryGetValue <string>(element, "typeName"))) { _logger.LogError("typeName element is missing at json configuration."); return(false); } if (JsonOperations.TryGetValues <string>(element, "keys") == null) { _logger.LogError("keys element is missing at json configuration."); return(false); } if (JsonOperations.TryGetValues <string>(element, "items") == null) { _logger.LogError("items element is missing at json configuration."); return(false); } } return(true); }
public async Task <IActionResult> DownloadData(long?id, ResponseViewModel model) { List <McpdipDetail> Details = new List <McpdipDetail>(); string ItemType = "ResponseError"; string exportType = ""; Details = await GetErrorsForDownload(model); exportType = model.SelectedExport; if (exportType == ".csv") { var columnHeader = new string[] { "DetailId", "ResponseTarget", "ChildrenId", "ItemReference", "Id", "Description", "Severity", "OriginalTable", "OriginalId", "OriginalHeaderId", "OriginalCin", "OriginalItemId", "OriginalDataSource" }; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine(string.Join(",", columnHeader)); Details.ForEach(x => sb.AppendLine($"{x.DetailId.ToString()},{x.ResponseTarget },{x.ChildrenId.ToString() },{x.ItemReference},{x.Id},{x.Description},{x.Severity},{x.OriginalTable},{x.OriginalId.ToString()},{x.OriginalHeaderId.ToString()},{x.OriginalCin},{x.OriginalItemId},{x.OriginalDataSource}")); byte[] buffer = System.Text.Encoding.ASCII.GetBytes(sb.ToString()); return(File(buffer, "text/csv", ItemType + DateTime.Today.ToString("yyyyMMdd") + ".csv")); } else if (exportType == "json") { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append($"\"{ItemType}\":"); sb.Append(JsonOperations.GetResponseDetailJson(Details)); byte[] buffer = System.Text.Encoding.ASCII.GetBytes(sb.ToString()); return(File(buffer, "text/json", ItemType + DateTime.Today.ToString("yyyyMMdd") + ".json")); } else { string fileName = ItemType + DateTime.Today.ToString("yyyyMMdd") + ".xlsx"; using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(Details.ToDataTable()); using (MemoryStream stream = new MemoryStream()) { wb.SaveAs(stream); return(File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName)); } } } }
public void Deserialize_Should_Work_For_Valid_Input() { var lockTime = DateTime.Now; var userName = new Bogus.Faker().Internet.UserName(); var originalLaunchLock = new LaunchLock() { FileName = FileName, Username = userName, LockTime = lockTime, IsValid = true }; var input = JsonOperations.Serialize(originalLaunchLock); var launchLock = JsonOperations.Deserialize(FileName, input); launchLock.IsValid.Should().Be(true); launchLock.FileName.Should().Be(FileName); launchLock.LockTime.Should().BeCloseTo(lockTime); launchLock.Username.Should().Be(userName); }
public ServiceCollectionHelper() { _configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.Development.json") .Build(); _services = new ServiceCollection(); IJsonOperations jsonOperations = new JsonOperations(); _services.AddLogging(); _services.AddLocalization(options => options.ResourcesPath = "Resources"); ConfigureDatabase(); ConfigureDependencyInjection(); ConfigureIdentity(); ConfigureJWT(jsonOperations); var app = _services.BuildServiceProvider().GetRequiredService <IApplicationBuilder>(); app.ResetDatabaseAsync().Wait(); }
private void Deserialize_Click(object sender, EventArgs e) { var results = JsonOperations.Read(); if (results != null) { var profile = results.TechProfile; DisplayNameTextBox.Text = profile.DisplayName; MvpCheckBox.Checked = profile.IsMvp; DateAddedTextBox.Text = profile.AuthenticationModes.FirstOrDefault()?.DateAdded.ToString("d"); var imageFileName = "ProfileImage.png"; if (Helpers.DownLoadProfileImage(profile.AvatarUrl, imageFileName)) { ProfilePictureBox.Image = Image.FromFile(imageFileName); } } else { MessageBox.Show("We failed to find your file."); } }
private string GetFormattedString(string text, EnStringType stringType, bool isFormatted) { string result = text; try { switch (stringType) { case EnStringType.Json: result = JsonOperations.GetFormattedJson(result, isFormatted ? Formatting.Indented : Formatting.None); break; case EnStringType.Xml: result = XMLOperations.GetXmlString(result, isFormatted); break; } } catch (Exception ex) { MessageBox.Show(this, ex.Message, $"{stringType} Convert Error ...", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(result); }
/// <summary> /// Starts the database update process. /// </summary> /// <param name="data">Json configuration of item data</param> /// <returns>Returns the handling task.</returns> /// <remarks>Update process will be only started if the version of the json configuration is newer than the version which is stored in database.</remarks> public async Task RunAsync(JObject data) { string versionValue = JsonOperations.TryGetValue <string>(data, "version"); _logger.LogDebug("Config version: " + versionValue); string versionCollectionName = JsonOperations.TryGetValue <string>(data, "customVersionCollectionName"); _logger.LogDebug("Config version collection nane: " + versionCollectionName); // sets default version collection name if not exists if (string.IsNullOrEmpty(versionCollectionName)) { versionCollectionName = "DbInitConfig"; _logger.LogInformation("Version collection name was not set. Default name will be used. -> " + versionCollectionName); } // Checks if configuration version is newer than existing version if (await IsNewerConfigVersionAsync(versionValue, versionCollectionName)) { var collectionConfigurations = data["data"]; foreach (var config in collectionConfigurations) { var instance = CreateOperationInstance(config); await UpdateCollectionAsync(instance); } // Updates version at database await UpdateConfigVersionAsync(versionValue, versionCollectionName); _logger.LogDebug("Version update at database completed."); } else { _logger.LogInformation("No newer version found. -> " + versionValue); } }
public void Initialize() { JsonOperations = new JsonOperations(); FileName = @"C:\ProgramFiles\Test.txt"; }
public void Deserialize_Should_Work_For_Invalid_Input() { var launchLock = JsonOperations.Deserialize(FileName, "lock"); launchLock.IsValid.Should().Be(false); }
public void Setup() { invalidFileExtension = new JsonOperations("./TestFiles/InvalidExtension.txt"); invalidFile = new JsonOperations("./TestFiles/InValidFile_MissingGenderInOneOfTheObjects.json"); validJsonFile = new JsonOperations("./TestFiles/ValidFile.json"); }