public void JsonProcessor_ProcessFile_JsonFile_SuccessedProcessedFile() { JsonProcessor jsonProcessor = new JsonProcessor(); string testFile = Path.Combine ( Directory.GetCurrentDirectory(), @"TestFiles\JsonProcessor_ProcessFile_File_ProcessedFile\JsonProcessor_ProcessFile_JsonFile_SuccessedProcessedFile.json" ); tempFile = Path.Combine ( Directory.GetCurrentDirectory(), @"TestFiles\JsonProcessor_ProcessFile_File_ProcessedFile\Expected_JsonProcessor_ProcessFile_JsonFile_SuccessedProcessedFile_Temp.json" ); string expectedFile = Path.Combine ( Directory.GetCurrentDirectory(), @"TestFiles\JsonProcessor_ProcessFile_File_ProcessedFile\Expected_JsonProcessor_ProcessFile_JsonFile_SuccessedProcessedFile.json" ); File.Copy(testFile, tempFile, true); jsonProcessor.ProcessFile(tempFile); var tempFileBytes = File.ReadAllBytes(tempFile); var expectedFileBytes = File.ReadAllBytes(expectedFile); Assert.AreEqual(expectedFileBytes, tempFileBytes); }
public async Task <Dictionary <string, object> > ValidateUnregisteredDevice(string deviceId) { Dictionary <string, object> deviceInfo = null; using (var client = openAmHttpClient(ClientType.Device)) { var url = "auth/json/sessions/?_action=getProperty"; var content = new StringContent(string.Empty, Encoding.UTF8, "application/json"); content.Headers.Add("mgiSsoSession", deviceId); var response = await client.PostAsync(url, content); // This helps to see requests in Fiddler // Should not be uncommented for anything except debugging purposes //WebRequest.DefaultWebProxy = new WebProxy("127.0.0.1", 8888); if (response.StatusCode != HttpStatusCode.OK) { return(null); } var responseData = await response.Content.ReadAsStringAsync(); deviceInfo = JsonProcessor.DeserializeObject <Dictionary <string, object> >(responseData); deviceInfo = deviceInfo.Where(prop => !string.IsNullOrWhiteSpace((string)prop.Value)) .ToDictionary(prop => prop.Key, prop => prop.Value); } return(deviceInfo); }
private static Dictionary <string, string> ProcessApiErrors(DeepHealthCheckResponse respVm) { // This processing is done at the request of DYNATRACE team //Parse the deep health check responses, throw & catch the exception for dynatrace monitoring. But return OK from the controller. Dictionary <string, string> apiErrors = null; try { var failedHealthCheck = respVm.HealthStatus.Any(x => x.StatusCode != StatusCode.Ok && x.StatusCode != StatusCode.NotImplemented); if (failedHealthCheck) { throw new DeepHealthCheckException { ErrorString = "One or more dependencies have failed.", DetailString = JsonProcessor.SerializeObject(respVm) }; } } catch (DeepHealthCheckException exc) { apiErrors = new Dictionary <string, string> { { "DeepHealthCheckException", exc.ErrorString } }; } return(apiErrors); }
private void OnDeserialize() { animalRegister = JsonProcessor.Deserialize <AnimalRegister>(txtJson.text); UpdateLog(); btnSerialize.interactable = animalRegister != null; }
public void TestMultipleJsonArrayAsRootFail() { Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[],")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[\"abc\" : \"def\"],")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[], []")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[],\n[]")); }
public static TResponse GetTransactionLookupStatusResponse <TResponse>(string referenceNumber, Func <TrainingModeResponses, string> getFileName) { var instance = GetConfiguration(); var scenario = instance.Scenarios.SingleOrDefault(x => x.ReferenceNumber == referenceNumber && getFileName(x.Responses) != null); if (scenario?.Responses == null) { throw new TrainingModeException("STRKEY_TRAINING_ERROR_EDIT_TRAN_REF_NUMBER"); } var responseFilePath = Path.Combine(JsonFileHelper.ExecutingDir(), TrainingModeFolderName, scenario.SessionType.ToString(), referenceNumber ?? string.Empty, getFileName(scenario.Responses)); if (!File.Exists(responseFilePath)) { throw new FileNotFoundException($"Could not find Training Mode Transaction Lookup Status response file for referenceNumber:{referenceNumber}."); } try { return(JsonProcessor.DeserializeObject <TResponse>(JsonFileHelper.GetFileContents(responseFilePath), true)); } catch (Exception exception) { throw new InvalidDataException($"Could not deserialize Training Mode Transaction Lookup Status response for sessionType:{scenario.SessionType}, referenceNumber:{referenceNumber}.", exception); } }
private void Start() { // while (true) // { // yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Return)); // JsonProcessor.Serialize(new JsonClassD()); // } Log.Info(JsonProcessor.Serialize(new JsonClassC())); Log.Info("------"); Log.Info(JsonProcessor.Serialize(new JsonClassD())); // MethodInfo baseMethod = typeof(JsonClassA).GetMethod(nameof(JsonClassA.OnSerializationCallback)); // MethodInfo overrideMethod = typeof(JsonClassB).GetMethod(nameof(JsonClassB.OnSerializationCallback)); // MethodInfo secondDegreeOverrideMethod = typeof(JsonClassD).GetMethod(nameof(JsonClassD.OnSerializationCallback)); // MethodInfo newMethod = typeof(JsonClassC).GetMethod(nameof(JsonClassC.OnSerializationCallback)); // MethodInfo interfaceMethod = typeof(IJsonClass<int>).GetMethod(nameof(IJsonClass<int>.OnSerializationCallback)); // InterfaceMapping iMappingA = typeof(JsonClassA).GetInterfaceMap(typeof(IJsonClass<int>)); // InterfaceMapping iMappingB = typeof(JsonClassB).GetInterfaceMap(typeof(IJsonClass<int>)); // Log.Info("Can the override method's base definition be matched? {0}", baseMethod == overrideMethod.GetBaseDefinition()); // Log.Info("Can the second degree override method's base definition be matched directly to the base? {0}", baseMethod == secondDegreeOverrideMethod.GetBaseDefinition()); // Log.Info("Can the second degree override method's base definition be matched to its first-order base? {0}", overrideMethod == secondDegreeOverrideMethod.GetBaseDefinition()); // Log.Info("Can the base method be found in the interface mapping? {0}", iMappingA.TargetMethods.Contains(baseMethod)); // Log.Info("Can the override method be found in the interface mapping? {0}", iMappingB.TargetMethods.Contains(overrideMethod)); // Log.Info("Is the base method virtual? {0}", baseMethod.IsVirtual); // Log.Info("Is the override method virtual? {0}", overrideMethod.IsVirtual); // Log.Info("Is the new method virtual? {0}", newMethod.IsVirtual); // PropertyInfo interfacePropertyInfo = typeof(IJsonClass).GetProperty(nameof(IJsonClass.SomeValue)); // PropertyInfo implementedPropertyInfo = typeof(JsonClassA).GetProperty(nameof(JsonClassA.SomeValue)); }
public bool PrepareJSON(string timeInUse = null) { List <string> dataPointsInUse; if (timeInUse != null) { dataPointsInUse = new List <string> { timeInUse }; dataPointsInUse = GetDataPointsInUse(dataPointsInUse, "jsonElement", "field"); } else { dataPointsInUse = GetDataPointsInUse("jsonElement", "field"); } if (dataPointsInUse.Count == 0) { return(true); } JsonProcessor jsonProcessor = new JsonProcessor(); try { dataRecords = jsonProcessor.GetRecords(dataFile, dataRestURL, repeatingElement, dataSourceFileOrURL, dataPointsInUse, node); } catch (Exception ex) { sourceLogger.Error(ex, "Error retrieving JSON data"); return(false); } return(true); }
public void ShouldDeserializeActivityCorrectly() { // Given string courseResultJson = "{\"result\":{\"event_array\":[{\"break_length\":\"00:30\",\"end_time\":\"15:50\",\"id\":1,\"length\":\"01:30\",\"room\":\"A\",\"room_id\":1,\"start_time\":\"14:20\",\"weekday\":1}],\"event_count\":1,\"id\":1,\"students_array\":[{\"group\":\"1\",\"groups\":\"2\",\"id\":1,\"name\":\"A\"}],\"students_count\":1,\"subject\":\"A\",\"subject_id\":1,\"teacher_array\":[{\"id\":1,\"name\":\"A\"}],\"teacher_count\":1},\"status\":\"ok\"}"; // When EntityApiResponse <Activity> parsedEntities = JsonProcessor.GetObjectFromStream <EntityApiResponse <Activity> >( new MemoryStream(Encoding.UTF8.GetBytes(courseResultJson))); // Then parsedEntities.Should().NotBeNull(); parsedEntities.Result.Should().NotBeNull(); parsedEntities.Result.Id.Should().Be(1); parsedEntities.Result.Subject.Should().Be("A"); parsedEntities.Result.SubjectId.Should().Be(1); parsedEntities.Result.Teachers.Should().Contain(z => z.Name == "A" && z.Id == 1); parsedEntities.Result.CourseGroups.Should().Contain(z => z.GroupId == 1 && z.Id == 1 && z.Name == "A" && z.TotalGroups == 2); parsedEntities.Result.Events.Should().Contain(z => z.BreakLength == "00:30" && z.Day == WeekDay.Monday && z.Duration == "01:30" && z.Ends == "15:50" && z.Id == 1 && z.RoomId == 1 && z.RoomName == "A" && z.Start == "14:20"); }
public void TestLowercase3() { var array = new JArray { new JObject(new JProperty("properties", new JObject(new JProperty("instanceData", new JObject(new JProperty("Microsoft.Resources", new JObject(new JProperty("resourceUri", "/subscriptions/12345678-1234-1234-1234-ABCD2345678/resourceGroups/MyGroup/providers/Microsoft.Sql/servers/MySqlServer")))))))) }; JsonProcessor.Lowercase(array, "properties.instanceData.['Microsoft.Resources'].resourceUri".Split(',')); string expected = @"[ { ""properties"": { ""instanceData"": { ""Microsoft.Resources"": { ""resourceUri"": ""/subscriptions/12345678-1234-1234-1234-abcd2345678/resourcegroups/mygroup/providers/microsoft.sql/servers/mysqlserver"" } } } } ]"; Assert.AreEqual(expected, array.ToString()); }
public static List <Claim> ParseClaims(Dictionary <string, object> response) { var claims = new List <Claim>(); if (response == null) { return(claims); } foreach (var claim in response) { if (claim.Value is string) { if (!string.IsNullOrWhiteSpace(claim.Value.ToString())) { claims.TryAddClaim(claim.Key, (string)claim.Value); } } else { var claimValues = JsonProcessor.ToStringList(claim); foreach (var claimValue in claimValues) { if (!string.IsNullOrWhiteSpace(claimValue)) { claims.TryAddClaim(claim.Key, claimValue); } } } } return(claims); }
public async Task SendGameState() { if (GameAPI.getGameState() != null) { await Clients.All.SendAsync("sendGameState", JsonProcessor.getWerewolfJson(GameAPI.getGameState())); } }
public void TestOneJsonArray() { Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[ 1 : 1 ]")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[ 1 1 ]")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[ 1 : \"1\" ]")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("[ \"1\" : \"1\" ]")); object parsed = JsonProcessor.Parse("[ 1 ]"); Assert.IsTrue(parsed is IList); IList parsedList = parsed as IList; Assert.AreEqual((long)1, parsedList[0]); parsed = JsonProcessor.Parse("[ \n ]"); Assert.IsTrue(parsed is IList); parsedList = parsed as IList; Assert.AreEqual(0, parsedList.Count); parsed = JsonProcessor.Parse("[ \"asdf\" ]"); Assert.IsTrue(parsed is IList); parsedList = parsed as IList; Assert.AreEqual("asdf", parsedList[0]); parsed = JsonProcessor.Parse("[ \"\u849c\" ]"); Assert.IsTrue(parsed is IList); parsedList = parsed as IList; Assert.AreEqual("\u849c", parsedList[0]); }
public MoAndLocationRepository() { var jsonData = JsonFileHelper.GetFileContents(_configurationFilePath); MoAndLocations = !string.IsNullOrEmpty(jsonData) ? JsonProcessor.DeserializeObject <MoAndLocationsData>(jsonData): new MoAndLocationsData(); }
private static EventResponse Log(EventRequest eventRequest) { var resp = new EventResponse(); var userName = AuthIntegration.HasClaims() ? AuthIntegration.GetOperator().UserName : null; if (string.IsNullOrEmpty(userName)) { return(resp); } //[DATE TIME] [SEVERITY] [APPLICATION] [METHOD] DETAIL try { //LogManager.SetLogicalContextProperty(LogProperties.ApplicationName, $"{eventRequest.Source}"); var jsonString = JsonProcessor.SerializeObject(eventRequest.Payload); var strLog = $"Msg='{jsonString}'"; logger.Info(strLog); } catch { throw new Exception("Event could not be logged"); } return(resp); }
public Task <Tuple <HttpStatusCode, IDictionary <string, object> > > RunCommandAsync(ParseCommand command, IProgress <ParseUploadProgressEventArgs> uploadProgress = null, IProgress <ParseDownloadProgressEventArgs> downloadProgress = null, CancellationToken cancellationToken = default) => PrepareCommand(command).ContinueWith(commandTask => { return(Client.ExecuteAsync(commandTask.Result, uploadProgress, downloadProgress, cancellationToken).OnSuccess(t => { cancellationToken.ThrowIfCancellationRequested(); Tuple <HttpStatusCode, string> response = t.Result; string contentString = response.Item2; int responseCode = (int)response.Item1; if (responseCode >= 500) { // Server error, return InternalServerError. throw new ParseException(ParseException.ErrorCode.InternalServerError, response.Item2); } else if (contentString != null) { IDictionary <string, object> contentJson = null; // TODO: Newer versions of Parse Server send certain and/or all failure results back as HTML; add case for this. try { contentJson = contentString.StartsWith("[") ? new Dictionary <string, object> { ["results"] = JsonProcessor.Parse(contentString) } : JsonProcessor.Parse(contentString) as IDictionary <string, object>; } catch (Exception e) { throw new ParseException(ParseException.ErrorCode.OtherCause, "Invalid or alternatively-formatted response recieved from server.", e); } if (responseCode < 200 || responseCode > 299) { throw new ParseException(contentJson.ContainsKey("code") ? (ParseException.ErrorCode)(int) (long) contentJson["code"] : ParseException.ErrorCode.OtherCause, contentJson.ContainsKey("error") ? contentJson["error"] as string : contentString); } return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1, contentJson); } return new Tuple <HttpStatusCode, IDictionary <string, object> >(response.Item1, null); })); }).Unwrap();
/// <summary> /// Constructor /// </summary> public CreateCloneAndAssignIdTest() { var inputObjectProcessor = new WSV2.Program.Processor.InputObjectProcessor(); var fileProcessor = new FileProcessor(); var jsonProcessor = new JsonProcessor(fileProcessor); _cloneProcessor = new Program.Processor.CloneProcessor(inputObjectProcessor, jsonProcessor); }
internal ParsePushNotificationEventArgs(IDictionary <string, object> payload) { Payload = payload; #if !IOS StringPayload = JsonProcessor.Encode(payload); #endif }
/// <summary> /// Constructor /// </summary> public GetInitialEntityTest() { var inputObjectProcessor = new WSV2.Program.Processor.InputObjectProcessor(); var fileProcessor = new FileProcessor(); var jsonProcessor = new JsonProcessor(fileProcessor); _cloneProcessor = new Program.Processor.CloneProcessor(inputObjectProcessor, jsonProcessor); }
/// <summary> /// Constructor /// </summary> public HandleAllToTest() { var inputObjectProcessor = new WSV2.Program.Processor.InputObjectProcessor(); var fileProcessor = new FileProcessor(); var jsonProcessor = new JsonProcessor(fileProcessor); _cloneProcessor = new Program.Processor.CloneProcessor(inputObjectProcessor, jsonProcessor); }
public static void Main() { var jsonProcessor = new JsonProcessor(); jsonProcessor.InitializeDatabase(); jsonProcessor.ImportData(); jsonProcessor.ExportData(); }
public void TestMultipleJsonObjectAsRootFail() { Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("{},")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("{\"abc\" : \"def\"},")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("{\"abc\" : \"def\" \"def\"}")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("{}, {}")); Assert.ThrowsException <ArgumentException>(() => JsonProcessor.Parse("{},\n{}")); }
public static void Main() { var jsonProcessor = new JsonProcessor(); jsonProcessor.ImportData(); jsonProcessor.ExportData(); }
private string GetFormattedObject(string name, object value) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"{name}"); stringBuilder.AppendLine($"{JsonProcessor.SerializeObject(value, indented: true)}\n"); return(stringBuilder.ToString()); }
private void OnLoadAsset() { animalRegister = JsonProcessor.Deserialize <AnimalRegister>(jsonAsset.text); UpdateLog(); txtJson.text = jsonAsset.text; btnSerialize.interactable = animalRegister != null; btnDeserialize.interactable = !string.IsNullOrWhiteSpace(txtJson.text); }
public SupportAuthPrincipalCreator() { var jsonFile = Path.Combine(JsonFileHelper.ExecutingDir(), ConfigurationManager.AppSettings["SupportAuthFileName"]); if (File.Exists(jsonFile)) { var jsonData = File.ReadAllText(jsonFile); this.supportAuthAgents = JsonProcessor.DeserializeObject <Dictionary <string, AuthClaimsVm> >(jsonData); } }
public EnvironmentAgentRepository() { var jsonData = JsonFileHelper.GetFileContents(_configurationFilePath); Identities = !string.IsNullOrEmpty(jsonData) ? JsonProcessor.DeserializeObject <Dictionary <string, List <EnvironmentAgent> > >(jsonData) : null; Identities = Identities ?? new Dictionary <string, List <EnvironmentAgent> >(); }
public void TestJsonArrayWithElements() { // Just make sure they don't throw exception as we already check their content correctness // in other unit tests. JsonProcessor.Parse("[ \"mura\" ]"); JsonProcessor.Parse("[ \"\u1234\" ]"); JsonProcessor.Parse("[ \"\u1234ff\", \"\u1234\" ]"); JsonProcessor.Parse("[ [], [], [], [] ]"); JsonProcessor.Parse("[ [], [ {}, {} ], [ {} ], [] ]"); }
public void TestJsonObjectWithElements() { // Just make sure they don't throw exception as we already check their content correctness // in other unit tests. JsonProcessor.Parse("{ \"mura\": \"masa\" }"); JsonProcessor.Parse("{ \"mura\": 1234 }"); JsonProcessor.Parse("{ \"mura\": { \"masa\": 1234 } }"); JsonProcessor.Parse("{ \"mura\": { \"masa\": [ 1234 ] } }"); JsonProcessor.Parse("{ \"mura\": { \"masa\": [ 1234 ] }, \"arr\": [] }"); }
private void OnSerialize() { jsonBuilder.Clear(); JsonProcessor.Serialize(animalRegister, jsonBuilder, jsonOptions); btnDeserialize.interactable = (jsonBuilder.Length > 0); UpdateLog(); txtJson.text = jsonBuilder.ToString(); }