public void sendRequestHttpPost(string url, JsonObject mJsonObject, Dictionary <String, String> headers, Callback mCallbackPost) { var client = new RestClient(url); // client.Authenticator = new HttpBasicAuthenticator(username, password); Console.Write("URL? " + url); var request = new RestRequest(); Console.WriteLine("sending " + mJsonObject.ToString()); request.AddJsonBody(mJsonObject.ToString()); client.PostAsync(request, (IRestResponse arg1, RestRequestAsyncHandle arg2) => { var o = JsonObject.Parse(arg1.Content); if (mCallbackPost != null) { JsonObject obj = (System.Json.JsonObject)o; Console.WriteLine("received2 " + obj.ToString()); if (handleUnregistered(obj, getHandler(), mCallbackPost)) { return; } else { Console.WriteLine("Handle normally"); mCallbackPost.onResponse(obj); } } }); }
public void PostEntry() { var json = new JsonObject(); json["command"] = "entry"; var send = "data=" + json.ToString(); network.SendPostRequest(send); }
protected JsonObject Call(string subpath, string method = "GET", string contentType = "application/text", string data = "") { string uri; uri = String.Format("https://{0}{1}", _options["api_base"], GetPath(subpath)); if(_sessionId != null && _sessionId != "") { uri = String.Format("{0}{1}", uri, String.Format("&hs={0}", _sessionId)); } Debug.WriteLine(uri); var returnVal = UserWebClient.UploadString(uri, method: method, contentType: contentType, data: data); if (returnVal != null) { if (returnVal.Length > 0) { JsonObject o = new JsonObject(JsonValue.Parse(returnVal)); if (SuccessfulCall(o)) { return o; } else { var response = JsonConvert.DeserializeObject<Helpers.APIResponse>(o.ToString()); throw new Exception(String.Format("Unsuccessful call to web api. {0}", response.result.code), new Exception(String.Format("{0}", response.result.description))); } } } return new JsonObject(); }
protected Boolean handleUnregistered(JsonObject t, UnregisteredErrorCallback mCallback, Callback mCallbackPost) { if (t.ContainsKey("response_error")) { JsonObject er = (System.Json.JsonObject)t["response_error"]; Console.WriteLine("Contains resp error" + er["response_code"].Equals("40") ); if (Int32.Parse(er["response_code"]) == 40) { Console.WriteLine("COntains 40"); Console.WriteLine("Unregister"); try { UnregisteredError e = JsonConvert.DeserializeObject <UnregisteredError>( t.ToString()); mCallback.onUserNotRegistered(e); // Console.WriteLine("UNREG"); return(true); } catch (Exception e) { mCallbackPost.onFailure(e); } } } Console.WriteLine("Not Unregister"); return(false); }
public void ValidJsonObjectRoundTrip() { bool oldValue = CreatorSettings.CreateDateTimeWithSubMilliseconds; CreatorSettings.CreateDateTimeWithSubMilliseconds = false; try { int seed = 1; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); JsonObject sourceJson = new JsonObject(new Dictionary<string, JsonValue>() { { "Name", PrimitiveCreator.CreateInstanceOfString(rndGen) }, { "Age", PrimitiveCreator.CreateInstanceOfInt32(rndGen) }, { "DateTimeOffset", PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen) }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } }); sourceJson.Add("NewItem1", PrimitiveCreator.CreateInstanceOfString(rndGen)); sourceJson.Add(new KeyValuePair<string, JsonValue>("NewItem2", PrimitiveCreator.CreateInstanceOfString(rndGen))); JsonObject newJson = (JsonObject)JsonValue.Parse(sourceJson.ToString()); newJson.Remove("NewItem1"); sourceJson.Remove("NewItem1"); Assert.False(newJson.ContainsKey("NewItem1")); Assert.False(!JsonValueVerifier.Compare(sourceJson, newJson)); } finally { CreatorSettings.CreateDateTimeWithSubMilliseconds = oldValue; } }
//Using ModernHTTPClient private async Task<JsonValue> AnswerHttp(string question) { JsonValue jsonDoc = null; const string dataset = "travel"; var questionJson = new JsonObject(); questionJson.Add("questionText", question); var evidenceRequest = new JsonObject(); evidenceRequest.Add("items", 1); questionJson.Add("evidenceRequest", evidenceRequest); var postData = new JsonObject(); postData.Add("question", questionJson); string text = postData.ToString(); var _nativehandler = new NativeMessageHandler (); using (var content = new StringContent(text, Encoding.UTF8, "application/json")) using (var client = new HttpClient(_nativehandler)) { client.DefaultRequestHeaders.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes( string.Format("{0}:{1}", username,password)))); client.DefaultRequestHeaders.Accept.Add (new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue ("application/json")); var response = await client.PostAsync(baseURL, content).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var jsonOut = await response.Content.ReadAsStringAsync().ConfigureAwait(false); jsonDoc = await Task.Run (() => JsonObject.Parse (jsonOut)); } } return jsonDoc; }
/// <summary> /// JSON 文字列に変換します。 /// </summary> /// <returns>JSON 文字列。</returns> public string ToJsonString() { var obj = new JsonObject(DateTimeOffset.Now); obj.Add(TaskMeta.Name, (JsonValue)Name); obj.Add(TaskMeta.Done, (JsonValue)Done); return obj.ToString(); }
private string GetJSONValue(Person person) { dynamic json = new JsonObject(); json.Id = person.Id; json.Balance = person.Balance; json.DomainName = person.DomainName; return json.ToString(); }
public void JsonObjectOrder () { var obj = new JsonObject (); obj["a"] = 1; obj["c"] = 3; obj["b"] = 2; var str = obj.ToString (); Assert.AreEqual (str, "{\"a\": 1, \"b\": 2, \"c\": 3}"); }
public void StartPolling() { var data = new JsonObject(); data["command"] = "polling"; data["matchKeyName"] = game.Match.KeyName; var pollingData = "data=" + data.ToString(); network.StartPolling(pollingData); }
public void PostClickArea(int areaNumber) { var json = new JsonObject(); json["command"] = "area_click"; json["areaID"] = areaNumber; json["matchKeyName"] = game.Match.KeyName; json["playerKeyName"] = game.Player.KeyName; var send = "data=" + json.ToString(); network.SendPostRequest(send); }
private void loginButton_Click(object sender, EventArgs e) { saveSettings(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://cold-planet-7717.herokuapp.com/sessions.json"); request.Method = "POST"; request.CookieContainer = new CookieContainer(); JsonObject sessionObject = new JsonObject(); JsonObject infoObject = new JsonObject(); infoObject.Add(new KeyValuePair<string, JsonValue>("email", usernameTextBox.Text)); infoObject.Add(new KeyValuePair<string, JsonValue>("password", passwordTextBox.Text)); infoObject.Add(new KeyValuePair<string, JsonValue>("apns", "")); sessionObject.Add(new KeyValuePair<string, JsonValue>("session", infoObject)); byte[] byteArray = Encoding.UTF8.GetBytes(sessionObject.ToString()); request.ContentType = "application/json"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); if (responseFromServer != null) { JsonObject responseObject = (JsonObject)JsonValue.Parse(responseFromServer); Form2 feed = new Form2(); request.CookieContainer.Add(response.Cookies); feed.request = request; feed.cookies = request.CookieContainer; feed.userID = (string)responseObject["id"]; feed.Show(); this.Hide(); } reader.Close(); dataStream.Close(); response.Close(); }
void timer_Elapsed(object sender, ElapsedEventArgs e) { decimal value = Convert.ToDecimal(counter.NextValue()); DateTime time = DateTime.Now; dynamic message = new JsonObject(); message.time = time; message.value = value; SendMessage(message.ToString()); }
public static async Task < JsonValue > doLogin(String cpf, String password) { String url = "http://10.10.15.41:8080/Futebol/rest/login/authenticate"; HttpWebResponse response = null; HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(new Uri(url)); request.ContentType = "application/json"; request.Method = "POST"; /* Monta o objeto json */ using(var streamWriter = new StreamWriter(request.GetRequestStream())) { JsonObject json = new JsonObject(); json.Add("cpf", cpf); json.Add("password", password); streamWriter.Write(json.ToString()); streamWriter.Flush(); streamWriter.Close(); } /* Chama o serviço REST */ try { using(response = await request.GetResponseAsync() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { using(Stream stream = response.GetResponseStream()) { JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); return jsonDoc; } //Console.Write("Guilherme " + response.StatusCode); } else { JsonObject jo = new JsonObject(); jo.Add("sucess", false); return JsonValue.Parse(jo.ToString()); } } } catch (WebException e) { Console.Write("GUILHERME ERROR: ", e); JsonValue error = null; return error; } }
/// <summary> /// Creates a symbol compatible with Application Framework from JSON object /// </summary> /// <param name="jsonObject">JSON object defining a symbol</param> /// <returns>Symbol</returns> public static Symbol SymbolFromJson(JsonObject jsonObject) { Symbol symb = null; if (jsonObject != null) { string symbType = jsonObject["type"]; if (!string.IsNullOrEmpty(symbType)) { switch (symbType) { case "esriPMS":// REST defined PictureMarkerSymbol --> output: ImageFillSymbol #region ESRI.ArcGIS.Mapping.Core.Symbols.ImageFillSymbol imgsymb = new ESRI.ArcGIS.Mapping.Core.Symbols.ImageFillSymbol(); double size = 64; // standard size of images used for Viewer symbols if (jsonObject.ContainsKey("width") || jsonObject.ContainsKey("height")) { // Get the greater of the width or height, converting from points to pixels in the process var pointsToPixelsFactor = 4d / 3d; var width = jsonObject.ContainsKey("width") ? jsonObject["width"] * pointsToPixelsFactor : 0; var height = jsonObject.ContainsKey("height") ? jsonObject["height"] * pointsToPixelsFactor : 0; size = width > height ? width : height; } imgsymb.Size = size; if (jsonObject.ContainsKey("xoffset")) imgsymb.OriginX = (size /2 + jsonObject["xoffset"]) / size; if (jsonObject.ContainsKey("yoffset")) imgsymb.OriginY = (size / 2 + jsonObject["yoffset"]) / size; if (jsonObject.ContainsKey("imageData")) imgsymb.ImageData = jsonObject["imageData"]; else if (jsonObject.ContainsKey("url")) imgsymb.Source = jsonObject["url"]; var fill = imgsymb.Fill as ImageBrush; if (fill != null) fill.Stretch = Stretch.Uniform; symb = imgsymb; break; #endregion default: // all other REST defined cases symb = Symbol.FromJson(jsonObject.ToString()); break; } } } return symb; }
public async Task<JsonValue> FetchAnswer(string question) { const string dataset = "travel"; var questionJson = new JsonObject(); questionJson.Add("questionText", question); var evidenceRequest = new JsonObject(); evidenceRequest.Add("items", 1); questionJson.Add("evidenceRequest", evidenceRequest); var postData = new JsonObject(); postData.Add("question", questionJson); string text = postData.ToString(); HttpWebRequest profileRequest = (HttpWebRequest)WebRequest.Create(baseURL); string _auth = string.Format("{0}:{1}", username, password); string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth)); string _cred = string.Format("{0} {1}", "Basic", _enc); profileRequest.Headers[HttpRequestHeader.Authorization] = _cred; profileRequest.Accept = "application/json"; profileRequest.ContentType = "application/json"; byte[] bytes = Encoding.UTF8.GetBytes(text); profileRequest.Method = "POST"; profileRequest.ContentLength = bytes.Length; using (Stream requeststream = profileRequest.GetRequestStream()) { requeststream.Write(bytes, 0, bytes.Length); requeststream.Close(); } // Send the request to the server and wait for the response: using (WebResponse response = await profileRequest.GetResponseAsync ()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream ()) { // Use this stream to build a JSON document object: JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString ()); // Return the JSON document: return jsonDoc; } } }
public override void OnMessage(string value) { try { // クライアントからメッセージが来た場合 JsonObject jsonValue = (JsonObject)JsonValue.Parse(value); this.EmailAddress = (string)((JsonPrimitive)jsonValue["address"]).Value; this.Password = (string)((JsonPrimitive)jsonValue["password"]).Value; // Exchange Online に接続 (今回はデモなので、Address は決めうち !) ExchangeVersion ver = new ExchangeVersion(); ver = ExchangeVersion.Exchange2010_SP1; sv = new ExchangeService(ver, TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time")); //sv.TraceEnabled = true; // デバッグ用 sv.Credentials = new System.Net.NetworkCredential( this.EmailAddress, this.Password); sv.EnableScpLookup = false; sv.AutodiscoverUrl(this.EmailAddress, AutodiscoverCallback); // Streaming Notification の開始 (今回はデモなので、15 分で終わり !) StreamingSubscription sub = sv.SubscribeToStreamingNotifications( new FolderId[] { new FolderId(WellKnownFolderName.Calendar) }, EventType.Created, EventType.Modified, EventType.Deleted); subcon = new StreamingSubscriptionConnection(sv, 15); // only 15 minutes ! subcon.AddSubscription(sub); subcon.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(subcon_OnNotificationEvent); subcon.Open(); // 準備完了の送信 ! JsonObject jsonObj = new JsonObject( new KeyValuePair<string, JsonValue>("MessageType", "Ready"), new KeyValuePair<string, JsonValue>("ServerUrl", sv.Url.ToString())); this.SendMessage(jsonObj.ToString()); } catch (Exception ex) { this.SendInternalError(ex); } base.OnMessage(value); }
public void DataContractSerializerTest() { ValidateSerialization(new JsonPrimitive(DateTime.Now)); ValidateSerialization(new JsonObject { { "a", 1 }, { "b", 2 }, { "c", 3 } }); ValidateSerialization(new JsonArray { "a", "b", "c", 1, 2, 3 }); JsonObject beforeObject = new JsonObject { { "a", 1 }, { "b", 2 }, { "c", 3 } }; JsonObject afterObject1 = (JsonObject)ValidateSerialization(beforeObject); beforeObject.Add("d", 4); afterObject1.Add("d", 4); Assert.Equal(beforeObject.ToString(), afterObject1.ToString()); JsonObject afterObject2 = (JsonObject)ValidateSerialization(beforeObject); beforeObject.Add("e", 5); afterObject2.Add("e", 5); Assert.Equal(beforeObject.ToString(), afterObject2.ToString()); JsonArray beforeArray = new JsonArray { "a", "b", "c" }; JsonArray afterArray1 = (JsonArray)ValidateSerialization(beforeArray); beforeArray.Add("d"); afterArray1.Add("d"); Assert.Equal(beforeArray.ToString(), afterArray1.ToString()); JsonArray afterArray2 = (JsonArray)ValidateSerialization(beforeArray); beforeArray.Add("e"); afterArray2.Add("e"); Assert.Equal(beforeArray.ToString(), afterArray2.ToString()); }
public static bool userRegister(User user) { String url = "http://10.10.15.41:8080/Futebol/rest/user/register"; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url)); request.ContentType = "application/json"; request.Method = "POST"; /* Monta o objeto json */ using(var streamWriter = new StreamWriter(request.GetRequestStream())) { JsonObject json = new JsonObject(); json.Add("firstName", user.firstName); json.Add("lastName", user.lastName); json.Add("cpf", user.cpf); json.Add("password", user.password); streamWriter.Write(json.ToString()); streamWriter.Flush(); streamWriter.Close(); } /* Chama o serviço REST */ try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if(response.StatusCode.Equals(HttpStatusCode.OK)){ return true; }else{ return false; } } catch (WebException e) { Console.Write("GUILHERME ERROR: ", e); JsonValue error = null; return error; } }
/// <summary> /// Creates a symbol compatible with Application Framework from JSON object /// </summary> /// <param name="jsonObject">JSON object defining a symbol</param> /// <returns>Symbol</returns> public static Symbol SymbolFromJson(JsonObject jsonObject) { Symbol symb = null; if (jsonObject != null) { string symbType = jsonObject["type"]; if (!string.IsNullOrEmpty(symbType)) { switch (symbType) { case "esriPMS":// REST defined PictureMarkerSymbol --> output: ImageFillSymbol #region ESRI.ArcGIS.Mapping.Core.Symbols.ImageFillSymbol imgsymb = new ESRI.ArcGIS.Mapping.Core.Symbols.ImageFillSymbol(); double size = 64; // standard size of images used for Viewer symbols if (jsonObject.ContainsKey("width")) size = jsonObject["width"]; imgsymb.Size = size; if (jsonObject.ContainsKey("xoffset")) imgsymb.OriginX = (size /2 + jsonObject["xoffset"]) / size; if (jsonObject.ContainsKey("yoffset")) imgsymb.OriginY = (size / 2 + jsonObject["yoffset"]) / size; if (jsonObject.ContainsKey("imageData")) imgsymb.ImageData = jsonObject["imageData"]; else if (jsonObject.ContainsKey("url")) imgsymb.Source = jsonObject["url"]; symb = imgsymb; break; #endregion default: // all other REST defined cases symb = Symbol.FromJson(jsonObject.ToString()); break; } } } return symb; }
void TestJsonObjectAndFormsEncodedConversion(string formUrlEncoded, JsonObject json, bool formsToJsonShouldSucceed) { var formatter = new ReadWriteFormUrlEncodedFormatter(); var ms = new MemoryStream(); formatter.WriteToStreamAsync( typeof(JsonObject), json, ms, null, new FormatterContext(new MediaTypeHeaderValue("application/x-www-form-urlencoded"), false), null).Wait(); Assert.AreEqual(formUrlEncoded, Uri.UnescapeDataString(Encoding.UTF8.GetString(ms.ToArray()))); if (formsToJsonShouldSucceed) { var jo = formatter.ReadFromStreamAsync( typeof(JsonObject), new MemoryStream(Encoding.UTF8.GetBytes(formUrlEncoded)), null, new FormatterContext(new MediaTypeHeaderValue("application/x-www-form-urlencoded"), true)).Result as JsonObject; Assert.AreEqual(json.ToString(), Uri.UnescapeDataString(jo.ToString())); } }
private string buildJson(string playerId, int score, GameMode mode, GameDifficulty difficulty, DateTime date, Dictionary<int, bool> answers) { // { // “player”:”Varyon”, // “score”:10000, // “difficulty”:0, // “mode”:0, // “date”:”2012-03-07 23:15:00”, // “answers”: [ // {“id” : 002, “result” : false}, // {“id” : 003, “result” : true}, // ] // } JsonObject json = new JsonObject (); json.Add ("player", new JsonPrimitive (playerId)); json.Add ("score", new JsonPrimitive (score)); json.Add ("mode", new JsonPrimitive ((int)mode)); json.Add ("difficulty", new JsonPrimitive ((int)difficulty)); json.Add ("date", new JsonPrimitive (date.ToString ("yyyy-MM-dd hh:mm:ss"))); List<JsonValue> answersItemsJson = new List<JsonValue> (); foreach (var gameId in answers.Keys) { JsonObject o = new JsonObject(); o.Add("id", new JsonPrimitive(gameId)); o.Add("result", new JsonPrimitive(answers[gameId])); answersItemsJson.Add (o); } JsonArray answersJson = new JsonArray (answersItemsJson); json.Add ("answers", answersJson); return json.ToString (); }
// POST /api/echo public void Post(string message) { // AWS: Get instance public address string myAddress = HttpContext.Current.Request.Url.Authority; try { myAddress = Encoding.ASCII.GetString(new WebClient().DownloadData("http://169.254.169.254/latest/meta-data/public-hostname")); } catch { } var messageJob = new JsonObject(); messageJob["message"] = message; messageJob["sender"] = myAddress; // AWS SQS Client var sqsClient = new AmazonSQSClient(); SendMessageRequest request = new SendMessageRequest() .WithQueueUrl("https://queue.amazonaws.com/******/codeCampDemo") .WithMessageBody(messageJob.ToString()); sqsClient.SendMessage(request); }
/// <summary> /// Enrolls an image URL of a subject in a gallery /// </summary> /// <param name="ImageURL">URL of the image</param> /// <param name="Subject">Subject name</param> /// <param name="Gallery">Gallery name</param> private async Task<string> EnrollImage( string ImageURL, string Subject, string Gallery ) { // Create JSON request JsonObject jsonParams = new JsonObject(); jsonParams.Add( "image", ImageURL ); jsonParams.Add( "subject_id", Subject ); jsonParams.Add( "gallery_name", Gallery ); jsonParams.Add( "selector", "FACE" ); // Create an HTTP web request HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( new Uri( this.ApiUrlEnroll ) ); request.ContentType = "application/json"; request.Method = "POST"; request.Headers.Add( "app_id", AppId ); request.Headers.Add( "app_key", AppKey ); StreamWriter streamWriter = new StreamWriter( request.GetRequestStream() ); streamWriter.Write( jsonParams.ToString() ); streamWriter.Flush(); streamWriter.Close(); // Submit the web request and await the response string returnString = await AsyncWebAction( request ); // Return the response return returnString; }
/// <summary> /// Accepts an image and returns the name that corresponds to the best match /// </summary> /// <param name="theBitmap"></param> /// <returns></returns> private async Task<string> RecognizeImage( Bitmap theBitmap ) { // Initialize the return string string theName = "NotRecognized"; // Clear the current results MatchTextView.Text = ""; MatchImageView.SetImageDrawable( null ); // Encode the camera image byte[] bitmapData; using (var stream = new MemoryStream()) { theBitmap.Compress( Bitmap.CompressFormat.Jpeg, 50, stream ); bitmapData = stream.ToArray(); } string encodedBitmap = Convert.ToBase64String( bitmapData ); // Define the gallery name string GalleryName = "TestCelebs"; // Create JSON request JsonObject jsonParams = new JsonObject(); jsonParams.Add( "image", encodedBitmap ); jsonParams.Add( "gallery_name", GalleryName ); jsonParams.Add( "threshold", MatchThreshold ); // Create an HTTP web request HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( new Uri( this.ApiUrlRecognize ) ); request.ContentType = "application/json"; request.Method = "POST"; request.Headers.Add( "app_id", AppId ); request.Headers.Add( "app_key", AppKey ); StreamWriter streamWriter = new StreamWriter( request.GetRequestStream() ); streamWriter.Write( jsonParams.ToString() ); streamWriter.Flush(); streamWriter.Close(); // Submit the web request and await the response JsonValue json = await AsyncWebActionJson( request ); try { // Parse the results JsonValue imagesResult = json["images"]; JsonValue attributesResult = imagesResult[0]; // This has to be accessed by the index instead of the name, not sure why JsonValue transactionResult = attributesResult["transaction"]; JsonValue statusResult = transactionResult["status"]; // Check for a successful match if (statusResult.ToString().Contains( "success" )) { JsonValue subjectResult = transactionResult["subject"]; JsonValue confidenceResult = transactionResult["confidence"]; // Get the name as a string //theName = subjectResult + " " + confidenceResult.ToString().Substring( 3, 2 ) + "%"; theName = subjectResult; } else { theName = "No Match"; } } catch( Exception ex ) { } // Return the name return theName; }
public void TestDataContractJsonSerializerSettings() { TestTypeForSerializerSettings instance = new TestTypeForSerializerSettings { BaseRef = new DerivedType(), Date = AnyInstance.AnyDateTime, Dict = new Dictionary<string, object> { { "one", 1 }, { "two", 2 }, { "two point five", 2.5 }, } }; JsonObject dict = new JsonObject { { "one", 1 }, { "two", 2 }, { "two point five", 2.5 }, }; JsonObject equivalentJsonObject = new JsonObject { { "BaseRef", new JsonObject { { "__type", "DerivedType:NS" } } }, { "Date", AnyInstance.AnyDateTime }, { "Dict", dict }, }; JsonObject createdFromType = JsonValueExtensions.CreateFrom(instance) as JsonObject; Assert.Equal(equivalentJsonObject.ToString(), createdFromType.ToString()); TestTypeForSerializerSettings newInstance = equivalentJsonObject.ReadAsType<TestTypeForSerializerSettings>(); // DISABLED, 198487 - Assert.Equal(instance.Date, newInstance.Date); Assert.Equal(instance.BaseRef.GetType().FullName, newInstance.BaseRef.GetType().FullName); Assert.Equal(3, newInstance.Dict.Count); Assert.Equal(1, newInstance.Dict["one"]); Assert.Equal(2, newInstance.Dict["two"]); Assert.Equal(2.5, Convert.ToDouble(newInstance.Dict["two point five"], CultureInfo.InvariantCulture)); }
public void ToStringTest() { JsonObject target = new JsonObject(); JsonValue item1 = AnyInstance.AnyJsonValue1 ?? "not null"; JsonValue item2 = null; JsonValue item3 = AnyInstance.AnyJsonValue2 ?? "not null"; JsonValue item4 = AnyInstance.AnyJsonValue3 ?? "not null"; target.Add("item1", item1); target.Add("item2", item2); target.Add("item3", item3); target.Add("", item4); string expected = String.Format(CultureInfo.InvariantCulture, "{{\"item1\":{0},\"item2\":null,\"item3\":{1},\"\":{2}}}", item1.ToString(), item3.ToString(), item4.ToString()); Assert.Equal<string>(expected, target.ToString()); string json = "{\r\n \"item1\": \"hello\",\r\n \"item2\": null,\r\n \"item3\": [\r\n 1,\r\n 2,\r\n 3\r\n ],\r\n \"\": \"notnull\"\r\n}"; target = JsonValue.Parse(json) as JsonObject; Assert.Equal<string>(json.Replace("\r\n", "").Replace(" ", ""), target.ToString()); }
public void TestConcurrentToString() { bool exceptionThrown = false; bool incorrectValue = false; JsonObject jo = new JsonObject(); StringBuilder sb = new StringBuilder(); sb.Append('{'); for (int i = 0; i < 100000; i++) { if (i > 0) { sb.Append(','); } string key = i.ToString(CultureInfo.InvariantCulture); jo.Add(key, i); sb.AppendFormat("\"{0}\":{0}", key); } sb.Append('}'); string expected = sb.ToString(); int numberOfThreads = 5; Thread[] threads = new Thread[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { threads[i] = new Thread(new ThreadStart(delegate { for (int j = 0; j < 10; j++) { try { string str = jo.ToString(); if (str != expected) { incorrectValue = true; Log.Info("Value is incorrect"); } } catch (Exception e) { exceptionThrown = true; Log.Info("Exception thrown: {0}", e); } } })); } for (int i = 0; i < numberOfThreads; i++) { threads[i].Start(); } for (int i = 0; i < numberOfThreads; i++) { threads[i].Join(); } Assert.False(incorrectValue); Assert.False(exceptionThrown); }
public void JsonObjectCopytoFunctionalTest() { int seed = 1; for (int i = 0; i < iterationCount / 10; i++) { seed++; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); bool retValue = true; JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength); KeyValuePair <string, JsonValue>[] destJson = new KeyValuePair <string, JsonValue> [arrayLength]; if (sourceJson != null && destJson != null) { sourceJson.CopyTo(destJson, 0); } else { Log.Info("[JsonObjectCopytoFunctionalTest] sourceJson.ToString() = " + sourceJson.ToString()); Log.Info("[JsonObjectCopytoFunctionalTest] destJson.ToString() = " + destJson.ToString()); Assert.False(true, "[JsonObjectCopytoFunctionalTest] failed to create the source JsonObject object."); return; } if (destJson.Length == arrayLength) { for (int k = 0; k < destJson.Length; k++) { JsonValue temp; sourceJson.TryGetValue(k.ToString(), out temp); if (!(temp != null && destJson[k].Value == temp)) { retValue = false; } } } else { retValue = false; } Assert.True(retValue, "[JsonObjectCopytoFunctionalTest] JsonObject.CopyTo() failed to function properly. destJson.GetLength(0) = " + destJson.GetLength(0)); } }
private bool SuccessfulCall(JsonObject response) { var r = JsonConvert.DeserializeObject<Helpers.APIResponse>(response.ToString()); if(r.result.code == "OK") { return true; } else { return false; } }
public void UpdateFromJson(JsonObject json) { try { Id = json ["id"]; Screenname = json ["screen_name"]; PicUrl = json ["profile_image_url"]; JsonString = json.ToString (); } catch (Exception e){ Console.WriteLine (e); } }
string JsonSerializeRefererAppLink(RefererAppLink refererAppLink) { var j = new JsonObject (); if (refererAppLink.TargetUrl != null) j ["target_url"] = refererAppLink.TargetUrl.ToString (); if (!string.IsNullOrEmpty (refererAppLink.AppName)) j ["app_name"] = refererAppLink.AppName; if (!string.IsNullOrEmpty (refererAppLink.AppStoreId)) j ["app_store_id"] = refererAppLink.AppStoreId; if (refererAppLink.Url != null) j ["url"] = refererAppLink.Url.ToString (); return j.ToString (); }
string JsonSerializeAppLinkData(AppLink appLink, JsonObject extras) { var j = new JsonObject (); j ["target_url"] = appLink.SourceUrl.ToString (); j ["version"] = AppLinks.Version; j ["user_agent"] = AppLinks.UserAgent; j ["extras"] = extras; return j.ToString (); }
private void DoRoundTripCasting(JsonValue jo, Type type) { bool result = false; // Casting if (jo.JsonType == JsonType.String) { JsonValue jstr = (string)jo; if (type == typeof(DateTime)) { Log.Info("{0} Value:{1}", type.Name, ((DateTime)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(DateTimeOffset)) { Log.Info("{0} Value:{1}", type.Name, ((DateTimeOffset)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(Guid)) { Log.Info("{0} Value:{1}", type.Name, (Guid)jstr); } else if (type == typeof(char)) { Log.Info("{0} Value:{1}", type.Name, (char)jstr); } else if (type == typeof(Uri)) { Log.Info("{0} Value:{1}", type.Name, ((Uri)jstr).AbsoluteUri); } else { Log.Info("{0} Value:{1}", type.Name, (string)jstr); } if (jo.ToString() == jstr.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Object) { JsonObject jobj = new JsonObject((JsonObject)jo); if (jo.ToString() == jobj.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Number) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Boolean) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, (bool)jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } if (!result) { Assert.Fail("Test Failed!"); } }
public static JsonPrimitive GetUniqueValue(int seed, JsonObject sourceJson) { JsonPrimitive newValue; int i = 0; do { newValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed + i); i++; } while (sourceJson.ToString().IndexOf(newValue.ToString()) > 0); return newValue; }
private void DoRoundTripCasting(JsonValue jo, Type type) { bool result = false; // Casting if (jo.JsonType == JsonType.String) { JsonValue jstr = (string)jo; if (type == typeof(DateTime)) { Log.Info("{0} Value:{1}", type.Name, ((DateTime)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(DateTimeOffset)) { Log.Info("{0} Value:{1}", type.Name, ((DateTimeOffset)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(Guid)) { Log.Info("{0} Value:{1}", type.Name, (Guid)jstr); } else if (type == typeof(char)) { Log.Info("{0} Value:{1}", type.Name, (char)jstr); } else if (type == typeof(Uri)) { Log.Info("{0} Value:{1}", type.Name, ((Uri)jstr).AbsoluteUri); } else { Log.Info("{0} Value:{1}", type.Name, (string)jstr); } if (jo.ToString() == jstr.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Object) { JsonObject jobj = new JsonObject((JsonObject)jo); if (jo.ToString() == jobj.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Number) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Boolean) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, (bool)jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } Assert.True(result); }