public void JsonObjectConstructorParmsTest() { JsonObject target = new JsonObject(); Assert.Equal(0, target.Count); string key1 = AnyInstance.AnyString; string key2 = AnyInstance.AnyString2; JsonValue value1 = AnyInstance.AnyJsonValue1; JsonValue value2 = AnyInstance.AnyJsonValue2; List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>() { new KeyValuePair<string, JsonValue>(key1, value1), new KeyValuePair<string, JsonValue>(key2, value2), }; target = new JsonObject(items[0], items[1]); Assert.Equal(2, target.Count); ValidateJsonObjectItems(target, key1, value1, key2, value2); target = new JsonObject(items.ToArray()); Assert.Equal(2, target.Count); ValidateJsonObjectItems(target, key1, value1, key2, value2); // Invalid tests items.Add(new KeyValuePair<string, JsonValue>(key1, AnyInstance.DefaultJsonValue)); ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items[0], items[1], items[2]); }); ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items.ToArray()); }); }
public void PostJSON( string inURL, JsonObject inJSON, Action< string, JsonObject > inCallback ) { var headers = new Dictionary< string, string >(); headers[ "Content-Type" ] = "application/json"; var jsonString = SimpleJson.SimpleJson.SerializeObject( inJSON ); Post( inURL, System.Text.Encoding.UTF8.GetBytes( jsonString ), headers, ( string inError, WWW inWWW ) => { if( inCallback != null ) { JsonObject obj = null; if ( string.IsNullOrEmpty( inError ) && ! string.IsNullOrEmpty( inWWW.text ) ) { Debug.Log("Response: " + inWWW.text ); object parsedObj = null; if ( SimpleJson.SimpleJson.TryDeserializeObject( inWWW.text, out parsedObj ) ) { obj = ( JsonObject ) parsedObj; } } inCallback( inError, obj ); } } ); }
public MsgEncoder(JsonObject protos) { if (protos == null) protos = new JsonObject(); this.protos = protos; this.util = new Util(); }
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); }); }
public static TwitterReverseGeocodeQuery Parse(TwitterReverseGeocodeResults results, JsonObject obj) { return new TwitterReverseGeocodeQuery(obj) { Results = results, Url = obj.GetString("url"), Type = obj.GetString("type") }; }
/// <summary> /// Encode the messge with id, route and jsonObject. /// </summary> /// <param name='id'> /// Identifier. /// </param> /// <param name='route'> /// Route. /// </param> /// <param name='jsonObject'> /// Json object. /// </param> /// <exception cref='System.ArgumentException'> /// Is thrown when the argument exception. /// </exception> public static string encode(int id, string route, JsonObject jsonObject) { if (route.Length > 255) { throw new System.ArgumentException("route maxlength is overflow"); } byte[] byteArray = new byte[HEADER + route.Length]; int index = 0; byteArray[index++] = Convert.ToByte((id >> 24) & 0xFF); byteArray[index++] = Convert.ToByte((id >> 16) & 0xFF); byteArray[index++] = Convert.ToByte((id >> 8) & 0xFF); byteArray[index++] = Convert.ToByte(id & 0xFF); byteArray[index++] = Convert.ToByte(route.Length & 0xFF); char[] routeArray = route.ToCharArray(); int routeLength = routeArray.Length; for(int i = 0; i < routeLength; i++) { byteArray[index++] = Convert.ToByte(routeArray[i]); } string encodeString = ""; try{ encodeString = Encoding.UTF8.GetString(byteArray); }catch(Exception e){ Console.WriteLine(string.Format("Error in new Encoding.UTF8.GetString:{0}", e.Message)); } return encodeString + jsonObject.ToString(); }
internal static JsonObject Generate(WorklogInput worklogInput) { var json = new JsonObject { { "self", worklogInput.Self.ToString() }, { "comment", worklogInput.Comment }, { "started", worklogInput.StartDate.ToRestString() }, { "timeSpent", worklogInput.MinutesSpent.ToString() } }; if (worklogInput.Visibility != null) { json.Add("visibility", VisibilityJsonGenerator.Generate(worklogInput.Visibility).ToJson()); } if (worklogInput.Author != null) { json.Add("author", BasicUserJsonGenerator.Generate(worklogInput.Author).ToJson()); } if (worklogInput.UpdateAuthor != null) { //json.Add("updateAuthor", BasicUserJsonGenerator.Generate(worklogInput.UpdateAuthor).ToString()); json.Add("updateAuthor", worklogInput.UpdateAuthor.ToJson()); } return json; }
// Use this for initialization void Start () { // json对象构造示例 JsonObject root = new JsonObject(); root["age"] = 25; root["name"] = "rare"; JsonObject obj = new JsonObject(); root["person"] = obj; obj["age"] = 1; obj["name"] = "even"; JsonArray arr = new JsonArray(); arr[0] = "ComputerGrphic"; arr[1] = "Unity3D"; arr[2] = "Graphic"; root["books"] = arr; // json取值 int a = root["age"]; Debug.Log("age:"+a.ToString()); string v = root["name"]; Debug.Log("name:" + v); // save json and format string strSerializeFile = Application.dataPath + "json/home.json"; RareJson.Serialize(root, strSerializeFile, true); // json解析 string strJsonName = Application.dataPath + "json/Contents.json"; JsonNode node = RareJson.ParseJsonFile(strJsonName); // json not format strSerializeFile = Application.dataPath + "json/serialize.json"; RareJson.Serialize(node, strSerializeFile, false); }
/// <summary>${REST_GeometryBufferAnalystResult_method_fromJson_D}</summary> /// <returns>${REST_GeometryBufferAnalystResult_method_fromJson_return}</returns> /// <param name="jsonResult">${REST_GeometryBufferAnalystResult_method_fromJson_param_jsonObject}</param> internal static GeometryBufferAnalystResult FromJson(JsonObject jsonResult) { GeometryBufferAnalystResult result = new GeometryBufferAnalystResult(); result.ResultGeometry = (ServerGeometry.FromJson(jsonResult["resultGeometry"].GetObjectEx())).ToGeometry(); //result.Image = ImageResult.FromJson((System.Json.JsonObject)jsonResult["image"]); return result; }
/// <summary> /// Constructs a ModuleDescriptor from a Json object /// </summary> /// <param name="InObject"></param> /// <returns>The new module descriptor</returns> public static ModuleDescriptor FromJsonObject(JsonObject InObject) { ModuleDescriptor Module = new ModuleDescriptor(InObject.GetStringField("Name"), InObject.GetEnumField<ModuleHostType>("Type")); ModuleLoadingPhase LoadingPhase; if (InObject.TryGetEnumField<ModuleLoadingPhase>("LoadingPhase", out LoadingPhase)) { Module.LoadingPhase = LoadingPhase; } UnrealTargetPlatform[] WhitelistPlatforms; if (InObject.TryGetEnumArrayField<UnrealTargetPlatform>("WhitelistPlatforms", out WhitelistPlatforms)) { Module.WhitelistPlatforms = WhitelistPlatforms; } UnrealTargetPlatform[] BlacklistPlatforms; if (InObject.TryGetEnumArrayField<UnrealTargetPlatform>("BlacklistPlatforms", out BlacklistPlatforms)) { Module.BlacklistPlatforms = BlacklistPlatforms; } string[] AdditionalDependencies; if (InObject.TryGetStringArrayField("AdditionalDependencies", out AdditionalDependencies)) { Module.AdditionalDependencies = AdditionalDependencies; } return Module; }
public void OnSendMsgBtn() { string szRoute = "connector.entryHandler.notify"; JsonObject jsonMessage = new JsonObject(); jsonMessage.Add("key", "OnSendMsgBtn"); m_PomeloClient.notify(szRoute, jsonMessage); }
/// <summary>${REST_ClosestFacilityPath_method_fromJson_D}</summary> /// <returns>${REST_ClosestFacilityPath_method_fromJson_return}</returns> /// <param name="json">${REST_ClosestFacilityPath_method_fromJson_param_jsonObject}</param> internal static ClosestFacilityPath FromJson(JsonObject json) { if (json != null) { ClosestFacilityPath result = new ClosestFacilityPath(); if (json["facility"].ValueType==JsonValueType.Number) { result.Facility = (int)json["facility"].GetNumberEx(); } else { result.Facility = JsonHelper.ToPoint2D(json["facility"].GetObjectEx()); } result.FacilityIndex = (int)json["facilityIndex"].GetNumberEx(); //对应父类中的属性; ServerPath path = ServerPath.ServerPathFromJson(json); result.EdgeFeatures = path.EdgeFeatures; result.EdgeIDs = path.EdgeIDs; result.NodeFeatures = path.NodeFeatures; result.NodeIDs = path.NodeIDs; result.PathGuideItems = path.PathGuideItems; result.Route = path.Route; result.StopWeights = path.StopWeights; result.Weight = path.Weight; return result; } return null; }
// Strip null values from serialized JSON. protected override bool TrySerializeUnknownTypes(object input, out object output) { var result = new JsonObject(); var getters = GetCache[input.GetType()].Where(x => x.Value != null); foreach (var getter in getters) { var value = getter.Value(input); if (value == null) { continue; } var dictionary = value as IDictionary; if (dictionary != null) { value = ToObject(dictionary); } var fieldName = MapClrMemberNameToJsonFieldName(getter.Key); result.Add(fieldName, value); } output = result; return true; }
public static TwitterHashTagEntitity Parse(JsonObject entity) { return new TwitterHashTagEntitity { Text = entity.GetString("text"), StartIndex = entity.GetArray("indices").GetInt(0), EndIndex = entity.GetArray("indices").GetInt(1) }; }
/// <summary> /// Gets an instance of <code>YouTubeVideoSnippet</code> from the specified <code>JsonObject</code>. /// </summary> /// <param name="obj">The instance of <code>JsonObject</code> to parse.</param> public static YouTubeVideoSnippet Parse(JsonObject obj) { // Check whether "obj" is NULL if (obj == null) return null; // Parse the "liveBroadcastContent" property YouTubeVideoLiveBroadcastContent broadcast; string strBroadcast = obj.GetString("liveBroadcastContent"); if (!Enum.TryParse(strBroadcast, true, out broadcast)) { throw new Exception("Unknown value for liveBroadcastContent \"" + strBroadcast + "\" - please create an issue so it can be fixed https://github.com/abjerner/Skybrud.Social/issues/new"); } // Get the array of tags (may not be present) JsonArray tags = obj.GetArray("tags"); // Initialize the snippet object YouTubeVideoSnippet snippet = new YouTubeVideoSnippet(obj) { PublishedAt = obj.GetDateTime("publishedAt"), ChannelId = obj.GetString("channelId"), Title = obj.GetString("title"), Description = obj.GetString("description"), Thumbnails = obj.GetObject("thumbnails", YouTubeVideoThumbnails.Parse), ChannelTitle = obj.GetString("channelTitle"), Tags = tags == null ? new string[0] : obj.GetArray("tags").Cast<string>(), CategoryId = obj.GetString("categoryId"), LiveBroadcastContent = broadcast }; return snippet; }
/// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { // Allow saved page state to override the initial item to display if (pageState != null && pageState.ContainsKey("SelectedItem")) { navigationParameter = pageState["SelectedItem"]; } Geolocator locator = new Geolocator(); Geoposition geoPos = await locator.GetGeopositionAsync(); Geocoordinate geoCoord = geoPos.Coordinate; String YWSID = "Bi9Fsbfon92vmD4DkkO4Fg"; String url; if (navigationParameter != "") { url = "http://api.yelp.com/business_review_search?term=food&location=" + navigationParameter + "&ywsid=" + YWSID; } else { url = "http://api.yelp.com/business_review_search?term=food&lat=" + geoCoord.Latitude + "&long=" + geoCoord.Longitude + "&ywsid=" + YWSID; } var httpClient = new HttpClient(); String content = await httpClient.GetStringAsync(url); response = JsonObject.Parse(content); this.Frame.Navigate(typeof(MainPage),response); }
private void ReadValue(JsonObject input) { if (input == null) writer.WriteNull(); else input.Accept(this); }
protected override void ProcessSub(HttpContext context, string uploadPath, string fileName) { JsonObject obj2 = new JsonObject(); obj2.Put("data", uploadPath + "T_" + fileName); obj2.Put("success", true); context.Response.Write(obj2.ToString()); }
public override void Append(JsonSchemaRuleComponent rules, JsonObject definition, Func<JsonObject, JsonSchemaRule> parse) { if (definition.Contains<JsonTrue>("uniqueItems")) { rules.Add(new JsonUniqueItemsRule()); } }
private static JsonObject serializeObject(object obj) { PropertyInfo[] propInfo = obj.GetType().GetProperties(); string propertyName; object propertyValue; JsonValueType type; JsonObject o = new JsonObject(propInfo.Length); foreach (var p in propInfo) { propertyName = p.Name; propertyValue = p.GetValue(obj); type = JsonValue.GetPrimitiveType(p.PropertyType); if (type == JsonValueType.Object) { JsonObject o2 = serializeObject(propertyValue); o.Add(propertyName, o2); continue; } else if (type == JsonValueType.Array) { JsonArray a = serializeArray((IEnumerable)propertyValue); o.Add(propertyName, a); continue; } else { string value = propertyValue.ToString(); JsonPrimitive primitive = new JsonPrimitive(value, type); o.Add(propertyName, primitive); } } return o; }
/// <summary> /// If the event exists,invoke the event when server return messge. /// </summary> /// <param name="eventName"></param> /// <param name="value"></param> /// <returns></returns> /// public void InvokeOnEvent(string route, JsonObject msg) { if(!this.eventMap.ContainsKey(route)) return; List<Action<JsonObject>> list = eventMap[route]; foreach(Action<JsonObject> action in list) action.Invoke(msg); }
private string AddRuleProduct(HttpContext context) { JsonObject obj2 = new JsonObject(); int num = Convert.ToInt32(context.Request.Form["ProductId"]); int ruleId = Convert.ToInt32(context.Request.Form["RuleId"]); string str = context.Request.Form["ProductName"]; if (this.ruleProductBll.Exists(ruleId, (long) num)) { obj2.Put("STATUS", "Presence"); return obj2.ToString(); } Maticsoft.Model.Shop.Sales.SalesRuleProduct model = new Maticsoft.Model.Shop.Sales.SalesRuleProduct { ProductId = num, RuleId = ruleId, ProductName = str }; if (this.ruleProductBll.Add(model)) { obj2.Put("STATUS", "SUCCESS"); obj2.Put("DATA", "Approve"); return obj2.ToString(); } obj2.Put("STATUS", "NODATA"); return obj2.ToString(); }
public static FacebookObject Parse(JsonObject obj) { if (obj == null) return null; return new FacebookObject(obj) { Id = obj.GetString("id"), Name = obj.GetString("name") }; }
public static void Run() { //TODO: Fix this up with a request wrapper dynamic googleSearch = new RestClient(null, Services.GoogleSearchUri, RestService.Json); Console.WriteLine("Searching Google for 'seattle'..."); dynamic searchOptions = new JsonObject(); searchOptions.q = "seattle"; dynamic search = googleSearch.invokeAsync(searchOptions); search.Callback((RestCallback)delegate() { dynamic results = search.Result.responseData.results; foreach (dynamic item in results) { Console.WriteLine(item.titleNoFormatting); Console.WriteLine(item.url); Console.WriteLine(); } }); while (search.IsCompleted == false) { Console.WriteLine("."); Thread.Sleep(100); } }
private void CreateJsonTest() { JsonArray weekDiet = new JsonArray(); for(int i=0;i<7;i++) { JsonObject diet = new JsonObject(); diet["DayNumber"] = i; diet["Breakfast"] = "Banana"+ i; diet["Lunch"] = "Banana"+ i; diet["Dinner"] = "Banana"+ i; diet["WithSugar"] = (i % 2 == 0); diet["RandomNumber"] = Random.Range(0f,1.5f); weekDiet.Add(diet); } for (int i=0;i<7;i++) { if (i % 2 == 1) { weekDiet[i]["RandomNumber"] = 3; weekDiet[i]["RandomNumber"] = weekDiet[i]["RandomNumber"] * 2f; } } Debug.Log("Test InputOutputFileTest done: \n"+ weekDiet.ToJsonPrettyPrintString()); }
//note the async keyword - it's cause we're using an "await" method in our method body public async void Update() { var client = new HttpClient(); //ooh fancy new await syntax! //this actually executes in parallel and pauses the rest of the method's execution until it returns //(in a non blocking way of course) var result = await client.GetAsync(string.Format("http://search.twitter.com/search.json?q={0}&since_id={1}", SearchTerm, Since)); var root = new JsonObject(result.Content.ReadAsString()); var array = root.GetNamedArray("results"); for(int i = 0; i < array.Count; i++) { var element = array[i]; JsonObject obj = element.GetObject(); Tweet tweet = new Tweet { created_at = obj.GetNamedString("created_at"), from_user = obj.GetNamedString("from_user"), id_str = obj.GetNamedString("id_str"), profile_image_url = obj.GetNamedString("profile_image_url"), text = obj.GetNamedString("text") }; if (!Tweets.Any(t => t.id_str == tweet.id_str)) { Tweets.Insert(0, tweet); } } }
private void DeleteBrands(HttpContext context) { JsonObject obj2 = new JsonObject(); string str = context.Request.Params["idList"]; if (!string.IsNullOrWhiteSpace(str)) { Maticsoft.BLL.Shop.Products.BrandInfo info = new Maticsoft.BLL.Shop.Products.BrandInfo(); Maticsoft.BLL.Shop.Products.ProductInfo info2 = new Maticsoft.BLL.Shop.Products.ProductInfo(); Maticsoft.BLL.Shop.Products.ProductTypeBrand brand = new Maticsoft.BLL.Shop.Products.ProductTypeBrand(); int brandId = Globals.SafeInt(str, 0); if (info2.ExistsBrands(brandId)) { obj2.Put("STATUS", "FAILED"); obj2.Put("DATA", "该品牌正在使用中!"); } if (info.DeleteList(str)) { brand.Delete(null, new int?(brandId)); obj2.Put("STATUS", "SUCCESS"); } else { obj2.Put("STATUS", "FAILED"); obj2.Put("DATA", "系统忙,请稍后再试!"); } } else { obj2.Put("STATUS", "FAILED"); obj2.Put("DATA", "系统忙,请稍后再试!"); } context.Response.Write(obj2.ToString()); }
public void GetCategoryInfo(HttpContext context) { Func<Maticsoft.Model.SNS.Categories, bool> predicate = null; string categoryId = context.Request.Params["CID"]; int type = Globals.SafeInt(context.Request.Params["Type"], 0); JsonObject obj2 = new JsonObject(); if (!string.IsNullOrWhiteSpace(categoryId)) { if (predicate == null) { predicate = c => c.ParentID == Globals.SafeInt(categoryId, 0); } List<Maticsoft.Model.SNS.Categories> list2 = this.SNSCateBll.GetAllCateByCache(type).Where<Maticsoft.Model.SNS.Categories>(predicate).ToList<Maticsoft.Model.SNS.Categories>(); if ((list2 != null) && (list2.Count > 0)) { JsonArray data = new JsonArray(); list2.ForEach(delegate (Maticsoft.Model.SNS.Categories info) { data.Add(new JsonObject(new string[] { "CategoryId", "Name", "ParentID", "HasChildren" }, new object[] { info.CategoryId, info.Name, info.ParentID, info.HasChildren })); }); obj2.Put("STATUS", "Success"); obj2.Put("DATA", data); } else { obj2.Put("STATUS", "Fail"); } } else { obj2.Put("STATUS", "Error"); } context.Response.Write(obj2.ToString()); }
virtual public void start(JsonObject user, Action <JsonObject> callback) { this.transporter.start(); }
public void GetDataList() { _pageSize = UrlHelper.ReqIntByGetOrPost("pagesize", _pageSize); _total = UrlHelper.ReqLongByGetOrPost("total"); _selectTypeName = UrlHelper.ReqStrByGetOrPost("selecttypename"); _page = UrlHelper.ReqIntByGetOrPost("page"); _minid = UrlHelper.ReqStrByGetOrPost("minid"); _maxid = UrlHelper.ReqStrByGetOrPost("maxid"); _descOrder = UrlHelper.ReqBoolByGetOrPost("descorder", true); bool IsGetTotal = UrlHelper.ReqBoolByGetOrPost("isgettotal", true); string[] fieldArr = new string[] { "[SystemRoleID]" , "[SystemRoleName]" , "[RoleDesc]" , "[IsSystem]" }; int pageSize = UrlHelper.ReqIntByGetOrPost("pageSize"); int pageNumber = UrlHelper.ReqIntByGetOrPost("pageNumber"); string condition = MakeConditionString <DBControl.DBInfo.Tables.SystemRole>(HttpContext.Current, "s_"); try { JsonObject jsonData = JsonResult(false, enumReturnTitle.GetData, "数据获取失败。"); IDataReader idr = null; if (string.IsNullOrWhiteSpace(_selectTypeName)) { throw new Exception("请指定加载页面数据的类型,如首页selecttypename=firstpage等"); } enumSelectType selectType = (enumSelectType)Enum.Parse(typeof(enumSelectType), _selectTypeName, true); switch (selectType) { case enumSelectType.FirstPage: idr = DBControl.Base.DBAccess.GetFirstPageDataIDR <DBControl.DBInfo.Tables.SystemRole>(fieldArr.ToString(","), _descOrder, _pageSize, condition); break; case enumSelectType.LastPage: idr = DBControl.Base.DBAccess.GetLastPageDataIDR <DBControl.DBInfo.Tables.SystemRole>(fieldArr.ToString(","), _descOrder, _pageSize, condition); break; case enumSelectType.PrevPage: idr = DBControl.Base.DBAccess.GetPrevPageDataIDR <DBControl.DBInfo.Tables.SystemRole>(fieldArr.ToString(","), _descOrder, _pageSize, _minid, _maxid, condition); break; case enumSelectType.NextPage: idr = DBControl.Base.DBAccess.GetNextPageDataIDR <DBControl.DBInfo.Tables.SystemRole>(fieldArr.ToString(","), _descOrder, _pageSize, _minid, _maxid, condition); break; case enumSelectType.GoToPage: idr = DBControl.Base.DBAccess.GetPageDataIDR <DBControl.DBInfo.Tables.SystemRole>(fieldArr.ToString(","), _descOrder, _pageSize, _page, condition); break; } JsonArray jArray = DataListToJson(idr, tableInfo.PKey, _descOrder, ref _minid, ref _maxid, fieldArr); if (jArray.Count > 0) { jsonData = JsonResult(true, enumReturnTitle.GetData, "数据获取成功。"); jsonData.Add("rowsccount", jArray.Count); if (IsGetTotal) { _total = DBControl.Base.DBAccess.Count <DBControl.DBInfo.Tables.SystemRole>(condition); } jsonData.Add("total", _total); jsonData.Add("minid", _minid); jsonData.Add("maxid", _maxid); jsonData.Add("rows", jArray); } else { jsonData = JsonResult(false, enumReturnTitle.GetData, "没数据。"); } JsonWriter jWriter = new JsonWriter(); jsonData.Write(jWriter); CurrentContext.Response.Write(jWriter.ToString()); } catch (Exception ex) { ReturnMsg(false, enumReturnTitle.GetData, string.Format("获取数据失败:{0}", ex.Message)); } }
private Span JsonObject2Inline(JsonObject jo, string margin = "") { Span span = new Span(); span.Inlines.Add(new Run() { Text = "{", Foreground = color1 }); span.Inlines.Add(new LineBreak()); foreach (string key in jo.Keys) { span.Inlines.Add(new Run() { Text = margin + " " }); span.Inlines.Add(new Run() { Text = key, Foreground = color2 }); span.Inlines.Add(new Run() { Text = ": ", Foreground = color1 }); JsonValue jv = jo.GetNamedValue(key); switch (jv.ValueType) { case JsonValueType.Null: break; case JsonValueType.Boolean: break; case JsonValueType.Number: break; case JsonValueType.String: span.Inlines.Add(new Run() { Text = jv.GetString(), Foreground = color3 }); span.Inlines.Add(new LineBreak()); break; case JsonValueType.Array: break; case JsonValueType.Object: span.Inlines.Add(JsonObject2Inline(jv.GetObject(), margin + " ")); break; default: break; } } span.Inlines.Add(new Run() { Text = margin + "}", Foreground = color1 }); span.Inlines.Add(new LineBreak()); return(span); }
internal static System.Collections.Generic.IDictionary <string, V> FromJson <V>(JsonObject json, System.Collections.Generic.IDictionary <string, V> container, System.Func <JsonObject, V> objectFactory, System.Collections.Generic.HashSet <string> excludes = null) { if (null == json) { return(container); } foreach (var key in json.Keys) { if (true == excludes?.Contains(key)) { continue; } var value = json[key]; try { switch (value.Type) { case JsonType.Null: // skip null values. continue; case JsonType.Array: case JsonType.Boolean: case JsonType.Date: case JsonType.Binary: case JsonType.Number: case JsonType.String: container.Add(key, (V)value.ToValue()); break; case JsonType.Object: if (objectFactory != null) { var v = objectFactory(value as JsonObject); if (null != v) { container.Add(key, v); } } break; } } catch { } } return(container); }
//Send notify, do not need id internal void send(string route, JsonObject msg) { send(route, 0, msg); }
internal static System.Collections.Generic.IDictionary <string, V> FromJson <V>(JsonObject json, System.Collections.Generic.Dictionary <string, V> container, System.Func <JsonObject, V> objectFactory, System.Collections.Generic.HashSet <string> excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary <string, V>)container, objectFactory, excludes);
/// <summary> /// Serializes a dictionary into a JsonObject container. /// </summary> /// <param name="dictionary">The dictionary to serailize</param> /// <param name="container">the container to serialize the dictionary into</param> /// <returns>the container</returns> internal static JsonObject ToJson <T>(System.Collections.Generic.IDictionary <string, T> dictionary, JsonObject container) { container = container ?? new JsonObject(); if (dictionary != null && dictionary.Count > 0) { foreach (var key in dictionary) { // currently, we don't serialize null values. if (null != key.Value) { container.Add(key.Key, ToJsonValue(key.Value)); continue; } } } return(container); }
internal static JsonObject ToJson <T>(System.Collections.Generic.Dictionary <string, T> dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary <string, T>)dictionary, container);
public void notify(string route, JsonObject msg) { protocol.send(route, msg); }
public void connect(JsonObject user) { connect(user, null); }
/// <summary> /// Gets an instance of <var>AnalyticsDataQuery</var> from the specified JSON string. /// </summary> /// <param name="json">The JSON string representation of the object.</param> public static AnalyticsDataQuery ParseJson(string json) { return(JsonObject.ParseJson(json, Parse)); }
private void OkDialogButton_Click(object sender, EventArgs e) { JsonObject request = Requests.CreateBasicObject(ProtocolConstants.METHOD_TORRENTSET); JsonObject arguments = Requests.GetArgObject(request); arguments.Put(ProtocolConstants.KEY_IDS, Toolbox.ListViewSelectionToIdArray(selections)); arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITUPENABLED, uploadLimitEnableField.Checked ? 1 : 0); arguments.Put(ProtocolConstants.FIELD_UPLOADLIMITED, uploadLimitEnableField.Checked ? 1 : 0); arguments.Put(ProtocolConstants.FIELD_UPLOADLIMIT, uploadLimitField.Value); arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITUP, uploadLimitField.Value); arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITDOWNENABLED, downloadLimitEnableField.Checked ? 1 : 0); arguments.Put(ProtocolConstants.FIELD_DOWNLOADLIMITED, downloadLimitEnableField.Checked ? 1 : 0); arguments.Put(ProtocolConstants.FIELD_DOWNLOADLIMIT, downloadLimitField.Value); arguments.Put(ProtocolConstants.FIELD_SPEEDLIMITDOWN, downloadLimitField.Value); arguments.Put(ProtocolConstants.FIELD_PEERLIMIT, peerLimitValue.Value); if (seedRatioLimitValue.Enabled) { arguments.Put(ProtocolConstants.FIELD_SEEDRATIOLIMIT, seedRatioLimitValue.Value); } if (seedIdleLimitValue.Enabled) { arguments.Put(ProtocolConstants.FIELD_SEEDIDLELIMIT, seedIdleLimitValue.Value); } if (honorsSessionLimits.Enabled) { arguments.Put(ProtocolConstants.FIELD_HONORSSESSIONLIMITS, honorsSessionLimits.Checked); } if (seedRatioLimitedCheckBox.Enabled) { arguments.Put(ProtocolConstants.FIELD_SEEDRATIOMODE, (int)(2 - seedRatioLimitedCheckBox.CheckState)); } if (seedIdleLimitedCheckBox.Enabled) { arguments.Put(ProtocolConstants.FIELD_SEEDIDLEMODE, (int)(2 - seedIdleLimitedCheckBox.CheckState)); } if (bandwidthComboBox.Enabled) { int bandwidthPriority = 0; if (bandwidthComboBox.SelectedIndex == 0) { bandwidthPriority = -1; } else if (bandwidthComboBox.SelectedIndex == 2) { bandwidthPriority = 1; } arguments.Put(ProtocolConstants.FIELD_BANDWIDTHPRIORITY, bandwidthPriority); } Torrent firstTorrent = (Torrent)selections[0]; JsonArray trackerRemove = new JsonArray(); foreach (JsonObject tracker in firstTorrent.Trackers) { int id = Toolbox.ToInt(tracker[ProtocolConstants.FIELD_ID]); if (!trackersList.Items.Contains(id)) { trackerRemove.Add(id); } } JsonArray trackerReplace = new JsonArray(); foreach (TrackerListItem t in trackersList.Items) { if (!t.Changed) { continue; } trackerReplace.Add(t.Id); trackerReplace.Add(t.Announce); } JsonArray trackerAdd = new JsonArray(); foreach (TrackerListItem t in trackersList.Items) { if (t.Id == -1) { trackerAdd.Add(t.Announce); } } if (trackerRemove.Count > 0) { arguments.Put(ProtocolConstants.FIELD_TRACKER_REMOVE, trackerRemove); } if (trackerReplace.Count > 0) { arguments.Put(ProtocolConstants.FIELD_TRACKER_REPLACE, trackerReplace); } if (trackerAdd.Count > 0) { arguments.Put(ProtocolConstants.FIELD_TRACKER_ADD, trackerAdd); } Program.Form.SetupAction(CommandFactory.RequestAsync(request)); this.Close(); }
/// <summary> /// Gets a JSON string representing the object. /// </summary> public string ToJson() { return(JsonObject == null ? null : JsonObject.ToJson()); }
private FacebookDebugToken(JsonObject obj) : base(obj) { }
/// <summary> Actually parse </summary> /// <returns> Parsed structure as a <see cref="JsonObject"/> mirroring <see cref="Node"/>, otherwise the <see cref="string"/> of text. </returns> public JsonValue Parse() { string leadingWhitespace = SkipWhitespace(); if (At("<")) { i++; string tagName = ReadName(); if (tagName == "!DOCTYPE" || tagName == "?xml") { while (!At(">")) { i++; } i++; return(Parse()); } JsonObject tag = new JsonObject(); JsonObject attr = new JsonObject(); JsonArray children = new JsonArray(); if (leadingWhitespace.Length > 0) { tag["leadingWhitespace"] = leadingWhitespace; } tag["tag"] = tagName; tag["attr"] = attr; tag["selfClosed"] = false; tag["children"] = children; tag["comment"] = ""; // Log.Info($"Saw tag TagName: {tagName}"); if (tagName.StartsWith("!--")) { tag["comment"] = ReadComment(); return(tag); } SkipWhitespace(); while (!At("/") && !At(">")) { if (eof) { return(tag); } string attrName = ReadName(); SkipWhitespace(); if (!At("=")) { throw new Exception($"Expected '=' after attribute name, had '{cur}'. {lineInfo}\n{nearbyText}"); } i++; SkipWhitespace(); string attrVal = ReadString(); SkipWhitespace(); attr[attrName] = attrVal; } bool selfClosed = At('/'); tag["selfClosed"] = selfClosed; if (selfClosed) { i += 2; return(tag); } i++; string innerWhitespace = SkipWhitespace(); while (!(cur == '<' && next == '/')) { if (eof) { return(tag); } var child = Parse(); if (child.isString) { child = innerWhitespace + child.stringVal; } else if (innerWhitespace.Length > 0) { children.Add(innerWhitespace); } children.Add(child); innerWhitespace = SkipWhitespace(); } i += 2; string endName = ReadName(); if (endName != tagName) { throw new Exception($"Wrong ending tag for '{tagName}', saw '{endName}'. {lineInfo}\n{nearbyText}"); } SkipWhitespace(); if (!At(">")) { throw new Exception($"Expected end angle bracket '>', got '{cur}' {lineInfo}\n{nearbyText}"); } i++; return(tag); } // Not tag, but text: StringBuilder text = new StringBuilder(leadingWhitespace); while (!At("<")) { if (eof) { return(text.ToString()); } text.Append(cur); i++; } return(text.ToString()); }
/// <summary> /// Loads an instance of <var>AnalyticsDataQuery</var> from the JSON file at the specified /// <var>path</var>. /// </summary> /// <param name="path">The path to the file.</param> public static AnalyticsDataQuery LoadJson(string path) { return(JsonObject.LoadJson(path, Parse)); }
public KeyNotFoundException(JsonObject jsonObj, string key) : base(BuildMessage(jsonObj, key)) { this.Object = jsonObj; this.Key = key; }
public static void TestBasic() { string test = @" <test> <!-- THIS IS A COMMENT --> <test2/> <!-- THIS IS A COMMENT --> <test3 a='b' c='d'> <!-- THIS IS A COMMENT --> this is text: x y z w <!-- THIS IS A COMMENT --> </test3> <test4> Some Text <test5 /> Some Text <test5 /> Some Text </test4> <!-- THIS IS A COMMENT --> </test>".Replace('\'', '\"'); JsonObject parsed = XML.Parse(test); //Log.Info(parsed.PrettyPrint()); void check(JsonObject parsed) { parsed.ShouldNotBe(null); parsed["tag"].ShouldEqual("test"); parsed["selfClosed"].ShouldEqual(false); parsed["children"].Count.ShouldBe(12); parsed["attr"].Count.ShouldBe(0); parsed["children"][1]["tag"].ShouldEqual("!--"); parsed["children"][3]["tag"].ShouldEqual("test2"); parsed["children"][3]["selfClosed"].ShouldEqual(true); parsed["children"][5]["tag"].ShouldEqual("!--"); parsed["children"][7]["tag"].ShouldEqual("test3"); parsed["children"][7]["selfClosed"].ShouldEqual(false); parsed["children"][7]["children"].Count.ShouldBe(4); parsed["children"][7]["attr"]["a"].ShouldEqual("b"); parsed["children"][7]["attr"]["c"].ShouldEqual("d"); parsed["children"][9]["tag"].ShouldEqual("test4"); parsed["children"][9]["children"].Count.ShouldBe(5); parsed["children"][9]["children"][1]["tag"].ShouldEqual("test5"); parsed["children"][9]["children"][1]["selfClosed"].ShouldEqual(true); parsed["children"][9]["children"][3]["tag"].ShouldEqual("test5"); parsed["children"][9]["children"][3]["selfClosed"].ShouldEqual(true); } check(parsed); string toStringd = XML.ToXML(parsed); // Can't guarantee that the generated XML looks anything like what was originally parsed // but we can guarantee there's a similar structure and certain contents. JsonObject backToXML = XML.Parse(toStringd); check(backToXML); }
private static void SendDgramMsg(string strFilePath, string strMachineID, Socket socket) { //数据包 _TAG_NETPACK_DISTINGUISHHEAD_VER1 pack = new _TAG_NETPACK_DISTINGUISHHEAD_VER1(); //基本包头 NETPACK_BASEHEAD_APPLICATION_VER1 baseHeadPack = new NETPACK_BASEHEAD_APPLICATION_VER1(); baseHeadPack._encrypt = DecDefine.NETPACK_ENCRYPT_NOTHING; baseHeadPack._format = DecDefine.NETPACK_BASEHEAD_VER1_FORMAT_JSON; JsonObject json = new JsonObject(); json["MachineID"] = new JsonProperty("\"" + strMachineID + "\""); json["ChangeID"] = new JsonProperty("\"" + System.DateTime.Now.Year.ToString() + string.Format("{0:00}", System.DateTime.Now.Month) + string.Format("{0:00}", System.DateTime.Now.Day) + string.Format("{0:00}", System.DateTime.Now.Hour) + string.Format("{0:00}", System.DateTime.Now.Minute) + string.Format("{0:00}", System.DateTime.Now.Second) + string.Format("{0:000}", System.DateTime.Now.Millisecond) + "\""); JsonObject jsonParam = new JsonObject(); jsonParam["ParamChange"] = new JsonProperty(json); baseHeadPack._validsize = (short)jsonParam.ToString().Length; baseHeadPack._datasize = (short)jsonParam.ToString().Length; byte[] byteData = Encoding.ASCII.GetBytes(jsonParam.ToString()); // string str = Encoding.ASCII.GetString(byteData); // UMPService00.IEventLog.WriteEntry("send message = "+str, EventLogEntryType.Warning); _TAG_NETPACK_ENCRYPT_CONTEXT encrypt = new _TAG_NETPACK_ENCRYPT_CONTEXT(); encrypt._encrypt = DecDefine.NETPACK_ENCRYPT_NOTHING; //识别头 _TAG_NETPACK_DISTINGUISHHEAD disHead = new _TAG_NETPACK_DISTINGUISHHEAD(); byte[] byteHeadPack = Common.StructToBytes(baseHeadPack); byte[] byteFollowData = new byte[byteHeadPack.Length + byteData.Length]; Array.Copy(byteHeadPack, byteFollowData, byteHeadPack.Length); Array.Copy(byteData, 0, byteFollowData, byteHeadPack.Length, byteData.Length); _TAG_NETPACK_MESSAGE message = Common.CreateMessage(0xffff, 0xffff, 0xffff, 0xffff, DecDefine.NETMSG_SMALLTYPE_COMMON_PARAM_NOTIFY, DecDefine.NETMSG_MIDTYPE_COMMON_PARAM, DecDefine.NETMSG_LARGTYPE_COMMON, DecDefine.NETMSG_NUMBER_COMMON_PARAM_NOTIFY_CHANGE); _TAG_NETPACK_DISTINGUISHHEAD_VER1 ReleasePack = Common.CreatePack(DecDefine.NETPACK_DISTHEAD_VER1, disHead, DecDefine.NETPACK_BASETYPE_APPLICATION_VER1, DecDefine.NETPACK_EXTTYPE_NOTHING, encrypt, (ushort)byteData.Length, message, 0xffff, 0xffff, DecDefine.NETPACK_PACKTYPE_APPLICATION, 0, 0, 0, -1); bool bIsSend = false; //UMPService00.IEventLog.WriteEntry("_TAG_NETPACK_DISTINGUISHHEAD_VER1 size = " + Marshal.SizeOf(typeof(_TAG_NETPACK_DISTINGUISHHEAD_VER1)) // +"mes length = "+byteFollowData.Length.ToString(), EventLogEntryType.Warning); for (int i = 0; i <= 3; i++) { if (bIsSend) { break; } try { SendMsg(ReleasePack, byteFollowData, socket); bIsSend = true; socket.Close(); } catch { bIsSend = false; Thread.Sleep(2 * 1000); } } }
private static string BuildMessage(JsonObject jsonObj, string key) { return(String.Format( "Cannot find the required key '{0}' in {1} ", key, jsonObj)); }
private byte[] ExportCsvHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { string retval = ""; StringBuilder sb = new StringBuilder(); string s = ""; bool applyQuery = true; bool? applyHeader = true; //bool? applyGeoms = true; bool addHeader = false; //bool addGeoms = false; responseProperties = "{\"Content-Type\" : \"text/csv\"}"; string whereClause = ""; bool found = operationInput.TryGetString("query", out whereClause); if (!found || string.IsNullOrEmpty(whereClause)) { //then no definition query applyQuery = false; } long?layerOrdinal; found = operationInput.TryGetAsLong("layer", out layerOrdinal); //.TryGetString("layer", out parm2Value); if (!found) { throw new ArgumentNullException("layer"); } bool useHeader = operationInput.TryGetAsBoolean("headers", out applyHeader); if (useHeader) { if ((bool)applyHeader) { addHeader = true; } } //bool useGeoms = operationInput.TryGetAsBoolean("addgeoms", out applyGeoms); //if (useGeoms) //{ // if ((bool)applyGeoms) // { // addGeoms = true; // } //} ESRI.ArcGIS.Carto.IMapServer mapServer = (ESRI.ArcGIS.Carto.IMapServer)serverObjectHelper.ServerObject; ESRI.ArcGIS.Carto.IMapServerDataAccess mapServerObjects = (ESRI.ArcGIS.Carto.IMapServerDataAccess)mapServer; var lyr = mapServerObjects.GetDataSource(mapServer.DefaultMapName, Convert.ToInt32(layerOrdinal)); if (lyr is IFeatureClass) { IFeatureClass fclass = (IFeatureClass)lyr; IQueryFilter filter = new QueryFilterClass(); filter.set_OutputSpatialReference(fclass.ShapeFieldName, getWGS84()); if (applyQuery) { filter.WhereClause = whereClause; } IFeatureCursor curs = fclass.Search(filter, false); try { //(); s = curs.ToCSV(addHeader); Marshal.ReleaseComObject(curs); } catch (Exception ex) { s = ex.GetBaseException().ToString(); //.StackTrace; } retval = s; sb.Append(retval); } else { throw new Exception("Layer " + layerOrdinal.ToString() + " is not a feature layer."); } return(Encoding.UTF8.GetBytes(sb.ToString())); }
private async Task GetDataAsync(string userid, bool loadMore) { Answer answer = null; if (loadMore) { if (FeedDataSource.next_url != string.Empty) { answer = await new Client().GetAnswerAsync(FeedDataSource.next_url); } } else { AuthData authData = await DataStorage.GetAuthData(); if (userid.Equals(string.Empty)) { //answer = await new Client().GetAnswerAsync("https://api.instagram.com/v1/users/5946413/media/recent/?access_token=5946413.f59def8.7601270936b741c5a90161431a5df01f"); answer = await new Client().GetAnswerAsync("https://api.instagram.com/v1/users/self/feed?access_token=" + authData.Token); } else { answer = await new Client().GetAnswerAsync("https://api.instagram.com/v1/users/" + userid + "/media/recent/?access_token=" + authData.Token); } } if (answer.Status == ResponseStatus.Success) { JsonObject jsonObject = JsonObject.Parse(answer.Content); JsonArray jsonArray = jsonObject["data"].GetArray(); if (jsonObject.ContainsKey("pagination")) { FeedDataSource.next_url = GetNextUrl(jsonObject["pagination"].GetObject()); } int counter = 0; foreach (JsonValue feedItem in jsonArray) { var itemObject = feedItem.GetObject(); var tags = GetTags(itemObject["tags"].GetArray()); //Tags tags = null; var Type = GetType(itemObject["type"].GetString()); //MediaType Type = MediaType.Image; var location = GetLocation(itemObject["location"]); //Location location = null; var comments = GetComments(itemObject["comments"].GetObject()); //Comments comments = null; var filter = itemObject["filter"].GetString(); //string filter = string.Empty; var createdTime = itemObject["created_time"].GetString(); //string createdTime = string.Empty; var link = itemObject["link"].GetString(); //string link = string.Empty; var likes = GetLikes(itemObject["likes"].GetObject()); //Likes likes = null; var images = GetImages(itemObject["images"].GetObject()); //Images images = null; var usersInPhoto = GetUsersInPhoto(itemObject["users_in_photo"].GetArray()); //UsersInPhoto usersInPhoto = null; var caption = GetCaption(itemObject["caption"]); //Caption caption = null; var userhasLiked = itemObject["user_has_liked"].GetBoolean(); //bool userhasLiked = false; var id = itemObject["id"].GetString(); //string id = string.Empty; var user = GetUser(itemObject["user"].GetObject()); //User user = null; FeedItem item = null; if (Type == MediaType.Video) { var videos = GetVideos(itemObject["videos"].GetObject()); item = new FeedItem(null, tags, Type, location, comments, filter, createdTime, link, likes, images, usersInPhoto, caption, userhasLiked, id, user, videos); } else { item = new FeedItem(null, tags, Type, location, comments, filter, createdTime, link, likes, images, usersInPhoto, caption, userhasLiked, id, user); } this.Feed.Add(item); } } else if (answer.Status == ResponseStatus.ConnectionError) { await new Windows.UI.Popups.MessageDialog("Check your internet connection", "Connection problem").ShowAsync(); } else if (answer.Status == ResponseStatus.InvalidToken) { await new Windows.UI.Popups.MessageDialog("Pass authorization once again to update token", "Invalid Token").ShowAsync(); } }
void LoadPlayerDataFromJson(string jsonData) { data = JsonObject.Deserialise <PlayerData>(jsonData); }
private byte[] ExportGeoJsonHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"application/json\"}";; bool applyQuery = true; bool useBbox = true; bool useBboxSR = true; string retval = ""; string whereClause; string boxClause; int bboxSRID = 0; IPolygon queryGeom = null; Helpers helper = new Helpers(); bool found = operationInput.TryGetString("query", out whereClause); if (!found || string.IsNullOrEmpty(whereClause)) { //then no definition query applyQuery = false; } string ssrid; found = operationInput.TryGetString("bboxSR", out ssrid); if (!found || string.IsNullOrEmpty(ssrid)) { //then no definition query useBboxSR = false; } else { int srid; bool valid = int.TryParse(ssrid, out srid); if (valid) { bboxSRID = srid; } else { useBboxSR = false; } } found = operationInput.TryGetString("bbox", out boxClause); if (!found || string.IsNullOrEmpty(boxClause)) { //then no definition query useBbox = false; } if (useBbox) { try { double xmin; double ymin; double xmax; double ymax; string[] vals = boxClause.Split(new char[] { ',' }); if (vals.Length == 4) { bool bxmin = double.TryParse(vals[0], out xmin); bool bymin = double.TryParse(vals[1], out ymin); bool bxmax = double.TryParse(vals[2], out xmax); bool bymax = double.TryParse(vals[3], out ymax); if (bxmin && bymin && bxmax && bymax) { ISpatialReference sr = null; if (useBboxSR) { sr = helper.GetSpatialReference(bboxSRID); if (sr == null) { //erroneous srid, ignore bounding box useBbox = false; } } else { sr = helper.getWGS84(); } if (useBbox) { queryGeom = new Polygon() as IPolygon; IPointCollection coll = queryGeom as IPointCollection; coll.AddPoint(new Point() { X = xmin, Y = ymin, SpatialReference = sr }); coll.AddPoint(new Point() { X = xmin, Y = ymax, SpatialReference = sr }); coll.AddPoint(new Point() { X = xmax, Y = ymax, SpatialReference = sr }); coll.AddPoint(new Point() { X = xmax, Y = ymin, SpatialReference = sr }); coll.AddPoint(new Point() { X = xmin, Y = ymin, SpatialReference = sr }); queryGeom.SpatialReference = sr; } } else { useBbox = false; } } else { useBbox = false; } } catch { useBbox = false; } } long?layerOrdinal; found = operationInput.TryGetAsLong("layer", out layerOrdinal); //.TryGetString("layer", out parm2Value); if (!found) { throw new ArgumentNullException("layer"); } string s = ""; ESRI.ArcGIS.Carto.IMapServer mapServer = (ESRI.ArcGIS.Carto.IMapServer)serverObjectHelper.ServerObject; ESRI.ArcGIS.Carto.IMapServerDataAccess mapServerObjects = (ESRI.ArcGIS.Carto.IMapServerDataAccess)mapServer; var lyr = mapServerObjects.GetDataSource(mapServer.DefaultMapName, Convert.ToInt32(layerOrdinal)); if (lyr is IFeatureClass) { IFeatureClass fclass = (IFeatureClass)lyr; retval = "{\"shape\": \"" + fclass.ShapeFieldName + "\"}"; IQueryFilter filter = null; if (useBbox) { IGeoDataset gds = fclass as IGeoDataset; filter = new SpatialFilterClass(); ISpatialFilter spf = filter as ISpatialFilter; spf.Geometry = helper.TransformShapeCS(queryGeom, queryGeom.SpatialReference, gds.SpatialReference); spf.GeometryField = fclass.ShapeFieldName; spf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; } else { filter = new QueryFilterClass(); } filter.set_OutputSpatialReference(fclass.ShapeFieldName, getWGS84()); if (applyQuery) { filter.WhereClause = whereClause; } IFeatureCursor curs = fclass.Search(filter, false); //apply extension methods here try { s = curs.ToGeoJson(); Marshal.ReleaseComObject(curs); } catch (Exception ex) { s = ex.GetBaseException().ToString(); //.StackTrace; } retval = s; } else { throw new Exception("Layer " + layerOrdinal.ToString() + " is not a feature layer."); } return(Encoding.UTF8.GetBytes(retval)); }
public async static Task WriteToFolder(Book b, StorageFolder folder) { // todo: Fix for internet defects + optimize async functions JsonObject obj = new JsonObject(); StorageFile imageFile = await folder.CreateFileAsync("image.jpg", CreationCollisionOption.OpenIfExists); if (b.LargeImageUri != new Uri("ms-appx:/Assets/avatar_book-sm.png")) { HttpClient client = new HttpClient(); HttpResponseMessage response = new HttpResponseMessage(); response = await client.GetAsync(b.LargeImageUri); response.EnsureSuccessStatusCode(); // todo: Monkey Coding Style. Fix this shit. if (response.Headers.ContainsKey("Location")) { response = await client.GetAsync(new Uri(response.Headers["Location"])); response.EnsureSuccessStatusCode(); } var responseBody = await response.Content.ReadAsBufferAsync(); await FileIO.WriteBufferAsync(imageFile, responseBody); obj["cover_local"] = JsonValue.CreateStringValue(imageFile.Path); } else { obj["cover_local"] = JsonValue.CreateStringValue("ms-appx:/Assets/avatar_book-sm.png"); } obj["key"] = JsonValue.CreateStringValue(b.Key); obj["title_suggest"] = JsonValue.CreateStringValue(b.Title); // Forming Authors { JsonArray authors = new JsonArray(); foreach (var author in b.Authors) { authors.Add(JsonValue.CreateStringValue(author)); } obj["author_name"] = authors; } // Forming Subjects { JsonArray subjects = new JsonArray(); foreach (var subject in b.Subjects) { subjects.Add(JsonValue.CreateStringValue(subject)); } obj["subject"] = subjects; } // Sentence { JsonArray firstArray = new JsonArray(); foreach (var sentence in b.FirstSentences) { firstArray.Add(JsonValue.CreateStringValue(sentence)); } obj["first_sentence"] = firstArray; } StorageFile file = await folder.CreateFileAsync("data.json", CreationCollisionOption.OpenIfExists); await FileIO.WriteTextAsync(file, obj.ToString()); }
private async Task <bool> GetMediaDataAsync(string path) { if (this._groups.Count != 0) { return(false); } string jsonText = string.Empty; if (string.IsNullOrEmpty(path)) { // load the default data //If retrieving json from web failed then use embedded json data file. if (string.IsNullOrEmpty(jsonText)) { Uri dataUri = new Uri("ms-appx:///DataModel/MediaData.json"); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = "ms-appx:///DataModel/MediaData.json"; } } else { if (path.StartsWith("ms-appx://")) { Uri dataUri = new Uri(path); StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri); jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = path; } else if (path.StartsWith("http://") || path.StartsWith("https://")) { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file string MediaDataFile = path; Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent; Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(filter); Uri httpUri = new Uri(MediaDataFile); jsonText = await http.GetStringAsync(httpUri); MediaDataPath = MediaDataFile; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } else { try { //Download the json file from the server to configure what content will be dislayed. //You can also modify the local MediaData.json file and delete this code block to test //the local json file string MediaDataFile = path; StorageFile file; file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path); if (file != null) { jsonText = await FileIO.ReadTextAsync(file); MediaDataPath = MediaDataFile; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } } } if (string.IsNullOrEmpty(jsonText)) { return(false); } try { JsonObject jsonObject = JsonObject.Parse(jsonText); JsonArray jsonArray = jsonObject["Groups"].GetArray(); foreach (JsonValue groupValue in jsonArray) { JsonObject groupObject = groupValue.GetObject(); MediaDataGroup group = new MediaDataGroup(groupObject["UniqueId"].GetString(), groupObject["Title"].GetString(), groupObject["Category"].GetString(), groupObject["ImagePath"].GetString(), groupObject["Description"].GetString()); foreach (JsonValue itemValue in groupObject["Items"].GetArray()) { JsonObject itemObject = itemValue.GetObject(); long timeValue = 0; group.Items.Add(new MediaItem(itemObject["UniqueId"].GetString(), itemObject["Comment"].GetString(), itemObject["Title"].GetString(), itemObject["ImagePath"].GetString(), itemObject["Description"].GetString(), itemObject["Content"].GetString(), itemObject["PosterContent"].GetString(), (long.TryParse(itemObject["Start"].GetString(), out timeValue) ? timeValue : 0), (long.TryParse(itemObject["Duration"].GetString(), out timeValue) ? timeValue : 0), (itemObject.ContainsKey("HttpHeaders") ? itemObject["HttpHeaders"].GetString() : ""), itemObject["PlayReadyUrl"].GetString(), itemObject["PlayReadyCustomData"].GetString(), itemObject["BackgroundAudio"].GetBoolean())); } this.Groups.Add(group); return(true); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message); } return(false); }
/// <summary> /// Converts an object to a <see cref="JsonValue"/>. /// </summary> /// <param name="serializer">The <see cref="JsonSerializer"/> instance to use for additional serialization of values.</param> /// <returns>The <see cref="JsonValue"/> representation of the object.</returns> public virtual JsonValue ToJson(JsonSerializer serializer) { if (BooleanSchemaDefinition != null) { return(BooleanSchemaDefinition); } serializer = serializer ?? _schemaSerializer; var json = new JsonObject(); if (!string.IsNullOrWhiteSpace(Schema)) { json["$schema"] = Schema; } if (Id != null) { json["$id"] = Id; } if (Comment != null) { json["$comment"] = Comment; } if (Title != null) { json["title"] = Title; } if (!string.IsNullOrWhiteSpace(Description)) { json["description"] = Description; } if (Definitions != null) { json["definitions"] = Definitions.ToJson(serializer); } if (ReadOnly.HasValue) { json["readOnly"] = ReadOnly; } if (Type != JsonSchemaType.NotDefined) { var array = Type.ToJson(); if (array.Type == JsonValueType.Array) { array.Array.EqualityStandard = ArrayEquality.ContentsEqual; } json["type"] = array; } if (Properties != null) { json["properties"] = Properties.ToJson(serializer); } if (Maximum.HasValue) { json["maximum"] = Maximum; } if (ExclusiveMaximum.HasValue) { json["exclusiveMaximum"] = ExclusiveMaximum; } if (Minimum.HasValue) { json["minimum"] = Minimum; } if (ExclusiveMinimum.HasValue) { json["exclusiveMinimum"] = ExclusiveMinimum; } if (MultipleOf.HasValue) { json["multipleOf"] = MultipleOf; } if (MaxLength.HasValue) { json["maxLength"] = MaxLength; } if (MinLength.HasValue) { json["minLength"] = MinLength; } if (Pattern != null) { json["pattern"] = Pattern; } if (AdditionalItems != null) { json["additionalItems"] = AdditionalItems.ToJson(serializer); } if (Items != null) { json["items"] = Items.ToJson(serializer); } if (MaxItems.HasValue) { json["maxItems"] = MinItems; } if (MinItems.HasValue) { json["minItems"] = MinItems; } if (UniqueItems ?? false) { json["uniqueItems"] = UniqueItems; } if (Contains != null) { json["contains"] = Contains.ToJson(serializer); } if (MaxProperties.HasValue) { json["maxProperties"] = MaxProperties; } if (MinProperties.HasValue) { json["minProperties"] = MinProperties; } if (Required != null) { json["required"] = Required.ToJson(); } if (AdditionalProperties != null) { json["additionalProperties"] = AdditionalProperties.ToJson(serializer); } if (PatternProperties != null && PatternProperties.Any()) { json["patternProperties"] = PatternProperties.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value).ToJson(serializer); } if (Dependencies != null && Dependencies.Any()) { var jsonDependencies = new JsonObject(); foreach (var dependency in Dependencies) { jsonDependencies[dependency.PropertyName] = dependency.GetJsonData(); } json["dependencies"] = jsonDependencies; } if (PropertyNames != null) { json["propertyNames"] = PropertyNames.ToJson(serializer); } if (Const != null) { json["const"] = Const; } if (Enum != null) { var array = Enum.ToJson(serializer); array.Array.EqualityStandard = ArrayEquality.ContentsEqual; json["enum"] = Enum.ToJson(serializer); } if (Format != null) { json["format"] = Format.Key; } if (ContentMediaType != null) { json["contentMediaType"] = ContentMediaType; } if (ContentEncoding != null) { json["contentEncoding"] = serializer.Serialize(ContentEncoding); } if (If != null) { json["if"] = If.ToJson(serializer); } if (Then != null) { json["then"] = Then.ToJson(serializer); } if (Else != null) { json["else"] = Else.ToJson(serializer); } if (AllOf != null) { var array = AllOf.Select(s => s.ToJson(serializer)).ToJson(); array.EqualityStandard = ArrayEquality.ContentsEqual; json["allOf"] = array; } if (AnyOf != null) { var array = AnyOf.Select(s => s.ToJson(serializer)).ToJson(); array.EqualityStandard = ArrayEquality.ContentsEqual; json["anyOf"] = array; } if (OneOf != null) { var array = OneOf.Select(s => s.ToJson(serializer)).ToJson(); array.EqualityStandard = ArrayEquality.ContentsEqual; json["oneOf"] = array; } if (Not != null) { json["not"] = Not.ToJson(serializer); } if (Default != null) { json["default"] = Default; } if (Examples != null) { json["examples"] = Examples; } if (ExtraneousDetails != null) { foreach (var kvp in ExtraneousDetails.Where(kvp => !_definedProperties.Contains(kvp.Key))) { json[kvp.Key] = kvp.Value; } } return(json); }
public void request(string route, JsonObject msg, Action <JsonObject> action) { protocol.send(route, reqId, msg); reqId++; }
/// <summary> /// 保存数据字典数据 /// </summary> /// <returns></returns> public ActionResult Save(Model.JD_SITE model) { JsonObject json = new JsonObject(); StringBuilder sbErro = new StringBuilder(); if (string.IsNullOrEmpty(model.部门)) { sbErro.Append(",部门不能为空"); } else { Model.Department modelParmExist = new BLL.Department().GetModel(model.部门); if (modelParmExist == null) { sbErro.Append(",部门不存在"); } } if (string.IsNullOrEmpty(model.类别)) { sbErro.Append(",类别不能为空"); } else if (model.类别 != "自持" && model.类别 != "销售") { sbErro.Append(",类别必须是自持或销售"); } if (string.IsNullOrEmpty(model.区域)) { sbErro.Append(",区域不能为空"); } else { Model.Area modelParmExist = new BLL.Area().GetModel(model.区域); if (modelParmExist == null) { sbErro.Append(",区域不存在"); } } if (string.IsNullOrEmpty(model.客户)) { sbErro.Append(",客户不能为空"); } else { Model.Customer modelParmExist = new BLL.Customer().GetModel(model.客户); if (modelParmExist == null) { sbErro.Append(",客户不存在"); } } if (string.IsNullOrEmpty(model.站点编码)) { sbErro.Append(",站点编码不能为空"); } if (string.IsNullOrEmpty(model.站点名称)) { sbErro.Append(",站点名称不能为空"); } if (!string.IsNullOrEmpty(model.站点类型归属)) { int existsCount = new BLL.Common_Data().GetRecordCount("DataType='站点类型归属' and DataValue='" + model.站点类型归属 + "'"); if (existsCount == 0) { sbErro.Append(",站点类型归属不存在"); } } else { sbErro.Append(",站点类型归属不能为空"); } if (!string.IsNullOrEmpty(model.最新状态)) { int existsCount = new BLL.Common_Data().GetRecordCount("DataType='最新状态' and DataValue='" + model.最新状态 + "'"); if (existsCount == 0) { sbErro.Append(",最新状态不存在"); } } else { sbErro.Append(",最新状态不能为空"); } if (string.IsNullOrEmpty(model.是否退点)) { if (model.是否退点 != "是" && model.类别 != "否") { sbErro.Append(",是否退点是是或否"); } } if (sbErro.Length > 0) { json.Status = JsonObject.STATUS_FAIL; json.ErroMessage = sbErro.ToString().Substring(1); return(Json(json)); } //如果ID为空,则是添加 if (string.IsNullOrEmpty(model.id)) { List <Model.JD_SITE> modelExistsList = BLL.GetModelList("站点编码='" + model.站点编码 + "'"); if (modelExistsList != null && modelExistsList.Count > 0) { json.Status = JsonObject.STATUS_FAIL; json.ErroMessage = "添加失败,此数据已存在"; return(Json(json)); } model.CreateTime = DateTime.Now; model.CreateBy = CurrentUser.User.Userinfo.UserID; model.id = Guid.NewGuid().ToString(); bool res = BLL.Add(model); if (res) { json.Status = JsonObject.STATUS_SUCCESS; json.Message = "添加成功"; return(Json(json)); } else { json.Status = JsonObject.STATUS_FAIL; json.ErroMessage = "添加失败"; return(Json(json)); } } else { List <Model.JD_SITE> modelExistsList = BLL.GetModelList("站点编码='" + model.站点编码 + "' and id!='" + model.id + "'"); if (modelExistsList != null && modelExistsList.Count > 0) { json.Status = JsonObject.STATUS_FAIL; json.ErroMessage = "修改失败,此数据已存在"; return(Json(json)); } Model.JD_SITE modelOld = BLL.GetModel(model.id); if (modelOld == null) { json.Status = JsonObject.STATUS_FAIL; json.ErroMessage = "数据不存在"; return(Json(json)); } model.CreateBy = modelOld.CreateBy; model.CreateTime = modelOld.CreateTime; model.UpdateTime = DateTime.Now; model.UpdateBy = CurrentUser.User.Userinfo.UserID; bool res = BLL.Update(model); if (res) { json.Status = JsonObject.STATUS_SUCCESS; json.Message = "修改成功"; return(Json(json)); } else { json.Status = JsonObject.STATUS_FAIL; json.ErroMessage = "修改失败"; return(Json(json)); } } }
public void PreAuthenticate(IRequest req, IResponse res) { if (req.OperationName != null && IgnoreForOperationTypes.Contains(req.OperationName)) { return; } var bearerToken = req.GetBearerToken() ?? req.GetCookieValue(Keywords.TokenCookie); if (bearerToken != null) { var parts = bearerToken.Split('.'); if (parts.Length == 3) { if (RequireSecureConnection && !req.IsSecureConnection) { throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection); } var header = parts[0]; var payload = parts[1]; var signatureBytes = parts[2].FromBase64UrlSafe(); var headerJson = header.FromBase64UrlSafe().FromUtf8Bytes(); var payloadBytes = payload.FromBase64UrlSafe(); var headerData = headerJson.FromJson <Dictionary <string, string> >(); var bytesToSign = string.Concat(header, ".", payload).ToUtf8Bytes(); var algorithm = headerData["alg"]; //Potential Security Risk for relying on user-specified algorithm: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ if (RequireHashAlgorithm && algorithm != HashAlgorithm) { throw new NotSupportedException("Invalid algoritm '{0}', expected '{1}'".Fmt(algorithm, HashAlgorithm)); } if (!VerifyPayload(algorithm, bytesToSign, signatureBytes)) { return; } var payloadJson = payloadBytes.FromUtf8Bytes(); var jwtPayload = JsonObject.Parse(payloadJson); var session = CreateSessionFromPayload(req, jwtPayload); req.Items[Keywords.Session] = session; } else if (parts.Length == 5) //Encrypted JWE Token { if (RequireSecureConnection && !req.IsSecureConnection) { throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection); } if (PrivateKey == null || PublicKey == null) { throw new NotSupportedException("PrivateKey is required to DecryptPayload"); } var jweHeaderBase64Url = parts[0]; var jweEncKeyBase64Url = parts[1]; var ivBase64Url = parts[2]; var cipherTextBase64Url = parts[3]; var tagBase64Url = parts[4]; var sentTag = tagBase64Url.FromBase64UrlSafe(); var aadBytes = (jweHeaderBase64Url + "." + jweEncKeyBase64Url).ToUtf8Bytes(); var iv = ivBase64Url.FromBase64UrlSafe(); var cipherText = cipherTextBase64Url.FromBase64UrlSafe(); var jweEncKey = jweEncKeyBase64Url.FromBase64UrlSafe(); var cryptAuthKeys256 = RsaUtils.Decrypt(jweEncKey, PrivateKey.Value, UseRsaKeyLength); var authKey = new byte[128 / 8]; var cryptKey = new byte[128 / 8]; Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length); Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length); using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var writer = new BinaryWriter(encryptedStream)) { writer.Write(aadBytes); writer.Write(iv); writer.Write(cipherText); writer.Flush(); var calcTag = hmac.ComputeHash(encryptedStream.ToArray()); if (!calcTag.EquivalentTo(sentTag)) { return; } } } JsonObject jwtPayload; using (var aes = new AesManaged { KeySize = 128, BlockSize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) using (var decryptor = aes.CreateDecryptor(cryptKey, iv)) using (var ms = MemoryStreamFactory.GetStream(cipherText)) using (var cryptStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { var jwtPayloadBytes = cryptStream.ReadFully(); jwtPayload = JsonObject.Parse(jwtPayloadBytes.FromUtf8Bytes()); } var session = CreateSessionFromPayload(req, jwtPayload); req.Items[Keywords.Session] = session; } } }
public static void Run() { dynamic flickr = new RestClient(Services.FlickrUri, RestService.Json); flickr.apiKey = Services.FlickrApiKey; Console.WriteLine("Searching photos tagged with 'seattle'..."); dynamic photosOptions = new JsonObject(); photosOptions.tags = "seattle"; photosOptions.per_page = 4; dynamic search = flickr.Photos.Search(photosOptions); WritePhotos(search.Result); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Searching interesting photos..."); dynamic interestingnessOptions = new JsonObject(); interestingnessOptions.per_page = 4; dynamic listing = flickr.Interestingness.GetList(interestingnessOptions); WritePhotos(listing.Result); }
public void ShouldTreatNullAndDefaultValueAsEqual() { var jsonObject = new JsonObject(); var defaultInstance = jsonObject.ValueOrDefault("bf2360599bb84e57a2f465f2aa7f5a1b"); Assert.True(comparier.Equals(null, defaultInstance)); Assert.True(comparier.Equals(defaultInstance, null)); }