public void ProcessRequest(HttpContext context) { string action = context.Request.Form["Action"]; context.Response.Clear(); context.Response.ContentType = "application/json"; try { switch (action) { #region 本月账单 case "currentMon": TradeLsit(context, action); break; #endregion #region 全部账单 case "allMon": TradeLsit(context, action); break; #endregion default: break; } } catch (Exception ex) { JsonObject json = new JsonObject(); json.Put(TAO_KEY_STATUS, TAO_STATUS_ERROR); json.Put(TAO_KEY_DATA, ex); context.Response.Write(json.ToString()); } }
public virtual object Invoke(string method, params object[] args) { WebRequest request = GetWebRequest(new Uri(Url)); request.Method = "POST"; using (Stream stream = request.GetRequestStream()) using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) { JsonObject call = new JsonObject(); call["id"] = ++_id; call["method"] = method; call["params"] = args; call.Export(new JsonTextWriter(writer)); } using (WebResponse response = GetWebResponse(request)) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { JsonObject answer = new JsonObject(); answer.Import(new JsonTextReader(reader)); object errorObject = answer["error"]; if (errorObject != null) OnError(errorObject); return answer["result"]; } }
private string BuildQuery(JsonObject values) { List<string[]> pairs = new List<String[]>(); foreach (string k in values.Names) { AddValues(pairs, new List<string>(), k, values[k]); } StringBuilder result = new StringBuilder(); bool first = true; foreach (string[] pair in pairs) { if (first) { first = false; } else { result.Append('&'); } result.Append(HttpUtility.UrlEncode(pair[0])); result.Append('='); result.Append(HttpUtility.UrlEncode(pair[1])); } return result.ToString(); }
public static JsonObject FromException(Exception e, bool includeStackTrace) { if (e == null) throw new ArgumentNullException("e"); JsonObject error = new JsonObject(); error.Put("name", "JSONRPCError"); error.Put("message", e.GetBaseException().Message); if (includeStackTrace) error.Put("stackTrace", e.StackTrace); JsonArray errors = new JsonArray(); do { errors.Put(ToLocalError(e)); e = e.InnerException; } while (e != null); error.Put("errors", errors); return error; }
public override string ToString() { JsonObject serialized = new JsonObject(); serialized.Put(KEY_MMSI, this.Mmsi); serialized.Put(KEY_NAME, this.Name); return serialized.ToString(); }
public static void StaticUpdateStats(JsonObject stats) { if (ClassSingleton<StatsDialog>.IsActive()) { ClassSingleton<StatsDialog>.Instance.UpdateStats(stats); } }
public static JsonObject FromRequest(HttpRequest request) { //String methodName = request.getPathInfo().replaceAll("/", ""); JsonObject root = new JsonObject(); NameValueCollection parameters = request.Params; root.Put("method", parameters["method"]); if (!string.IsNullOrEmpty(parameters.Get("id"))) { root.Put("id", parameters["id"]); } JsonObject paramsRoot = new JsonObject(); for (int i = 0; i < parameters.Count; i++) { if (!RESERVED_PARAMS.Contains(parameters.GetKey(i).ToLower())) { String[] path = parameters.GetKey(i).Split('\\'); JsonObject holder = BuildHolder(paramsRoot, path, 0); holder.Put(path[path.Length - 1], ConvertToJsonValue(parameters.GetValues(i)[0])); } } if (paramsRoot.Count > 0) { root.Put("params", paramsRoot); } return root; }
public static ArchiveInfo fromJson(JsonObject jo) { try { ArchiveInfo info = new ArchiveInfo() { Name = jo["name"].ToString(), Domain = jo["domain"].ToString(), SupportHttp = Convert.ToBoolean(jo["http"]), SupportHttps = Convert.ToBoolean(jo["https"]), Software = "foolfuuka" == jo["software"].ToString() ? ArchiverSoftware.FoolFuuka : ArchiverSoftware.Fuuka }; JsonArray boards = (JsonArray)jo["boards"]; foreach (string b in boards.Cast<string>()) { info.AddPostBoard(b); } JsonArray files = (JsonArray)jo["files"]; foreach (string b in boards.Cast<string>()) { info.AddFileBoard(b); } return info; } catch { return null; } }
private void AsyncPlayFilesWorker(object sender, DoWorkEventArgs e) { var songs = (Collection<ApiAudioSong>)e.Argument; if (songs == null) return; if (!_parent.IsConnected()) return; _parent.JsonCommand("AudioPlaylist.Clear", null); var i = 0; var args = new JsonObject(); foreach (var apiAudioSong in songs) { if (((BackgroundWorker)sender).CancellationPending) { e.Cancel = true; return; } args["songid"] = apiAudioSong.IdSong; _parent.JsonCommand("AudioPlaylist.Add", args); if (i != 0) continue; _parent.JsonCommand("AudioPlaylist.Play", null); i++; } }
public void UpdateStats(JsonObject stats) { try { Toolbox.MaxSize ms = (Toolbox.MaxSize)(unitFactorComboBox.SelectedIndex + 1); JsonObject sessionstats = (JsonObject)stats["current-stats"]; JsonObject cumulativestats = (JsonObject)stats["cumulative-stats"]; TimeSpan ts = TimeSpan.FromSeconds(Toolbox.ToLong(sessionstats["secondsActive"])); downloadedBytesValue1.Text = Toolbox.GetFileSize(Toolbox.ToLong(sessionstats["downloadedBytes"]), ms); uploadedBytesValue1.Text = Toolbox.GetFileSize(Toolbox.ToLong(sessionstats["uploadedBytes"]), ms); filesAddedValue1.Text = ((JsonNumber)sessionstats["filesAdded"]).ToString(); sessionCountValue1.Text = ((JsonNumber)sessionstats["sessionCount"]).ToString(); secondsActiveValue1.Text = Toolbox.FormatTimespanLong(ts); ts = TimeSpan.FromSeconds(Toolbox.ToLong(cumulativestats["secondsActive"])); downloadedBytesValue2.Text = Toolbox.GetFileSize(Toolbox.ToLong(cumulativestats["downloadedBytes"]), ms); uploadedBytesValue2.Text = Toolbox.GetFileSize(Toolbox.ToLong(cumulativestats["uploadedBytes"]), ms); filesAddedValue2.Text = ((JsonNumber)cumulativestats["filesAdded"]).ToString(); sessionCountValue2.Text = ((JsonNumber)cumulativestats["sessionCount"]).ToString(); secondsActiveValue2.Text = ts.Ticks < 0 ? OtherStrings.UnknownNegativeResult : Toolbox.FormatTimespanLong(ts); } catch (Exception ex) { MessageBox.Show(ex.Message, "Unable to load stats data", MessageBoxButtons.OK, MessageBoxIcon.Error); CloseAndDispose(); } }
public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session) { if (request.UriPath.StartsWith(Url)) { string hash = request.QueryString["hash"].Value; if (string.IsNullOrEmpty(hash)) { ThreadServerModule._404(response); } else { if (Program.queued_files.ContainsKey(hash)) { FileQueueStateInfo f = Program.queued_files[hash]; JsonObject ob = new JsonObject(); ob.Add("p", f.Percent().ToString()); ob.Add("s", string.Format("{0} / {1}", Program.format_size_string(f.Downloaded), Program.format_size_string(f.Length))); ob.Add("c", f.Status == FileQueueStateInfo.DownloadStatus.Complete); WriteJsonResponse(response, ob.ToString()); } else { ThreadServerModule._404(response); } } return true; } return false; }
public TorrentGetCommand(JsonObject response) { Program.DaemonDescriptor.ResetFailCount(); if (!Program.Connected) { return; } JsonObject arguments = (JsonObject)response[ProtocolConstants.KEY_ARGUMENTS]; JsonArray torrents = (JsonArray)arguments[ProtocolConstants.KEY_TORRENTS]; Program.DaemonDescriptor.UpdateSerial++; oldCount = Program.TorrentIndex.Count; UpdateTorrents.Clear(); for (int i = 0; i < torrents.Count; i++) { JsonObject torrent = (JsonObject)torrents[i]; string hash = (string)torrent[ProtocolConstants.FIELD_HASHSTRING]; Torrent t = null; lock (Program.TorrentIndex) { if (!Program.TorrentIndex.ContainsKey(hash)) { t = new Torrent(torrent); } else { t = Program.TorrentIndex[hash]; if (t.Update(torrent, false)) stateChange = true; } UpdateTorrents.Add(t); } totalUpload += t.UploadRate; totalDownload += t.DownloadRate; } }
public void InitWithKeyValuePairs() { JsonObject o = new JsonObject(new string[] { "one", "two", }, new object[] { 1, 2 }); Assert.AreEqual(2, o.Count); Assert.AreEqual(1, o["one"]); Assert.AreEqual(2, o["two"]); }
public JsonObject(JsonObject jo, String[] names) { for (int i = 0; i < names.Length; i += 1) { PutOpt(names[i], jo.Opt(names[i])); } }
public PeerListViewItem(JsonObject peerObj) : base((string)peerObj[ProtocolConstants.ADDRESS]) { for (int i = 0; i < 7; i++) base.SubItems.Add(""); this.Address = base.Name = base.Text; int countryIndex = -1; if (!GeoIPCountry.Disabled) { try { countryIndex = GeoIPCountry.Instance.FindIndex(this.IpAddress); } catch { } } if (countryIndex > 0) this.Country = GeoIPCountry.CountryNames[countryIndex]; this.ClientName = (string)peerObj[ProtocolConstants.FIELD_CLIENTNAME]; this.Update(peerObj); if (countryIndex > 0) { base.ImageIndex = GeoIPCountry.FlagImageList.Images.IndexOfKey("flags_" + GeoIPCountry.CountryCodes[countryIndex].ToLower()); } Dns.BeginGetHostEntry(this.IpAddress, new AsyncCallback(GetHostEntryCallback), this); }
public Collection<ApiAudioGenre> GetGenres() { var genres = new Collection<ApiAudioGenre>(); var properties = new JsonArray(new[] { "title", "thumbnail" }); var param = new JsonObject(); param["properties"] = properties; var result = (JsonObject)_parent.JsonCommand("AudioLibrary.GetGenres", param); if (result != null) { if (result.Contains("genres")) { foreach (JsonObject genre in (JsonArray)result["genres"]) { try { var gen = new ApiAudioGenre { IdGenre = (long)(JsonNumber)genre["genreid"], Name = genre["title"].ToString(), AlbumCount = 0, Thumb = genre["thumbnail"].ToString() }; genres.Add(gen); } catch (Exception) { } } } } return genres; }
public Collection<ApiAudioArtist> GetArtists() { var artists = new Collection<ApiAudioArtist>(); var properties = new JsonArray(new[] { "thumbnail", "fanart", "description" }); var param = new JsonObject(); param["properties"] = properties; var result = (JsonObject)_parent.JsonCommand("AudioLibrary.GetArtists", param); if (result != null) { if (result.Contains("artists")) { foreach (JsonObject genre in (JsonArray)result["artists"]) { try { var artist = new ApiAudioArtist { IdArtist = (long)(JsonNumber)genre["artistid"], Name = genre["artist"].ToString(), Thumb = genre["thumbnail"].ToString(), Fanart = genre["fanart"].ToString(), Biography = genre["description"].ToString() }; artists.Add(artist); } catch (Exception) { } } } } return artists; }
private void AsyncPlayFilesWorker(object sender, DoWorkEventArgs e) { var songs = (Collection<ApiAudioSong>)e.Argument; if (songs == null) return; if (!_parent.IsConnected()) return; var plId = new JsonObject(); plId["playlistid"] = 1; _parent.JsonCommand("Playlist.Clear", plId); var i = 0; var args = new JsonObject(); var items = new JsonObject(); foreach (var apiAudioSong in songs) { if (((BackgroundWorker)sender).CancellationPending) { e.Cancel = true; return; } args["songid"] = apiAudioSong.IdSong; items["item"] = args; items["playlistid"] = 1; _parent.JsonCommand("Playlist.Add", items); if (i != 0) continue; var item = new JsonObject(); item["item"] = plId; _parent.JsonCommand("Player.Open", item); i++; } }
public static void Main(string[] args) { JsonWsp.Client cli = new JsonWsp.Client("http://10.1.5.160/service/AccessService/jsonwsp/description"); cli.SetViaProxy(true); if (args.Length==0) { Console.WriteLine("Usage: jsontest.exe <session_id>"); return; } Console.WriteLine("Call listPermissions"); Console.WriteLine("--------------------"); // Build arguments JsonObject args_dict = new JsonObject(); args_dict.Add("session_id",args[0]); // Call method JsonObject result = CommonCall(cli,"listPermissions",args_dict); if (result != null) { Jayrock.Json.JsonArray perm = (Jayrock.Json.JsonArray) result["access_identifiers"]; foreach (string i in perm) { Console.WriteLine(i); } } Console.WriteLine(); Console.WriteLine("Call hasPermissions"); Console.WriteLine("-------------------"); // Build arguments JsonObject args_dict2 = new JsonObject(); args_dict2.Add("session_id",args[0]); args_dict2.Add("access_identifier","product.web.10finger"); // Call method result = CommonCall(cli,"hasPermission",args_dict2); // Print if (result != null) { bool access = (bool) result["has_permission"]; if (access) { Console.WriteLine("Access Granted"); } else { Console.WriteLine("Access Denied"); } } Console.WriteLine(); Console.WriteLine("Call getUserInfo"); Console.WriteLine("----------------"); cli = new JsonWsp.Client("http://10.1.5.160/service/UserService/jsonwsp/description"); result = CommonCall(cli,"getUserInfo",args_dict); if (result != null) { JsonObject user_info = (JsonObject) result["user_info"]; Console.WriteLine("Org-name: " + user_info["org_name"]); Console.WriteLine("Org-domain: " + user_info["org_domain"]); Console.WriteLine("Org-code: " + user_info["org_code"]); Console.WriteLine("Org-type: " + user_info["org_type"]); Console.WriteLine("Given Name: " + user_info["given_name"]); Console.WriteLine("Surname: " + user_info["surname"]); Console.WriteLine("Uid: " + user_info["uid"]); Console.WriteLine("Common-name: " + user_info["common_name"]); } }
public void RegisterUser(JsonObject ps) { Profile p = new Profile(); ProfileManager pm = new ProfileManager(); FacebookService fb = new FacebookService(); Facebook.JsonObject o = fb.DownloadData<Facebook.JsonObject>("/me", ps["accessToken"].ToString()); if (pm.LoadUser(o["email"].ToString()) != null) throw new Exception("Profile already exists"); p.CreationDate = DateTime.Now; p.Email = o["email"].ToString(); p.IsLockedOut = false; if (o.ContainsKey("username")) p.UserName = o["username"].ToString(); else p.UserName = ps["userID"].ToString(); pm.RegisterUser(p); SocialConnection sc = new SocialConnection(); sc.OauthToken = ps["accessToken"].ToString(); sc.ReferenceID = ps["userID"].ToString(); sc.ServiceID = SocialServiceType.Facebook; sc.UserID = p.UserID; SocialServiceManager scm = new SocialServiceManager(); scm.AddConnection(sc); pm.ReleaseAuthenticationTicket(p); }
public void InitWithExtraKeys() { JsonObject o = new JsonObject(new string[] { "one", "two", "three" }, new object[] { 1, 2 }); Assert.AreEqual(3, o.Count); Assert.AreEqual(1, o["one"]); Assert.AreEqual(2, o["two"]); Assert.IsTrue(JsonNull.LogicallyEquals(o["three"])); }
public void InitWithNullValues() { JsonObject o = new JsonObject(new string[] { "one", "two", "three" }, null); Assert.AreEqual(3, o.Count); Assert.IsTrue(JsonNull.LogicallyEquals(o["one"])); Assert.IsTrue(JsonNull.LogicallyEquals(o["two"])); Assert.IsTrue(JsonNull.LogicallyEquals(o["three"])); }
public void ContentsClearedBeforeImporting() { JsonObject o = new JsonObject(); o.Put("foo", "bar"); Assert.AreEqual(1, o.Count); o.Import(new JsonTextReader(new StringReader("{}"))); Assert.AreEqual(0, o.Count); }
private static void addHeaders(JsonObject headers, sResponse response, String headerName) { string[] values = response.getHeaders(headerName); if (values != null) { headers.Put(headerName.ToLower(), new JsonArray(values)); } }
/** * Processes a JSON request. * * @param request Original JSON request * @return The JSON response. */ public JsonObject Process(JsonObject request) { JsonObject response = new JsonObject(); JsonObject requestContext = request.getJSONObject("context"); JsonArray requestedGadgets = request["gadgets"] as JsonArray; // Process all JSON first so that we don't wind up with hanging threads if // a JsonException is thrown. List<IAsyncResult> gadgets = new List<IAsyncResult>(requestedGadgets.Length); for (int i = 0, j = requestedGadgets.Length; i < j; ++i) { var context = new JsonRpcGadgetContext(requestContext, (JsonObject)requestedGadgets[i]); PreloadProcessor proc = new PreloadProcessor(CallJob); IAsyncResult result = proc.BeginInvoke(context, null, null); gadgets.Add(result); } foreach (var entry in gadgets) { try { AsyncResult result = (AsyncResult)entry; PreloadProcessor proc = (PreloadProcessor)result.AsyncDelegate; JsonObject gadget = proc.EndInvoke(result); response.Accumulate("gadgets", gadget); } catch (JsonException e) { throw new RpcException("Unable to write JSON", e); } catch (Exception ee) { if (!(ee is RpcException)) { throw new RpcException("Processing interrupted", ee); } RpcException e = (RpcException)ee; // Just one gadget failed; mark it as such. try { GadgetContext context = e.Context; JsonObject errorObj = new JsonObject(); errorObj.Put("url", context.getUrl()) .Put("moduleId", context.getModuleId()); errorObj.Accumulate("errors", e.Message); response.Accumulate("gadgets", errorObj); } catch (JsonException je) { throw new RpcException("Unable to write JSON", je); } } } return response; }
public UpdateFilesCommand(JsonObject response) { Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Program.Settings.Locale, true); Program.DaemonDescriptor.ResetFailCount(); MainWindow form = Program.Form; JsonObject arguments = (JsonObject)response[ProtocolConstants.KEY_ARGUMENTS]; JsonArray torrents = (JsonArray)arguments[ProtocolConstants.KEY_TORRENTS]; if (torrents.Count != 1) { return; } JsonObject torrent = (JsonObject)torrents[0]; JsonArray files = (JsonArray)torrent[ProtocolConstants.FIELD_FILES]; if (files == null) { return; } int id = Toolbox.ToInt(torrent[ProtocolConstants.FIELD_ID]); Torrent t = (Torrent)form.Invoke(new GetTorrentDelegate(delegate() { lock (Program.TorrentIndex) { foreach (KeyValuePair<string, Torrent> st in Program.TorrentIndex) { if (st.Value.Id == id) return st.Value; } } return null; })); if (t == null) { return; } JsonArray priorities = (JsonArray)torrent[ProtocolConstants.FIELD_PRIORITIES]; JsonArray wanted = (JsonArray)torrent[ProtocolConstants.FIELD_WANTED]; bool havepriority = (priorities != null && wanted != null); ImageList imgList = Program.Form.fileIconImageList; for (int i = 0; i < files.Length; i++) { JsonObject file = (JsonObject)files[i]; string name = Toolbox.TrimPath((string)file[ProtocolConstants.FIELD_NAME]); FileListViewItem item = t.Files.Find(name); if (item == null) { item = new FileListViewItem(file, imgList, i, wanted, priorities); t.Files.Add(item); } else { Program.Form.Invoke(new MethodInvoker(delegate() { item.Update(file, wanted, priorities); })); } } }
public Fault(JsonObject fault) { JsonArray detail = (JsonArray)fault["detail"]; m_details = String.Join("\n",(string[]) detail.ToArray()); m_error_string = (string) fault["string"]; m_fault_type = (string)fault["code"]=="server"?FaultType.ServerFault:FaultType.ClientFault; m_filename = (string)fault["filename"]; m_lineno = ((JsonNumber)fault["lineno"]).ToInt32(); }
public void Add() { JsonObject o = new JsonObject(); o.Add("foo", "bar"); Assert.AreEqual("bar", o["foo"]); ICollection names = o.Names; Assert.AreEqual(1, names.Count); Assert.AreEqual(new string[] { "foo" }, CollectionHelper.ToArray(names, typeof(string))); }
private void Push() { _valueStack.Push(_value); _memberStack.Push(_member); _array = null; _object = null; _value = null; _member = null; }
public void Names() { JsonObject o = new JsonObject(); o.Put("one", 1); o.Put("two", 2); ICollection names = o.Names; IEnumerator e = names.GetEnumerator(); e.MoveNext(); Assert.AreEqual("one", e.Current); e.MoveNext(); Assert.AreEqual("two", e.Current); }
public Jayrock.Json.JsonArray getImageJsonArray() { DatabaseAccess dbAccess = new DatabaseAccess(); Jayrock.Json.JsonArray images = new Jayrock.Json.JsonArray(); Jayrock.Json.JsonObject image; System.Data.DataTable dt; string sql = "select ID, FileName, Description, MIME from [Image] where Category='" + GlobalSetting.ArticleCategory.News + "' and ParentID = " + ID.ToString(); dbAccess.open(); try { dt = dbAccess.select(sql); } catch (Exception ex) { throw ex; } finally { dbAccess.close(); } foreach (System.Data.DataRow row in dt.Rows) { image = new Jayrock.Json.JsonObject(); foreach (System.Data.DataColumn col in dt.Columns) { image.Accumulate(col.ColumnName.ToLower(), row[col.ColumnName]); } images.Add(image); } return(images); }