public void SmartObjectDeserializeTest() { DateTime now = TestUtils.GetNowIgnoringMilis(); string json = "{\"x_device_id\":\"test\"," + "\"x_object_type\":\"type\"," + "\"x_registration_date\":\"" + now.ToString(EventSerializerTest.DatetimeFormat) + "\"," + "\"age\": 89," + "\"weight\": 125.5," + "\"married\": true," + "\"counter\": -13582," + "\"list_SmartObject\": [\"val1\",\"val2\",\"val3\"]," + "\"x_owner\" : { \"username\":\"owner\",\"sometrash\":8888}}"; var attributes = ImmutableDictionary.CreateBuilder <string, object>(); attributes.Add("age", 89); attributes.Add("weight", 125.5); attributes.Add("married", true); attributes.Add("counter", -13582); attributes.Add("list_SmartObject", new string[] { "val1", "val2", "val3" }); SmartObject SmartObject = ObjectSerializer.DeserializeObject(json); Assert.AreEqual(SmartObject.DeviceId, "test"); Assert.AreEqual(SmartObject.ObjectType, "type"); Assert.AreEqual(SmartObject.Username, "owner"); Assert.AreEqual(SmartObject.RegistrationDate.Value.ToString(EventSerializerTest.DatetimeFormat), now.ToString(EventSerializerTest.DatetimeFormat)); Assert.AreEqual(SmartObject.RegistrationDateTime.Value.ToString(EventSerializerTest.DatetimeFormat), now.ToString(EventSerializerTest.DatetimeFormat)); CollectionAssert.AreEqual(SmartObject.Attributes, attributes.ToImmutable()); }
public void SmartObjectDeserializeTestWrongRegistrationTimeType() { string json = "{\"x_registration_date\":\"5454544578f\"}"; Assert.That(() => ObjectSerializer.DeserializeObject(json), Throws.TypeOf <InvalidOperationException>() .With.Message.EqualTo("Field 'x_registration_date' does not match TYPE 'DATETIME'")); }
public void SmartObjectDeserializeTestWrongOwnerType() { string json = "{\"x_owner\":\"5454544578f\"}"; Assert.That(() => ObjectSerializer.DeserializeObject(json), Throws.TypeOf <InvalidOperationException>() .With.Message.EqualTo("Field 'x_owner' does not match TYPE 'OWNER'")); }
public void SmartObjectDeserializeTestWrongObjectType() { string json = "{\"x_object_type\":false}"; Assert.That(() => ObjectSerializer.DeserializeObject(json), Throws.TypeOf <InvalidOperationException>() .With.Message.EqualTo("Field 'x_object_type' does not match TYPE 'TEXT'")); }
public void SmartObjectDeserializeTestWrongDeviceIdType() { string json = "{\"x_device_id\":9898.3}"; Assert.That(() => ObjectSerializer.DeserializeObject(json), Throws.TypeOf <InvalidOperationException>() .With.Message.EqualTo("Field 'x_device_id' does not match TYPE 'TEXT'")); }
public void SmartObjectDeserializeTestWrongEventIdType() { string json = "{\"event_id\":\"54545c5454-054-54\",\"string\":\"stringValue\"}"; Assert.That(() => ObjectSerializer.DeserializeObject(json), Throws.TypeOf <InvalidOperationException>() .With.Message.EqualTo("Field 'x_event_id' does not match TYPE 'GUID'")); }
private ICacheStorageCollection BuildCollection() { var buffer = _distributedCache.Get(_options.CacheKey); return(buffer == null ? new CacheStorageCollection() : ObjectSerializer.DeserializeObject <ICacheStorageCollection>(buffer)); }
private async void LoadPageFromNotification(NotificationTappedEventArgs e) { var serializer = new ObjectSerializer <List <string> >(); var list = serializer.DeserializeObject(e.Data); Reminder tappedReminder = await databaseHelper.GetReminderAsync(int.Parse(list[0])); await MainPage.Navigation.PushModalAsync(new NavigationPage(new ReminderPage(tappedReminder))); }
void OnLevelCompleated() // add transition pattern { ChangeColors(); _spawner.SetNewPattern(ObjectSerializer.DeserializeObject(_transitionPattern)); SetLevel(Progress.Levels.Level + 1); }
public static List <SmartObject> DeserializeObjects(string json) { List <SmartObject> objects = new List <SmartObject>(); foreach (var jsonObject in JArray.Parse(json)) { objects.Add(ObjectSerializer.DeserializeObject(jsonObject.ToString(Formatting.None))); } return(objects); }
public MethodCall(XmlNode eventNode, Func <XmlNode, object, object> switchParameter, params Assembly[] assemblies) { foreach (Assembly assembly in assemblies) { ObjectSerializer.RegisterAssembly(assembly); } _type = eventNode.Name; XmlAttribute nameAttr = eventNode.Attributes["Name"]; XmlAttribute interfaceAttr = eventNode.Attributes["Interface"]; XmlAttribute hashAttr = eventNode.Attributes["Hash"]; if (nameAttr == null) { throw new InvalidOperationException("Unable to create " + _type + ". Name attribute not set."); } if (interfaceAttr == null) { throw new InvalidOperationException("Unable to create " + _type + " for " + nameAttr.Value + ". Interface attribute not set."); } _name = nameAttr.Value; _interface = interfaceAttr.Value; _hash = hashAttr == null ? "0" : hashAttr.Value; if (eventNode.FirstChild == null) { _return = null; _parameters = new object[0]; return; } XmlNode child = eventNode.FirstChild; if (child.Name.Equals("Parameters")) { _parameters = new object[child.ChildNodes.Count]; for (int i = 0; i < _parameters.Length; i++) { XmlNode paramNode = child.ChildNodes[i]; _parameters[i] = switchParameter(paramNode, ObjectSerializer.DeserializeObject(paramNode)); } child = child.NextSibling; } else { _parameters = new object[0]; } if (child != null && child.Name.Equals("Return")) { _return = ObjectSerializer.DeserializeObject(child); } }
void GetNewPattern() { if (_difficultyConfig == null) { return; } _currentPatterinTextAsset = GetRandomPatternNum(_difficultyConfig.GetLevelConfig(_currentDistance).TextAssets); _spawner.SetNewPattern(ObjectSerializer.DeserializeObject(_currentPatterinTextAsset)); }
public void SmartObjectDeserializeTestWithUsernameNull() { string json = "{\"x_owner\" : { \"sometrash\":8888} }"; SmartObject SmartObject = ObjectSerializer.DeserializeObject(json); Assert.IsNull(SmartObject.DeviceId); Assert.IsNull(SmartObject.ObjectType); Assert.IsNull(SmartObject.Username); Assert.IsNull(SmartObject.RegistrationDate); Assert.AreEqual(SmartObject.Attributes.Count, 0); }
public void SmartObjectDeserializeTestCheckNull() { string json = "{}"; SmartObject SmartObject = ObjectSerializer.DeserializeObject(json); Assert.IsNull(SmartObject.DeviceId); Assert.IsNull(SmartObject.ObjectType); Assert.IsNull(SmartObject.RegistrationDate); Assert.IsNull(SmartObject.Username); Assert.IsNotNull(SmartObject.Attributes); Assert.AreEqual(SmartObject.Attributes.Count, 0); }
/// <summary> /// Deserializes the XElement to the specified .NET type using options. /// </summary> /// <param name="type">The type of the deserialized .NET object.</param> /// <param name="element">The XElement to deserialize.</param> /// <param name="options">Indicates how the output is deserialized.</param> /// <returns>The deserialized object from the XElement.</returns> public static object DeserializeXElement(Type type, XElement element, XmlConvertOptions options) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (element == null) { throw new ArgumentNullException(nameof(element)); } return(ObjectSerializer.DeserializeObject(type, element, options)); }
public static RegistrationInfo ReadKey(String licenseKey, IListener listener) { RegistrationInfo registrationInfo = null; try { // Caso licenseKey esteja vazia estoura ArgumentNullException, caso licenseKey não // esteja em Base64 estoura FormatException e assim por diante Byte[] decodedKey = Convert.FromBase64String(licenseKey); String serializedObject = Encoding.UTF8.GetString(decodedKey); registrationInfo = (RegistrationInfo)ObjectSerializer.DeserializeObject(serializedObject, typeof(RegistrationInfo)); } catch (Exception exception) // O conteudo da licença não é válido { AddExceptionData(exception, "License Key = " + licenseKey, null); listener.NotifyObject(exception); return(null); } // Verifica se o conteúdo da licença está no formato esperado if (registrationInfo == null) { listener.NotifyObject(new Exception("O conteúdo da licença não está no formato esperado.")); return(null); } // Verifica se o usuário tentou forjar uma licença falsa if (registrationInfo.Hash == null) { Exception hashException = new Exception("O hash não estava presente na chave."); AddExceptionData(hashException, "License Key = " + licenseKey, null); listener.NotifyObject(hashException); return(null); } String hashInput = registrationInfo.ServiceUrl + registrationInfo.TenantId + registrationInfo.LicenseId + registrationInfo.Version + registrationInfo.ExpirationDate.ToString("yyyy-MM-ddTHH:mm:ss"); String hash = Cipher.GenerateHash(hashInput); if (registrationInfo.Hash != hash) { Exception hashException = new Exception("O hash não confere."); AddExceptionData(hashException, "License Key = " + licenseKey, "Hash Input = " + hashInput); listener.NotifyObject(hashException); return(null); } return(registrationInfo); }
public override bool OnStartJob(JobParameters jobParams) { if (jobParams.Extras.ContainsKey(LocalNotificationService.ExtraReturnNotification) == false) { return(false); } var serializedNotification = jobParams.Extras.GetString(LocalNotificationService.ExtraReturnNotification); var notification = ObjectSerializer <LocalNotification> .DeserializeObject(serializedNotification); var notificationService = Xamarin.Forms.DependencyService.Get <ILocalNotificationService>(); notificationService.Show(notification); return(true); }
public override Result DoWork() { var serializedNotification = InputData.GetString(NotificationCenter.ExtraReturnNotification); if (string.IsNullOrWhiteSpace(serializedNotification)) { return(Result.InvokeFailure()); } Task.Run(() => { var notification = ObjectSerializer <NotificationRequest> .DeserializeObject(serializedNotification); NotificationCenter.Current.Show(notification); }); return(Result.InvokeSuccess()); }
public override bool OnStartJob(JobParameters jobParams) { if (jobParams.Extras.ContainsKey(NotificationCenter.ExtraReturnNotification) == false) { return(false); } Task.Run(() => { JobFinished(jobParams, false); var serializedNotification = jobParams.Extras.GetString(NotificationCenter.ExtraReturnNotification); var notification = ObjectSerializer <NotificationRequest> .DeserializeObject(serializedNotification); NotificationCenter.Current.Show(notification); }); return(true); }
public override void OnReceive(Context context, Intent intent) { try { if (intent.HasExtra(LocalNotificationService.ExtraReturnNotification) == false) { return; } var serializedNotification = intent.GetStringExtra(LocalNotificationService.ExtraReturnNotification); var notification = ObjectSerializer <LocalNotification> .DeserializeObject(serializedNotification); var notificationService = Xamarin.Forms.DependencyService.Get <ILocalNotificationService>(); notificationService.Show(notification); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
private void LoadPageFromNotification(NotificationTappedEventArgs e) { if (string.IsNullOrWhiteSpace(e.Data)) { return; } var list = ObjectSerializer.DeserializeObject <List <string> >(e.Data); if (list.Count != 2) { return; } if (list[0] != typeof(NotificationPage).FullName) { return; } var tapCount = list[1]; ((NavigationPage)MainPage).Navigation.PushAsync(new NotificationPage(int.Parse(tapCount))); }
void GetNewPattern() { if (_patterns == null) { return; } if (_patterns.Length <= _currentPattern) { _onComplete?.Invoke(); return; } var currentPattern = ObjectSerializer.DeserializeObject(_patterns[_currentPattern]); _spawner.SetNewPattern(currentPattern); _currentPattern++; }
private void LoadPageFromNotification(LocalNotificationTappedEvent e) { if (string.IsNullOrWhiteSpace(e.Data)) { return; } var list = ObjectSerializer <List <string> > .DeserializeObject(e.Data); if (list.Count != 2) { return; } if (list[0] != typeof(NotificationPage).FullName) { return; } var tapCount = list[1]; MainPage = new NotificationPage(int.Parse(tapCount)); }
private void LoadPageFromNotification(NotificationTappedEventArgs e) { if (string.IsNullOrWhiteSpace(e.Data)) { return; } var list = ObjectSerializer <List <string> > .DeserializeObject(e.Data); //if (list.Count != 2) //{ // return; //} if (list[0] != typeof(NotificationPage).FullName) { return; } //var tapCount = list[1]; MainPage = new NotificationPage(); }
public bool CheckAndMakeCacheFile(List <EventTriggerModel> saves, string path) { var isNewCreated = false; var isExists = File.Exists(path); if (isExists && saves.Count > 0) { var bytes = File.ReadAllBytes(path); _commonCacheData = ObjectSerializer.DeserializeObject <CacheModel>(bytes).FirstOrDefault(); } else { isNewCreated = true; } foreach (var save in saves) { MakeIndexTriggerModel(save); InsertIndexTriggerModel(save); } UpdateCacheData(path, _commonCacheData); return(isNewCreated); }
public static string TestObjectSerializer(ScreenManager screenMan, out int errorsAdded) { int num = 0; string str = ""; List <string> stringList1 = new List <string>(); List <string> stringList2 = (List <string>)ObjectSerializer.DeserializeObject(Utils.GenerateStreamFromString(ObjectSerializer.SerializeObject((object)stringList1)), stringList1.GetType()); if (stringList2 == null || stringList2.Count != 0) { ++num; str += "\nError deserializing empty list"; } stringList1.Add("test 1"); stringList1.Add("12345"); List <string> stringList3 = (List <string>)ObjectSerializer.DeepCopy((object)stringList1); if (stringList3.Count != 2 || stringList3[0] != "test 1" || stringList3[1] != "12345") { ++num; str += "\nError deserializing empty list"; } VehicleRegistration self = new VehicleRegistration() { licenceNumber = "1123-123", licencePlate = "11-11", vehicle = new VehicleType() { maker = "asdf", model = "another asdf" } }; VehicleRegistration to = (VehicleRegistration)ObjectSerializer.DeepCopy((object)self); if (!Utils.PublicInstancePropertiesEqual <VehicleRegistration>(self, to)) { ++num; str += "\nError auto deserializing vehicle info\n"; } errorsAdded = num; return(str); }
private Task SaveFileLoad(object state) { if (state is SaveFileLoadModel model) { try { var saveFiles = ObjectSerializer.DeserializeObject <EventTriggerModel>(File.ReadAllBytes(model.SaveFilePath)); if (ObjectExtensions.GetInstance <CacheDataManager>().CheckAndMakeCacheFile(saveFiles, model.CacheFilePath)) { model.View.Save(saveFiles); } model.View.SaveDataBind(saveFiles); } catch (Exception ex) { File.Delete(model.SaveFilePath); LogHelper.Warning(ex); Task.FromException(new FileLoadException(DocumentHelper.Get(Message.FailedLoadSaveFile))); } } return(Task.CompletedTask); }
public SucceedAPIsMockModule() { Post(BasePath + "objects", x => { TestUtils.AssertObjectEquals(TestUtils.CreateTestObject(), ObjectSerializer.DeserializeObject(NancyUtils.BodyAsString(this.Request))); return(201); }); Put(BasePath + "objects", x => { List <SmartObject> objects = TestUtils.DeserializeObjects(NancyUtils.BodyAsString(this.Request)); TestUtils.AssertObjectsEqual(TestUtils.CreateObjects(objects.Count <SmartObject>()), objects); List <Result> results = new List <Result>(); foreach (SmartObject anObject in objects) { results.Add(new Result(anObject.DeviceId, Result.ResultStates.Success, null)); } return(JsonConvert.SerializeObject(results)); }); Put(BasePath + "objects/{deviceId}", x => { TestUtils.AssertObjectEquals(TestUtils.CreateObjectUpdateAttribute(), ObjectSerializer.DeserializeObject(NancyUtils.BodyAsString(this.Request))); Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId); return(200); }); Delete(BasePath + "objects/{deviceId}", x => { Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId); return(200); }); Get(BasePath + "objects/exists/{deviceId}", x => { var deviceId = (string)x.deviceId; Assert.AreEqual(TestUtils.DeviceId, deviceId); IDictionary <string, bool> result = new Dictionary <string, bool>() { { deviceId, true } }; return(JsonConvert.SerializeObject(result)); }); Post(BasePath + "owners", x => { TestUtils.AssertOwnerEquals(TestUtils.CreateTestOwner(), OwnerSerializer.DeserializeOwner(NancyUtils.BodyAsString(this.Request))); return(201); }); Put(BasePath + "owners", x => { List <Owner> owners = TestUtils.DeserializeOwners(NancyUtils.BodyAsString(this.Request)); TestUtils.AssertOwnersEqual(TestUtils.CreateOwners(owners.Count <Owner>()), owners); List <Result> results = new List <Result>(); foreach (Owner owner in owners) { results.Add(new Result(owner.Username, Result.ResultStates.Success, null)); } return(JsonConvert.SerializeObject(results)); }); Put(BasePath + "owners/{username}", x => { TestUtils.AssertOwnerEquals(TestUtils.CreateOwnerUpdateAttribute(), OwnerSerializer.DeserializeOwner(NancyUtils.BodyAsString(this.Request))); Assert.AreEqual(TestUtils.Username, (string)x.username); return(200); }); Put(BasePath + "owners/{username}/password", x => { Dictionary <string, string> body = JsonConvert.DeserializeObject <Dictionary <string, string> >(NancyUtils.BodyAsString(this.Request)); Assert.IsTrue(body.ContainsKey("x_password")); String password = ""; body.TryGetValue("x_password", out password); Assert.AreEqual(TestUtils.Password, password); Assert.AreEqual(TestUtils.Username, (string)x.username); return(200); }); Post(BasePath + "owners/{username}/objects/{deviceId}/claim", x => { Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId); Assert.AreEqual(TestUtils.Username, (string)x.username); return(200); }); Post(BasePath + "owners/{username}/objects/{deviceId}/unclaim", x => { Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId); Assert.AreEqual(TestUtils.Username, (string)x.username); return(200); }); Delete(BasePath + "owners/{username}", x => { Assert.AreEqual(TestUtils.Username, (string)x.username); return(200); }); Get(BasePath + "owners/exists/{username}", x => { string username = (string)x.username; Assert.AreEqual(TestUtils.Username, username); IDictionary <string, bool> result = new Dictionary <string, bool>() { { username, true } }; return(JsonConvert.SerializeObject(result)); }); Post(BasePath + "events", x => { bool reportResults = (bool)this.Request.Query["report_results"]; Assert.AreEqual(true, reportResults); List <EventResult> results = TestUtils.EventsToSuccesfullResults(NancyUtils.BodyAsString(this.Request)); return(JsonConvert.SerializeObject(results)); }); Get(BasePath + "events/exists/{eventId}", x => { IDictionary <string, bool> result = new Dictionary <string, bool>() { { (string)x.eventId, true } }; return(JsonConvert.SerializeObject(result)); }); Get(BasePath + "search/datasets", x => { return(JsonConvert.SerializeObject(TestUtils.CreateDatasets())); }); Post(BasePath + "search/basic", x => { Assert.AreEqual(TestUtils.CreateQuery(), NancyUtils.BodyAsString(this.Request)); return(TestUtils.CreateExpectedSearchResult()); }); // test HttpClient itself Post(BasePath + "compressed", x => { if (!NancyUtils.IsGzipCompressed(this.Request)) { return(FailedAPIsMockModule.badRequest()); } if (!this.Request.Headers.AcceptEncoding.Contains("gzip")) { return(FailedAPIsMockModule.badRequest()); } var body = NancyUtils.BodyAsString(this.Request); if (body != TestJsonString) { return(FailedAPIsMockModule.badRequest()); } var data = Encoding.UTF8.GetBytes(body); var response = new Response(); response.Headers.Add("Content-Encoding", "gzip"); response.Headers.Add("Content-Type", "application/json"); response.Contents = stream => { using (var gz = new GZipStream(stream, CompressionMode.Compress)) { gz.Write(data, 0, data.Length); gz.Flush(); } }; return(response); }); Post(BasePath + "decompressed", x => { if (NancyUtils.IsGzipCompressed(this.Request)) { return(FailedAPIsMockModule.badRequest()); } var body = NancyUtils.BodyAsString(this.Request); if (body != TestJsonString) { return(FailedAPIsMockModule.badRequest()); } return(TestJsonString); }); Post(BasePath + "tokencheck", x => { return(this.Request.Headers.Authorization); }); }
public override Result DoWork() { var serializedNotification = InputData.GetString(NotificationCenter.ExtraReturnNotification); if (string.IsNullOrWhiteSpace(serializedNotification)) { return(Result.InvokeFailure()); } var serializedNotificationAndroid = InputData.GetString($"{NotificationCenter.ExtraReturnNotification}_Android"); Task.Run(() => { try { Log.Info(Application.Context.PackageName, $"ScheduledNotificationWorker.DoWork: SerializedNotification [{serializedNotification}]"); var notification = ObjectSerializer.DeserializeObject <NotificationRequest>(serializedNotification); if (string.IsNullOrWhiteSpace(serializedNotificationAndroid) == false) { var notificationAndroid = ObjectSerializer.DeserializeObject <AndroidOptions>(serializedNotificationAndroid); if (notificationAndroid != null) { notification.Android = notificationAndroid; } } if (notification.NotifyTime.HasValue && notification.Repeats != NotificationRepeat.No) { switch (notification.Repeats) { case NotificationRepeat.Daily: // To be consistent with iOS, Schedule notification next day same time. notification.NotifyTime = notification.NotifyTime.Value.AddDays(1); break; case NotificationRepeat.Weekly: // To be consistent with iOS, Schedule notification next week same day same time. notification.NotifyTime = notification.NotifyTime.Value.AddDays(7); break; case NotificationRepeat.TimeInterval: if (notification.NotifyRepeatInterval.HasValue) { TimeSpan interval = notification.NotifyRepeatInterval.Value; notification.NotifyTime = notification.NotifyTime.Value.Add(interval); } break; } var notificationService = TryGetDefaultDroidNotificationService(); notificationService.ShowNow(notification, false); notificationService.EnqueueWorker(notification); return; } // To be consistent with iOS, Do not show notification if NotifyTime is earlier than DateTime.Now if (notification.NotifyTime != null && notification.NotifyTime.Value <= DateTime.Now.AddMinutes(-1)) { System.Diagnostics.Debug.WriteLine("NotifyTime is earlier than DateTime.Now, notification ignored"); return; } notification.NotifyTime = null; NotificationCenter.Current.Show(notification); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }); return(Result.InvokeSuccess()); }
float GetLevelDistance(IEnumerable <TextAsset> patterns) { return(patterns.Sum(t => ObjectSerializer.DeserializeObject(t).Size.z)); }