public void MetricsCollection () { string id = "myuniqueid"; var metrics = new MetricsCollection (id, new MemorySampleStore ()); Assert.AreEqual ("myuniqueid", metrics.AnonymousUserId); metrics.AddDefaults (); Assert.IsTrue (metrics.Count > 0); string metrics_str = metrics.ToJsonString (); Assert.IsTrue (metrics_str.Contains ("\"ID\":\"myuniqueid\"")); // tests/Makefile.am runs the tests with Locale=it_IT Assert.IsTrue (metrics_str.Contains ("it-IT")); // Make sure DateTime samples are saved as invariant strings var now = DateTime.Now; var time_metric = metrics.Add ("Foo", now); Assert.AreEqual (Hyena.DateTimeUtil.ToInvariantString (now), metrics.Store.GetFor (time_metric).First ().Value); // Make sure we can read the JSON back in var ds = new Json.Deserializer (); ds.SetInput (metrics.ToJsonString ()); var json_obj = ds.Deserialize () as JsonObject; Assert.AreEqual (id, json_obj["ID"]); Assert.IsTrue (json_obj["Metrics"] is JsonObject); }
public void ParseTest () { Deserializer deserializer = new Deserializer (); string refJson = "{ \"api-ref\" : \"http://domain/api/1.0/sally/notes\", \"href\" : \"http://domain/sally/notes\"}"; deserializer.SetInput (refJson); JsonObject refObj = (JsonObject) deserializer.Deserialize (); ResourceReference resourceRef = ResourceReference.ParseJson (refObj); Assert.AreEqual ("http://domain/api/1.0/sally/notes", resourceRef.ApiRef, "ApiRef"); Assert.AreEqual ("http://domain/sally/notes", resourceRef.Href, "Href"); refJson = "{ \"api-ref\" : \"http://domain/api/1.0/sally/notes\"}"; deserializer.SetInput (refJson); refObj = (JsonObject) deserializer.Deserialize (); resourceRef = ResourceReference.ParseJson (refObj); Assert.AreEqual ("http://domain/api/1.0/sally/notes", resourceRef.ApiRef, "ApiRef"); Assert.IsNull (resourceRef.Href, "Href should be null when none specified"); refJson = "{ \"href\" : \"http://domain/sally/notes\"}"; deserializer.SetInput (refJson); refObj = (JsonObject) deserializer.Deserialize (); resourceRef = ResourceReference.ParseJson (refObj); Assert.AreEqual ("http://domain/sally/notes", resourceRef.Href, "Href"); Assert.IsNull (resourceRef.ApiRef, "ApiRef should be null when none specified"); }
public void ParseTest () { Deserializer deserializer = new Deserializer (); string noteJson = "{\"guid\": \"002e91a2-2e34-4e2d-bf88-21def49a7705\"," + "\"title\" :\"New Note 6\"," + "\"note-content\" :\"New Note 6\\nDescribe youre note <b>here</b>.\"," + "\"note-content-version\" : 0.2," + "\"last-change-date\" : \"2009-04-19T21:29:23.2197340-07:00\"," + "\"last-metadata-change-date\" : \"2009-04-19T21:29:23.2197340-07:00\"," + "\"create-date\" : \"2008-03-06T13:44:46.4342680-08:00\"," + "\"last-sync-revision\" : 57," + "\"open-on-startup\" : false," + "\"tags\" : [\"tag1\",\"tag2\"]" + "}"; deserializer.SetInput (noteJson); JsonObject noteObj = (JsonObject) deserializer.Deserialize (); //Assert.AreEqual (57, (int)noteObj["last-sync-revision"]); NoteInfo note = NoteInfo.ParseJson (noteObj); Assert.AreEqual ("002e91a2-2e34-4e2d-bf88-21def49a7705", note.Guid, "GUID"); Assert.AreEqual ("New Note 6\nDescribe youre note <b>here</b>.", note.NoteContent, "NoteContent"); Assert.AreEqual (0.2, note.NoteContentVersion, "NoteContentVersion"); Assert.AreEqual ("New Note 6", note.Title, "Title"); Assert.AreEqual (DateTime.Parse ("2009-04-19T21:29:23.2197340-07:00"), note.LastChangeDate, "LastChangeDate"); Assert.AreEqual (DateTime.Parse ("2009-04-19T21:29:23.2197340-07:00"), note.LastMetadataChangeDate, "LastMetadataChangeDate"); Assert.AreEqual (DateTime.Parse ("2008-03-06T13:44:46.4342680-08:00"), note.CreateDate, "CreateDate"); Assert.AreEqual (57, note.LastSyncRevision, "LastSyncRevision"); Assert.IsTrue (note.OpenOnStartup.HasValue, "OpenOnStartup should have value"); Assert.IsFalse (note.OpenOnStartup.Value, "OpenOnStartup value"); Assert.IsNotNull (note.Tags, "Tags should not be null"); // TODO: Test resourceref,command,lack of guid,nullables,etc, // ApplicationException when missing comma in string, wrong type, etc }
public StationError GetError () { StationError error = StationError.None; string response; using (StreamReader sr = new StreamReader (response_stream)) { response = sr.ReadToEnd (); } if (response.Contains ("<lfm status=\"failed\">")) { // XML reply indicates an error Match match = Regex.Match (response, "<error code=\"(\\d+)\">"); if (match.Success) { error = (StationError) Int32.Parse (match.Value); Log.WarningFormat ("Lastfm error {0}", error); } else { error = StationError.Unknown; } } if (response_format == ResponseFormat.Json && response.Contains ("\"error\":")) { // JSON reply indicates an error Deserializer deserializer = new Deserializer (response); JsonObject json = deserializer.Deserialize () as JsonObject; if (json != null && json.ContainsKey ("error")) { error = (StationError) json["error"]; Log.WarningFormat ("Lastfm error {0} : {1}", error, (string)json["message"]); } } return error; }
public JsonObject GetResponseObject () { if (response_stream == null) return null; Deserializer deserializer = new Deserializer (response_stream); object obj = deserializer.Deserialize (); JsonObject json_obj = obj as Hyena.Json.JsonObject; if (json_obj == null) { throw new ApplicationException ("Lastfm invalid response : not a JSON object"); } return json_obj; }
// The listen/watch links take the user to another page with an embedded player. Instead of // going there, find the direct media URL and send it to Banshee's PlayerEngine. private bool TryInterceptListenWatch(string uri) { bool ret = false; if (uri != null && uri.Contains ("miroguide.com/items/")) { int i = uri.LastIndexOf ('/') + 1; var item_id = uri.Substring (i, uri.Length - i); // Get the actual media URL via the MiroGuide API new Hyena.Downloader.HttpStringDownloader () { Uri = new Uri (String.Format ("http://www.miroguide.com/api/get_item?datatype=json&id={0}", item_id)), Finished = (d) => { if (d.State.Success) { string media_url = null; var item = new Deserializer (d.Content).Deserialize () as JsonObject; if (item.ContainsKey ("url")) { media_url = item["url"] as string; } if (media_url != null) { Log.DebugFormat ("MiroGuide: streaming straight away {0}", media_url); Banshee.Streaming.RadioTrackInfo.OpenPlay (media_url); Banshee.ServiceStack.ServiceManager.PlaybackController.StopWhenFinished = true; ret = true; } } }, AcceptContentTypes = new [] { "text/javascript" } }.StartSync (); } return ret; }
public void ExceptionTest () { bool expectedExceptionRaised = false; try { ResourceReference.ParseJson (null); } catch (ArgumentNullException) { expectedExceptionRaised = true; } Assert.IsTrue (expectedExceptionRaised, "ArgumentNullException expected on null input"); expectedExceptionRaised = false; Deserializer deserializer = new Deserializer (); string invalidRefJson = "{ \"api-ref\" : 5, \"href\" : \"http://domain/sally/notes\"}"; deserializer.SetInput (invalidRefJson); JsonObject refObj = (JsonObject) deserializer.Deserialize (); try { ResourceReference.ParseJson (refObj); } catch (InvalidCastException) { expectedExceptionRaised = true; } Assert.IsTrue (expectedExceptionRaised, "InvalidCastException expected on invalid input"); }
public void Setup () { deserializer = new Deserializer (); }
// The listen/watch links take the user to another page with an embedded player. Instead of // going there, find the direct media URL and send it to Banshee's PlayerEngine. private bool TryInterceptListenWatch (string uri) { bool ret = false; if (uri != null && uri.StartsWith ("http://miroguide.com/items/")) { int i = Uri.LastIndexOf ('/') + 1; int channel_id = Int32.Parse (Uri.Substring (i, Uri.Length - i)); i = uri.LastIndexOf ('/') + 1; var item_id = uri.Substring (i, uri.Length - i); // Get the actual media URL via the MiroGuide API new Hyena.Downloader.HttpStringDownloader () { Uri = new Uri (String.Format ("http://www.miroguide.com/api/get_channel?datatype=json&id={0}", channel_id)), Finished = (d) => { if (d.State.Success) { string media_url = null; var obj = new Deserializer (d.Content).Deserialize (); var ary = ((JsonObject)obj)["item"] as JsonArray; foreach (JsonObject item in ary) { if ((item["playback_url"] as string).EndsWith (item_id)) { media_url = item["url"] as string; break; } } if (media_url != null) { Log.DebugFormat ("MiroGuide: streaming straight away {0}", media_url); Banshee.Streaming.RadioTrackInfo.OpenPlay (media_url); Banshee.ServiceStack.ServiceManager.PlaybackController.StopWhenFinished = true; ret = true; } } }, AcceptContentTypes = new [] { "text/javascript" } }.StartSync (); } return ret; }
Dictionary<string, object> DoServiceCall(string method, params object[] parameters) { var callId = Interlocked.Increment (ref this.callId); var callObject = new Dictionary<string, object> { {"id", callId}, {"method", method}, {"params", parameters} }; #if DEBUG Console.Error.Write ("Serializing JSON-RPC call object..."); Stopwatch s = new Stopwatch (); s.Start (); #endif string jsonPayload = new Serializer (callObject).Serialize (); #if DEBUG s.Stop (); Console.Error.WriteLine ("done in {0}.", s.Elapsed); Console.Error.WriteLine ("Serialized payload: {0}", jsonPayload); #endif var serviceClient = new CookieClient (); if (cookies != null) serviceClient.Cookies = cookies; serviceClient.Headers.Add (HttpRequestHeader.ContentType, "application/json"); #if DEBUG Console.Error.Write ("Making request..."); s.Reset (); s.Start (); #endif string responseJson = serviceClient.UploadString (ServiceUri, jsonPayload); #if DEBUG s.Stop (); Console.Error.WriteLine ("done in {0}.", s.Elapsed); Console.Error.WriteLine ("Response: {0}", responseJson); #endif cookies = serviceClient.Cookies; #if DEBUG s.Reset (); Console.Error.Write ("Deserializing result..."); s.Start (); #endif var response = new Deserializer (responseJson).Deserialize () as Dictionary<string, object>; #if DEBUG s.Stop (); Console.Error.WriteLine ("done in {0}.", s.Elapsed); #endif if ((long)response ["id"] != callId) throw new ApplicationException (string.Format ("Response ID and original call ID don't match. Expected {0}, received {1}.", callId, response ["id"])); if (response ["error"] != null) throw new ApplicationException (string.Format ("Received error message from Bugzilla. Message: {0}", ((JsonObject)response ["error"]) ["message"])); return response; }
public static JsonArray ServerRequest(string requestUrl) { try { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; using(HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if(response.StatusCode != HttpStatusCode.OK) { string s = String.Format("Server error(HTTP {0}: {1}).", response.StatusCode, response.StatusDescription); throw new Exception(s); } Stream receiveStream = response.GetResponseStream(); Deserializer d = new Deserializer(receiveStream); object jd = d.Deserialize(); JsonArray ja = jd as JsonArray; response.Close(); receiveStream.Close(); return ja; } } catch(Exception e) { SC.log(e.Message); return null; } }
public Dictionary<string, object> DoServiceCall(string method, params object[] parameters) { var callId = Interlocked.Increment (ref this.callId); var callObject = new Dictionary<string, object> { {"id", callId}, {"method", method}, {"params", parameters} }; #if DEBUG Console.Error.Write ("Serializing JSON-RPC call object..."); Stopwatch s = new Stopwatch (); s.Start (); #endif string jsonPayload = new Serializer (callObject).Serialize (); #if DEBUG s.Stop (); Console.Error.WriteLine ("done in {0}.", s.Elapsed); #endif var serviceClient = new CookieClient (); if (cookies != null) serviceClient.Cookies = cookies; #if DEBUG Console.Error.Write ("Making request..."); s.Reset (); s.Start (); #endif byte[] returnData = serviceClient.UploadData (ServiceUri, Encoding.UTF8.GetBytes (jsonPayload)); #if DEBUG s.Stop (); Console.Error.WriteLine ("done in {0}.", s.Elapsed); #endif cookies = serviceClient.Cookies; #if DEBUG s.Reset (); Console.Error.Write ("Decompressing result..."); s.Start (); #endif // All this because deluge always returns gzip data, despite what you send for Accept-Encoding. var responseJson = new StreamReader (new GZipStream (new MemoryStream (returnData), CompressionMode.Decompress), Encoding.UTF8).ReadToEnd (); #if DEBUG s.Stop (); Console.Error.WriteLine ("done in {0}.", s.Elapsed); #endif #if DEBUG s.Reset (); Console.Error.Write ("Deserializing result..."); s.Start (); #endif var response = new Deserializer (responseJson).Deserialize () as Dictionary<string, object>; #if DEBUG s.Stop (); Console.Error.WriteLine ("done in {0}.", s.Elapsed); #endif if ((long) response["id"] != callId) throw new ApplicationException (string.Format ("Response ID and original call ID don't match. Expected {0}, received {1}.", callId, response["id"])); if (response["error"] != null) throw new ApplicationException (string.Format ("Received error message from Deluge. Message: {0}", ((JsonObject) response["error"])["message"])); return response; }