public void AddTest() { string key1 = AnyInstance.AnyString; string key2 = AnyInstance.AnyString2; JsonValue value1 = AnyInstance.AnyJsonValue1; JsonValue value2 = AnyInstance.AnyJsonValue2; JsonObject target; target = new JsonObject(); target.Add(new KeyValuePair<string, JsonValue>(key1, value1)); Assert.Equal(1, target.Count); Assert.True(target.ContainsKey(key1)); Assert.Equal(value1, target[key1]); target.Add(key2, value2); Assert.Equal(2, target.Count); Assert.True(target.ContainsKey(key2)); Assert.Equal(value2, target[key2]); ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().Add(null, value1); }); ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().Add(new KeyValuePair<string, JsonValue>(null, value1)); }); ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject().Add(key1, AnyInstance.DefaultJsonValue); }); ExceptionHelper.Throws<ArgumentException>(delegate { new JsonArray().Add(AnyInstance.DefaultJsonValue); }); }
//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; }
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; } }
/// <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 static string CreateMetodRequestString(string proceDb, string proceName, string[] paramKeys, string[] paramVals) { System.Json.JsonObject _jsonObj = new System.Json.JsonObject(); _jsonObj.Add("ProceDb", proceDb); _jsonObj.Add("ProceName", proceName); _jsonObj.Add("ParamKeys", ConvertObjectAry2JsonValAry(paramKeys)); _jsonObj.Add("ParamVals", ConvertObjectAry2JsonValAry(paramVals)); return(new JsonArray(_jsonObj).ToString()); }
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(); }
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; } }
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 static HttpContent CreateJsonContent(params KeyValuePair<string, string>[] items) { var jsonObject = new JsonObject(); foreach (KeyValuePair<string, string> kv in items) { jsonObject.Add(kv.Key, kv.Value); } return new ObjectContent(typeof(JsonObject), jsonObject, "application/json"); }
/// <summary> /// 設定を保存します /// </summary> public async Task Save() { await Task.Run(() => { // Serialize var json = new JsonObject(); JsonPrimitive element; JsonPrimitive.TryCreate(Account.BaseUrl, out element); json.Add("BaseUrl", element); JsonPrimitive.TryCreate(Account.UserKey, out element); json.Add("UserKey", element); JsonPrimitive.TryCreate(PostTextFormat, out element); json.Add("PostTextFormat", element); JsonPrimitive.TryCreate((int)TargetPlayer, out element); json.Add("TargetPlayer", element); JsonPrimitive.TryCreate(IsAutoPost, out element); json.Add("IsAutoPost", element); JsonPrimitive.TryCreate(AutoPostInterval, out element); json.Add("AutoPostInterval", element); // Save using (var sw = new System.IO.StreamWriter("setting.json")) { json.Save(sw); } }); }
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; } }
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 (); }
static JsonObject CreateJsonObject(Random rndGen, int depth) { const string keyChars = "abcdefghijklmnopqrstuvwxyz0123456789"; int size = rndGen.Next(CreatorSettings.MaxArrayLength); if (CreatorSettings.NullValueProbability == 0 && size == 0) { size++; } JsonObject result = new JsonObject(); for (int i = 0; i < size; i++) { string key; do { key = PrimitiveCreator.CreateInstanceOfString(rndGen, 10, keyChars); } while (result.ContainsKey(key)); result.Add(key, CreateJsonValue(rndGen, depth + 1)); } return result; }
internal JsonObject ToJson() { var user_info = new JsonObject(); foreach (var kvp in UserInfo) { JsonValue value = null; if (kvp.Value is string) { value = (string)kvp.Value; } else if (kvp.Value is bool) { value = (bool)kvp.Value; } else { System.Diagnostics.Debug.Fail($"Unsupported type in JSON conversion '{kvp.Value?.GetType()}'"); } user_info.Add(kvp.Key, value); } return new JsonObject { ["data"] = Token, ["provider"] = IdentityProvider, ["user_info"] = user_info }; }
public void CountTest() { string key1 = AnyInstance.AnyString; string key2 = AnyInstance.AnyString2; JsonValue value1 = AnyInstance.AnyJsonValue1; JsonValue value2 = AnyInstance.AnyJsonValue2; JsonObject target = new JsonObject(); Assert.Equal(0, target.Count); target.Add(key1, value1); Assert.Equal(1, target.Count); target.Add(key2, value2); Assert.Equal(2, target.Count); target.Remove(key2); Assert.Equal(1, target.Count); }
public void ContainsKVPTest() { JsonObject target = new JsonObject(); KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString, AnyInstance.AnyJsonValue1); KeyValuePair<string, JsonValue> item2 = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString2, AnyInstance.AnyJsonValue2); target.Add(item); Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item)); Assert.False(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item2)); }
/// <summary> /// Serialize the match data in json /// </summary> /// <returns>The json.</returns> public string ToJson() { JsonObject json = new JsonObject (); json.Add (new KeyValuePair<string, JsonValue> ("MatchId", new JsonPrimitive (MatchId))); json.Add (new KeyValuePair<string, JsonValue> ("IsEnded", new JsonPrimitive (IsEnded))); json.Add (new KeyValuePair<string, JsonValue> ("Player1Id", new JsonPrimitive (Player1Id))); json.Add (new KeyValuePair<string, JsonValue> ("Player2Id", new JsonPrimitive (Player2Id))); json.Add (new KeyValuePair<string, JsonValue> ("Difficulty", Difficulty.ToString())); json.Add (new KeyValuePair<string, JsonValue> ("Filter", Filter.ToJson ())); JsonArray turnsJson = new JsonArray (); foreach (VersusMatchTurn turn in Turns) { JsonObject turnJson = new JsonObject (); turnJson.Add (new KeyValuePair<string, JsonValue> ("PlayerId", new JsonPrimitive (turn.PlayerId))); turnJson.Add (new KeyValuePair<string, JsonValue> ("Score", new JsonPrimitive (turn.Score))); turnsJson.Add (turnJson); } json.Add (new KeyValuePair<string, JsonValue> ("Turns", turnsJson)); return json.ToString (); }
public static JsonObject CreateIndexPopulatedJsonObject(int seed, int length) { JsonObject myObject; myObject = new JsonObject(new Dictionary<string, JsonValue>() { }); for (int i = myObject.Count; i < length; i++) { myObject.Add(i.ToString(CultureInfo.InvariantCulture), GetRandomJsonPrimitives(seed + i)); } return myObject; }
// 長方形のプロパティを表示(デバッグ用) private void OutputDebugRect(object sender, MouseButtonEventArgs e) { if (MediaData.movieList[0].currentPlayer.drawArea.FindName("hoge") != null) { Rectangle ele = (Rectangle)MediaData.movieList[0].currentPlayer.drawArea.FindName("hoge"); var json_obj = new JsonObject(); json_obj.Add("height", ele.Height.ToString()); json_obj.Add("width", ele.Width.ToString()); //json_obj.Add("color", "red"); json_obj.Add("left", Canvas.GetLeft(ele).ToString()); json_obj.Add("top", Canvas.GetTop(ele).ToString()); json_obj.Add("start", MediaData.movieList[0].currentPlayer.movie.Position.ToString()); //json_obj.Add("end", (movie1.Position + TimeSpan.FromSeconds(2)).ToString()); debugTextBox.Text = json_obj.ToString(); //debugTextBox.Text += json_obj.ToString() + "\n"; } }
public static JsonValue ToJson(object value) { if (value == null) return null; var jsonValue = value as JsonValue; if (jsonValue != null) return jsonValue; JsonPrimitiveProvider provider; if (s_primitiveProviders.TryGetValue(value.GetType(), out provider)) { return provider.ToPrimitive(value); } var dict = value as Dictionary<string, object>; if (dict != null) { return new JsonObject(dict.ToDictionary(p => p.Key, p => ToJson(p.Value))); } var array = value as IEnumerable; if (array != null) { return new JsonArray(array.Cast<object>().Select(o => ToJson(o))); } var jsonObject = new JsonObject(); foreach (var property in value.GetType().GetProperties().Where(p => !p.IsSpecialName)) { jsonObject.Add(property.Name, ToJson(property.GetValue(value, null))); } return jsonObject; }
/** For later public Section FacebookConfig (UILabel label) { Section facebookConfig = new Section(label); if (this._facebook.IsSessionValid) { facebookConfig.Add(new StringElement ("Uninstall app", this.UninstallFromFacebook)); } else { facebookConfig.Add(new StringElement ("Login to Facebook", this.Login)); } return facebookConfig; } **/ public void PostToWall(string wallPost) { Console.WriteLine("post to wall launched"); var json = new JsonObject (); json.Add ("name", new JsonPrimitive ("About One RM Log")); json.Add ("link", new JsonPrimitive ("http://pennyfarthingapps.com")); // TODO: update with one rm website // TODO: update the picture and URL for the facebook wall post var parameters = NSMutableDictionary.FromObjectsAndKeys ( new object [] { "Hit a new one rep max", "one rm log app", "I just got a new one rep max " + this.SocialMessage, "http://pennyfarthingapps.com", "http://www.wodti.me/img/facebook_icon_large.png", json.ToString ()}, new object [] { "name", "caption", "description", "link", "picture", "actions"}); _wallDialogHandler = DialogCallback (url => { if (url.Query == null) return; var pars = System.Web.HttpUtility.ParseQueryString (url.Query); if (pars ["post_id"] != null) ShowMessage ("Success", "Posted to your wall"); }); this._facebook.Dialog ("feed", parameters, _wallDialogHandler); }
private void getFeed() { request = (HttpWebRequest)WebRequest.Create("http://cold-planet-7717.herokuapp.com/home.json"); request.Method = "POST"; request.AllowAutoRedirect = true; request.CookieContainer = cookies; JsonObject tempObject = new JsonObject(); tempObject.Add(new KeyValuePair<string, JsonValue>("first", (JsonValue)"0")); tempObject.Add(new KeyValuePair<string, JsonValue>("last", (JsonValue)"20")); byte[] byteArray = Encoding.UTF8.GetBytes(tempObject.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) { feed = (JsonArray)JsonValue.Parse(responseFromServer); if (bindingSource1.Count > 0) { bindingSource1 = null; bindingSource1 = new BindingSource(); } foreach (var post in feed) { Post tempPost = new Post((string)post["content"], (string)post["name"], (string)post["username"]); bindingSource1.Add(tempPost); } reader.Close(); dataStream.Close(); response.Close(); dataGridView1.AutoGenerateColumns = false; dataGridView1.AutoSize = true; dataGridView1.DataSource = bindingSource1; if (dataGridView1.Columns.Count > 0) { return; } else { DataGridViewColumn column = new DataGridViewTextBoxColumn(); column.DataPropertyName = "name"; column.Name = "Name"; dataGridView1.Columns.Add(column); DataGridViewColumn column2 = new DataGridViewTextBoxColumn(); column2.DataPropertyName = "content"; column2.Name = "Content"; dataGridView1.Columns.Add(column2); dataGridView1.Columns["name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; dataGridView1.Columns["content"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; dataGridView1.Columns["content"].Width = 183; dataGridView1.Columns["content"].DefaultCellStyle.WrapMode = DataGridViewTriState.True; } } }
private void sendButton_Click(object sender, EventArgs e) { request = (HttpWebRequest)WebRequest.Create("http://cold-planet-7717.herokuapp.com/microposts.json"); request.Method = "POST"; request.AllowAutoRedirect = true; request.CookieContainer = cookies; JsonObject tempObject = new JsonObject(); tempObject.Add(new KeyValuePair<string, JsonValue>("content", (JsonValue)postTextBox.Text)); tempObject.Add(new KeyValuePair<string, JsonValue>("user_id", (JsonValue)userID)); byte[] byteArray = Encoding.UTF8.GetBytes(tempObject.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) { SystemSounds.Exclamation.Play(); postTextBox.Text = null; getFeed(); } }
/// <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 ClearTest() { string key1 = AnyInstance.AnyString; string key2 = AnyInstance.AnyString2; JsonValue value1 = AnyInstance.AnyJsonValue1; JsonValue value2 = AnyInstance.AnyJsonValue2; JsonObject target = new JsonObject(); target.Add(key1, value1); target.Clear(); Assert.Equal(0, target.Count); Assert.False(target.ContainsKey(key1)); target.Add(key2, value2); Assert.Equal(1, target.Count); Assert.False(target.ContainsKey(key1)); Assert.True(target.ContainsKey(key2)); }
/// <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; }
public void ContainsKeyTest() { string key1 = AnyInstance.AnyString; JsonValue value1 = AnyInstance.AnyJsonValue1; JsonObject target = new JsonObject(); Assert.False(target.ContainsKey(key1)); target.Add(key1, value1); Assert.True(target.ContainsKey(key1)); target.Clear(); Assert.False(target.ContainsKey(key1)); ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().ContainsKey(null); }); }
private static JsonObject CreateObjectWithTypeHint(XmlDictionaryReader jsonReader, ref bool isEmptyElement) { JsonObject jsonObject = new JsonObject(); string typeHintAttribute = jsonReader.GetAttribute(TypeHintAttributeName); isEmptyElement = jsonReader.IsEmptyElement; jsonReader.ReadStartElement(); SkipWhitespace(jsonReader); if (typeHintAttribute != null) { jsonObject.Add(TypeHintAttributeName, typeHintAttribute); } return jsonObject; }
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 static JsonObject CreateRandomPopulatedJsonObject(int seed, int length) { JsonObject myObject; myObject = new JsonObject( new Dictionary<string, JsonValue>() { { "Name", "myArray" }, { "Index", 1 } }); for (int i = myObject.Count; i < length / 2; i++) { myObject.Add(PrimitiveCreator.CreateInstanceOfString(new Random(seed + i)), GetRandomJsonPrimitives(seed + (i * 2))); } for (int i = myObject.Count; i < length; i++) { myObject.Add(new KeyValuePair<string, JsonValue>(PrimitiveCreator.CreateInstanceOfString(new Random(seed + (i * 10))), GetRandomJsonPrimitives(seed + (i * 20)))); } return myObject; }
void Populate (JsonValue json, RootElement root, JsonValue data) { if (json.ContainsKey("title")) root.Caption = json["title"]; JsonValue jsonRoot = null; try { jsonRoot = json["root"]; } catch (Exception){ Console.WriteLine("Bad JSON: could not find the root element - "+json.ToString()) ; return; } foreach (JsonObject section in jsonRoot){ var sec = new Section(section.s("caption"), section.s("footer")); if (section.ContainsKey("elements")){ foreach (JsonObject elem in section["elements"]) { var dataForElement = data; var bindExpression = elem.s("bind"); if (bindExpression!=null) { try { if (data!=null && data.JsonType==JsonType.Object){ var bind = elem.s("bind"); if (data != null && !string.IsNullOrEmpty(bind) && data.ContainsKey(bind)) { dataForElement = data[bind]; } } else if (bindExpression.StartsWith("#")) { dataForElement = _controller.GetValue(bindExpression.Replace("#", "")); } } catch (Exception){ Console.WriteLine("Exception when binding element " + elem.ToString()); } } _parseElement(elem, sec, dataForElement); } } else if (section.ContainsKey("iterate") && data != null){ string iterationname = section["iterate"]; string emptyMessage = section.ContainsKey("empty") ? section["empty"].CleanString() : "Empty"; var iterationdata = string.IsNullOrEmpty(iterationname) ? (JsonArray)data : (JsonArray)data[iterationname]; var template = (JsonObject)section["template"]; var items = iterationdata.ToList(); if (items.Count>0) { foreach(JsonValue v in items){ _parseElement(template, sec, v); } } else { sec.Add(new EmptyListElement(emptyMessage)); } } else if (section.ContainsKey("iterateproperties") && data != null){ string iterationname = section["iterateproperties"]; string emptyMessage = section.ContainsKey("empty") ? section["empty"].CleanString() : "Empty"; var iterationdata = string.IsNullOrEmpty(iterationname) ? (JsonObject)data : (JsonObject)data[iterationname]; var template = (JsonObject)section["template"]; var items = iterationdata.Keys; if (items.Count>0) { foreach(string v in items){ var obj = new JsonObject(); obj.Add(v, iterationdata[v]); _parseElement(template, sec, obj); } } else { sec.Add(new EmptyListElement(emptyMessage)); } } root.Add(sec); } }