private void UpdateValue(string name, IJsonValue value) { IJsonValue existingValue = JsonValue.CreateNullValue(); if (_settingsJson.ContainsKey(name)) { if (value is JsonObject) { existingValue = _settingsJson.GetNamedObject(name); } else { existingValue = _settingsJson.GetNamedValue(name); } if (value.ValueType != existingValue.ValueType) { Log.Warning($"Skipped update of setting '{name}' due to different value types."); return; } if (existingValue.Stringify().Equals(value.Stringify())) { return; } } _settingsJson.SetNamedValue(name, value); ValueChanged?.Invoke(this, new SettingValueChangedEventArgs(name, existingValue, value)); }
public void BasicSerialization() { // Serialize an instance without an ID IJsonValue value = MobileServiceTableSerializer.Serialize( new Person { Name = "John", Age = 45 }); Assert.AreEqual("John", value.Get("Name").AsString()); Assert.AreEqual(45, value.Get("Age").AsInteger()); Assert.IsNull(value.Get("id").AsInteger()); // Ensure the ID is written when provided // Serialize an instance without an ID value = MobileServiceTableSerializer.Serialize( new Person { Id = 2, Name = "John", Age = 45 }); Assert.AreEqual("John", value.Get("Name").AsString()); Assert.AreEqual(45, value.Get("Age").AsInteger()); Assert.AreEqual(2, value.Get("id").AsInteger()); // Ensure other properties are included but null value = MobileServiceTableSerializer.Serialize(new Person { Id = 12 }); string text = value.Stringify(); Assert.That(text, Contains.Substring("Name")); Assert.That(text, Contains.Substring("Age")); Assert.Throws <ArgumentNullException>(() => MobileServiceTableSerializer.Serialize(null)); }
public IAsyncOperationWithProgress <IBuffer, ulong> ReadAsBufferAsync() { return(AsyncInfo.Run <IBuffer, ulong>((cancellationToken, progress) => { return Task <IBuffer> .Run(() => { DataWriter writer = new DataWriter(); writer.WriteString(jsonValue.Stringify()); // Make sure that the DataWriter destructor does not free the buffer. IBuffer buffer = writer.DetachBuffer(); // Report progress. progress.Report(buffer.Length); return buffer; }); })); }
/// <summary> /// Perform a web request and include the standard Mobile Services /// headers. /// </summary> /// <param name="method"> /// The HTTP method used to request the resource. /// </param> /// <param name="uriFragment"> /// URI of the resource to request (relative to the Mobile Services /// runtime). /// </param> /// <param name="content"> /// Optional content to send to the resource. /// </param> /// <param name="ignoreFilters"> /// Optional parameter to indicate if the client filters should be ignored /// and the request should be sent directly. Is <c>false</c> by default. /// </param> /// <returns>The JSON value of the response.</returns> internal async Task <IJsonValue> RequestAsync(string method, string uriFragment, IJsonValue content, bool ignoreFilters = false) { Debug.Assert(!string.IsNullOrEmpty(method), "method cannot be null or empty!"); Debug.Assert(!string.IsNullOrEmpty(uriFragment), "uriFragment cannot be null or empty!"); // Create the web request IServiceFilterRequest request = new ServiceFilterRequest(); request.Uri = new Uri(this.ApplicationUri, uriFragment); request.Method = method.ToUpper(); request.Accept = RequestJsonContentType; // Set Mobile Services authentication, application, and telemetry // headers request.Headers[RequestInstallationIdHeader] = applicationInstallationId; if (!string.IsNullOrEmpty(this.ApplicationKey)) { request.Headers[RequestApplicationKeyHeader] = this.ApplicationKey; } if (this.CurrentUser != null && !string.IsNullOrEmpty(this.CurrentUser.MobileServiceAuthenticationToken)) { request.Headers[RequestAuthenticationHeader] = this.CurrentUser.MobileServiceAuthenticationToken; } // TODO: Set the User-Agent header; currently HttpWebRequest throws when the // User-Agent header is set. // Add any request as JSON if (content != null) { request.ContentType = RequestJsonContentType; request.Content = content.Stringify(); } // Send the request and get the response back as JSON IServiceFilter filter = ignoreFilters ? null : this.filter; IServiceFilterResponse response = await ServiceFilter.ApplyAsync(request, filter); IJsonValue body = GetResponseJsonAsync(response); // Throw errors for any failing responses if (response.ResponseStatus != ServiceFilterResponseStatus.Success || response.StatusCode >= 400) { ThrowInvalidResponse(request, response, body); } return(body); }
/// <summary> /// Perform a web request and include the standard Mobile Services /// headers. /// </summary> /// <param name="method"> /// The HTTP method used to request the resource. /// </param> /// <param name="uriFragment"> /// URI of the resource to request (relative to the Mobile Services /// runtime). /// </param> /// <param name="content"> /// Optional content to send to the resource. /// </param> /// <returns>The JSON value of the response.</returns> internal Task <IJsonValue> RequestAsync(string method, string uriFragment, IJsonValue content) { Debug.Assert(!string.IsNullOrEmpty(method), "method cannot be null or empty!"); Debug.Assert(!string.IsNullOrEmpty(uriFragment), "uriFragment cannot be null or empty!"); // Create the web request IServiceFilterRequest request = new ServiceFilterRequest(); request.Uri = new Uri(this.ApplicationUri, uriFragment); request.Method = method.ToUpper(); request.Accept = RequestJsonContentType; // Set Mobile Services authentication, application, and telemetry // headers request.Headers[RequestInstallationIdHeader] = applicationInstallationId; if (!string.IsNullOrEmpty(this.ApplicationKey)) { request.Headers[RequestApplicationKeyHeader] = this.ApplicationKey; } if (!string.IsNullOrEmpty(this.currentUserAuthenticationToken)) { request.Headers[RequestAuthenticationHeader] = this.currentUserAuthenticationToken; } // Add any request as JSON if (content != null) { request.ContentType = RequestJsonContentType; request.Content = content.Stringify(); } // Send the request and get the response back as JSON return(ServiceFilter.ApplyAsync(request, this.filter) .ContinueWith(t => { var response = t.Result; IJsonValue body = GetResponseJsonAsync(response); // Throw errors for any failing responses if (response.ResponseStatus != ServiceFilterResponseStatus.Success || response.StatusCode >= 400) { ThrowInvalidResponse(request, response, body); } return body; })); }
/// <summary> /// Sends a message to a peer. /// </summary> /// <param name="peerId">ID of the peer to send a message to.</param> /// <param name="json">The json message.</param> /// <returns>True if the message is sent.</returns> public async Task <bool> SendToPeer(int peerId, IJsonValue json) { string message = json.Stringify(); return(await SendToPeer(peerId, message)); }
/// <summary> /// Perform a web request and include the standard Mobile Services /// headers. /// </summary> /// <param name="method"> /// The HTTP method used to request the resource. /// </param> /// <param name="uriFragment"> /// URI of the resource to request (relative to the Mobile Services /// runtime). /// </param> /// <param name="content"> /// Optional content to send to the resource. /// </param> /// <returns>The JSON value of the response.</returns> internal async Task<IJsonValue> RequestAsync(string method, string uriFragment, IJsonValue content) { Debug.Assert(!string.IsNullOrEmpty(method), "method cannot be null or empty!"); Debug.Assert(!string.IsNullOrEmpty(uriFragment), "uriFragment cannot be null or empty!"); // Create the web request IServiceFilterRequest request = new ServiceFilterRequest(); request.Uri = new Uri(this.ApplicationUri, uriFragment); request.Method = method.ToUpper(); request.Accept = RequestJsonContentType; // Set Mobile Services authentication, application, and telemetry // headers request.Headers[RequestInstallationIdHeader] = applicationInstallationId; if (!string.IsNullOrEmpty(this.ApplicationKey)) { request.Headers[RequestApplicationKeyHeader] = this.ApplicationKey; } if (!string.IsNullOrEmpty(this.currentUserAuthenticationToken)) { request.Headers[RequestAuthenticationHeader] = this.currentUserAuthenticationToken; } // Add any request as JSON if (content != null) { request.ContentType = RequestJsonContentType; request.Content = content.Stringify(); } // Send the request and get the response back as JSON IServiceFilterResponse response = await ServiceFilter.ApplyAsync(request, this.filter); IJsonValue body = GetResponseJsonAsync(response); // Throw errors for any failing responses if (response.ResponseStatus != ServiceFilterResponseStatus.Success || response.StatusCode >= 400) { ThrowInvalidResponse(request, response, body); } return body; }
public static object ToObject(this IJsonValue value, Type targetType) { if (value.GetType() == targetType) { return(value); } if (value.ValueType == JsonValueType.Null) { return(null); } if (targetType == typeof(JsonObject)) { return(JsonObject.Parse(value.Stringify())); } if (typeof(IJsonValue).IsAssignableFrom(targetType)) { return(value); } if (targetType == typeof(string)) { return(value.GetString()); } if (targetType == typeof(int) || targetType == typeof(int?)) { return((int)value.GetNumber()); } if (targetType == typeof(long) || targetType == typeof(long?)) { return((long)value.GetNumber()); } if (targetType == typeof(bool) || targetType == typeof(bool?)) { return(value.GetBoolean()); } if (targetType == typeof(float) || targetType == typeof(float?)) { return((float)value.GetNumber()); } if (targetType == typeof(double) || targetType == typeof(double?)) { return(value.GetNumber()); } if (targetType == typeof(decimal) || targetType == typeof(decimal?)) { return((decimal)value.GetNumber()); } if (targetType == typeof(DateTime) || targetType == typeof(DateTime?)) { return(DateTime.Parse(value.GetString())); } if (targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) { return(TimeSpan.Parse(value.GetString())); } throw new NotSupportedException($"Type {targetType} is not supported."); }
public HttpJsonContent(IJsonValue jsonData) { if (jsonData == null) { throw new ArgumentException("jsonData cannot be null."); } InitData(jsonData.Stringify()); }
private async Task<IJsonValue> Post(string command, IJsonValue data) => await Post(command, data.Stringify());
private static DateTime JsonToDateTime(IJsonValue val) { try { DateTime result = new DateTime(1970, 1, 1); string json = val.Stringify(); string datestring = json.Split("()".ToCharArray())[1]; double millis = Convert.ToDouble(datestring); return result.AddMilliseconds(millis); } catch (Exception ex) { } return new DateTime(); }
public override async Task <bool> SendToPeer(int peerId, IJsonValue json) { Debug.WriteLine("SympleSignaller:SendToPeer json: " + peerId + " " + json); Debug.Assert(IsConnected()); if (!IsConnected()) { return(false); } if (_localIntIdsToServerIds.ContainsKey(peerId)) { string peerServerId = _localIntIdsToServerIds[peerId]; PeerData recipientPeerData = _roster[peerServerId]; Debug.WriteLine("original IJsonValue: " + json); JObject jsonMessage = JObject.Parse(json.Stringify()); Debug.WriteLine("after conversion to JObject: " + jsonMessage); if (jsonMessage["sdp"] != null) { JObject sessionDesc = jsonMessage; JObject parameters = new JObject(); parameters["to"] = peerDataToJObject(recipientPeerData); parameters["type"] = "message"; string jsonMessageType = (string)jsonMessage["type"]; if (jsonMessageType == "offer") { parameters["offer"] = sessionDesc; } else if (jsonMessageType == "answer") { parameters["answer"] = sessionDesc; } else { Debug.WriteLine("unknown jsonMessageType for sdp: " + jsonMessageType); throw new NotImplementedException(); } send(parameters); return(true); } if (jsonMessage["candidate"] != null) { JObject candidateObj = jsonMessage; JObject parameters = new JObject(); parameters["to"] = peerDataToJObject(recipientPeerData); parameters["type"] = "message"; parameters["candidate"] = candidateObj; send(parameters); return(true); } if (jsonMessage["message"] != null) { // sending a misc. message to the peer. var msgObj = jsonMessage["message"]; // note that we go down one level here JObject parameters = new JObject(); parameters["to"] = peerDataToJObject(recipientPeerData); parameters["type"] = "message"; parameters["message"] = msgObj; send(parameters); return(true); } Debug.WriteLine("unknown message of type " + jsonMessage); throw new NotImplementedException(); } else { Debug.WriteLine("attempted SendToPeer on unknown peer id " + peerId); throw new NotImplementedException(); } }
private static ZumoTest CreatePushTest(string wnsMethod, IJsonValue payload, XElement expectedResult) { string testName = "Test for " + wnsMethod + ": "; string payloadString = payload.Stringify(); testName += payloadString.Length < 15 ? payloadString : (payloadString.Substring(0, 15) + "..."); return(new ZumoTest(testName, async delegate(ZumoTest test) { test.AddLog("Test for method {0}, with payload {1}", wnsMethod, payload.Stringify()); var client = ZumoTestGlobals.Instance.Client; var table = client.GetTable(ZumoTestGlobals.PushTestTableName); PushWatcher watcher = new PushWatcher(); var item = new JsonObject(); item.Add("method", JsonValue.CreateStringValue(wnsMethod)); item.Add("channelUri", JsonValue.CreateStringValue(pushChannel.Uri)); item.Add("payload", payload); var pushResult = await table.InsertAsync(item); test.AddLog("Push result: {0}", pushResult.Stringify()); var notificationResult = await watcher.WaitForPush(TimeSpan.FromSeconds(10)); if (notificationResult == null) { test.AddLog("Error, push not received on the timeout allowed"); return false; } else { test.AddLog("Push notification received:"); XElement receivedPushInfo = null; switch (notificationResult.NotificationType) { case PushNotificationType.Raw: receivedPushInfo = new XElement("raw", new XText(notificationResult.RawNotification.Content)); break; case PushNotificationType.Toast: receivedPushInfo = XElement.Parse(notificationResult.ToastNotification.Content.GetXml()); break; case PushNotificationType.Badge: receivedPushInfo = XElement.Parse(notificationResult.BadgeNotification.Content.GetXml()); break; case PushNotificationType.Tile: receivedPushInfo = XElement.Parse(notificationResult.TileNotification.Content.GetXml()); break; } test.AddLog(" {0}: {1}", notificationResult.NotificationType, receivedPushInfo); bool passed; if (expectedResult.ToString(SaveOptions.DisableFormatting) == receivedPushInfo.ToString(SaveOptions.DisableFormatting)) { test.AddLog("Received notification is the expected one."); passed = true; } else { test.AddLog("Received notification is not the expected one. Expected:"); test.AddLog(expectedResult.ToString()); test.AddLog("Actual:"); test.AddLog(receivedPushInfo.ToString()); passed = false; } await Task.Delay(5000); // leave some time between pushes return passed; } })); }
public static bool CompareJson(IJsonValue expected, IJsonValue actual, List <string> errors) { if (expected == null) { return(actual == null); } if (actual == null) { return(false); } if (expected.ValueType != actual.ValueType) { errors.Add(string.Format("Expected value type {0} != actual {1}", expected.ValueType, actual.ValueType)); return(false); } switch (expected.ValueType) { case JsonValueType.Boolean: return(expected.GetBoolean() == actual.GetBoolean()); case JsonValueType.Null: return(true); case JsonValueType.String: return(expected.GetString() == actual.GetString()); case JsonValueType.Number: double expectedNumber = expected.GetNumber(); double actualNumber = actual.GetNumber(); double delta = 1 - expectedNumber / actualNumber; double acceptableEpsilon = 0.000001; if (Math.Abs(delta) > acceptableEpsilon) { errors.Add(string.Format("Numbers differ more than the allowed difference: {0} - {1}", expected.Stringify(), actual.Stringify())); return(false); } else { return(true); } case JsonValueType.Array: JsonArray expectedArray = expected.GetArray(); JsonArray actualArray = actual.GetArray(); if (expectedArray.Count != actualArray.Count) { errors.Add(string.Format("Size of arrays are different: expected {0} != actual {1}", expectedArray.Count, actualArray.Count)); return(false); } for (int i = 0; i < expectedArray.Count; i++) { if (!CompareJson(expectedArray[i], actualArray[i], errors)) { errors.Add("Difference in array item at index " + i); return(false); } } return(true); case JsonValueType.Object: JsonObject expectedObject = expected.GetObject(); JsonObject actualObject = actual.GetObject(); foreach (var key in expectedObject.Keys) { if (key == "id") { continue; // set by server, ignored at comparison } if (!actualObject.ContainsKey(key)) { errors.Add(string.Format("Expected object contains a pair with key {0}, actual does not.", key)); return(false); } if (!CompareJson(expectedObject[key], actualObject[key], errors)) { errors.Add("Difference in object member with key " + key); return(false); } } return(true); default: throw new ArgumentException("Don't know how to compare IJsonValue of type " + expected.ValueType); } }
private static ZumoTest CreatePushTest(string wnsMethod, IJsonValue payload, XElement expectedResult) { string testName = "Test for " + wnsMethod + ": "; string payloadString = payload.Stringify(); testName += payloadString.Length < 15 ? payloadString : (payloadString.Substring(0, 15) + "..."); return new ZumoTest(testName, async delegate(ZumoTest test) { test.AddLog("Test for method {0}, with payload {1}", wnsMethod, payload.Stringify()); var client = ZumoTestGlobals.Instance.Client; var table = client.GetTable(ZumoTestGlobals.PushTestTableName); PushWatcher watcher = new PushWatcher(); var item = new JsonObject(); item.Add("method", JsonValue.CreateStringValue(wnsMethod)); item.Add("channelUri", JsonValue.CreateStringValue(pushChannel.Uri)); item.Add("payload", payload); var pushResult = await table.InsertAsync(item); test.AddLog("Push result: {0}", pushResult.Stringify()); var notificationResult = await watcher.WaitForPush(TimeSpan.FromSeconds(10)); if (notificationResult == null) { test.AddLog("Error, push not received on the timeout allowed"); return false; } else { test.AddLog("Push notification received:"); XElement receivedPushInfo = null; switch (notificationResult.NotificationType) { case PushNotificationType.Raw: receivedPushInfo = new XElement("raw", new XText(notificationResult.RawNotification.Content)); break; case PushNotificationType.Toast: receivedPushInfo = XElement.Parse(notificationResult.ToastNotification.Content.GetXml()); break; case PushNotificationType.Badge: receivedPushInfo = XElement.Parse(notificationResult.BadgeNotification.Content.GetXml()); break; case PushNotificationType.Tile: receivedPushInfo = XElement.Parse(notificationResult.TileNotification.Content.GetXml()); break; } test.AddLog(" {0}: {1}", notificationResult.NotificationType, receivedPushInfo); bool passed; if (expectedResult.ToString(SaveOptions.DisableFormatting) == receivedPushInfo.ToString(SaveOptions.DisableFormatting)) { test.AddLog("Received notification is the expected one."); passed = true; } else { test.AddLog("Received notification is not the expected one. Expected:"); test.AddLog(expectedResult.ToString()); test.AddLog("Actual:"); test.AddLog(receivedPushInfo.ToString()); passed = false; } await Task.Delay(5000); // leave some time between pushes return passed; } }); }
private async Task <IJsonValue> Post(string command, IJsonValue data) => await Post(command, data.Stringify());