private string GetJson(ParameterInfo[] parameterInfos, object[] paras) { var paraDic = new Dictionary <string, object>(); for (int i = 0; i < paras.Length; i++) { var para = paras[i]; var paraType = para.GetType(); var paraInfo = parameterInfos[i]; if (paraType.IsValueTypeOrString()) { paraDic.Add(paraInfo.Name, para.ToStringValueType()); } else { var paraPairs = ObjectUtil.ExecuteObj(para); foreach (var paraPair in paraPairs) { paraDic[paraPair.Key] = paraPair.Value; } } } return(paraDic.ToJsonString("{}")); }
private void btSave_Click(object sender, EventArgs e) { foreach (var item in userControlInstrumentSettings) { var data = item.Value.GetData(); foreach (var d in data) { MeasurementController.Configs[item.Key][d.Key] = d.Value; } } var op = MeasurementController.Configs[MeasurementController.InstrumentType.PointOpticalSource]; op["Instrument_WaitTime"] = nudWaitTime.Value.ToString(); var wls = tbWLSetting.Text.Split(",").Select(q => q.CastTo(double.MinValue)).ToList(); if (wls.Count < 1 || wls.Any(q => q == double.MinValue)) { AppFramework.Context.ShowError("波长设置错误"); return; } var wlSetting = new Dictionary <double, int[]>(); for (int i = 0; i < wls.Count; i++) { wlSetting[wls[i]] = new int[] { 1, i + 1 }; } op["Instrument_WaveLengthSetting"] = wlSetting.ToJsonString(); AppFramework.Context.ShowAlert("保存成功设置"); this.Close(); }
/// <summary> /// Post /// </summary> /// <param name="url">请求地址</param> /// <param name="data">请求参数</param> /// <returns></returns> public static string Post(string url, Dictionary <string, object> data, Dictionary <string, string> headerParams, string contentType) { string strData = string.Empty; strData = data.ToJsonString(); return(Execute(url, strData, HTTP_TYPE.POST, headerParams, contentType)); }
public void InitPlayers() { var aps = this.GetAllPlayers(); Dictionary <int, int> playerPosDic = new Dictionary <int, int>(); var poses = new TNet.List <int>(); foreach (var m in _cellStyleDic) { var style = (MapStyle)m.Value; if (style == MapStyle.CANYON || style == MapStyle.HILL) { continue; } poses.Add(m.Key); } foreach (var p in aps) { var idx = Random.Range(0, poses.Count); playerPosDic.Add(p.id, poses[idx]); poses.Remove(idx); } tno.Send("RFC_SyncPlayersPosInfoAndCreatePlayer", Target.All, playerPosDic.ToJsonString()); }
/// <summary> /// 从实体类型中获取实体信息集合 /// </summary> /// <param name="entityTypes">实体类型集合</param> /// <returns>实体信息集合</returns> protected virtual TEntityInfo[] GetEntityInfos(Type[] entityTypes) { List <TEntityInfo> entityInfos = new List <TEntityInfo>(); foreach (Type type in entityTypes.OrderBy(m => m.FullName)) { string fullName = type.FullName; if (entityInfos.Exists(m => m.ClassName == fullName)) { continue; } TEntityInfo entityInfo = new TEntityInfo() { ClassName = fullName, Name = type.ToDescription(), DataLogEnabled = true }; IDictionary <string, string> propertyDict = new Dictionary <string, string>(); PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo property in properties) { propertyDict.Add(property.Name, property.ToDescription()); } entityInfo.PropertyNamesJson = propertyDict.ToJsonString(); entityInfos.Add(entityInfo); } return(entityInfos.ToArray()); }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(); if (user == null) { return(NotFound("用户不存在!")); } Logger.LogInformation("获取{UserName}的私有数据!", user.UserName); // Only include personal data for download var personalData = new Dictionary <string, string>(); var personalDataProps = typeof(User).GetProperties().Where( prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute))); foreach (var p in personalDataProps) { personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null"); } var logins = await _userManager.GetLoginsAsync(user); foreach (var login in logins) { personalData.Add($"{login.LoginProvider} 登录密钥", login.ProviderKey); } personalData.Add("验证密钥", await _userManager.GetAuthenticatorKeyAsync(user)); Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json"); return(new FileContentResult(Encoding.UTF8.GetBytes(personalData.ToJsonString()), "text/json")); }
static void Main(string[] args) { //var result = HttpHelper.HttpGet<string>("http://api.elvbus.com/api/Login/MemUserLoginByWeiXin?openId=oaxHIvwXc2xN-lcS9Uw3lqFqW1LA"); // result = HttpHelper.HttpPost<string>("http://api.elvbus.com/api/BacGrabOrder/GetVehiclePricing",new Dictionary<string, string>()); //CacheHelper.Init(CacheTypeEnum.Redis, null); //CacheHelper.Instance.Add("ss", "wshi"); //var a = CacheHelper.Instance.Get<string>("ss"); //return; //DateTime? now = DateTime.Now; //string ss = now.ToStr() + "{0}"; //Stopwatch ws = new Stopwatch(); //ws.Start(); //for (int i = 0; i < 100; i++) //{ // LogHelper.Instance.Error(ss, "tinghao"); //} //ws.Stop(); //LogHelper.Instance.Info("总耗时:{0}", ws.ElapsedMilliseconds); XmlDocument DOC = new XmlDocument(); DOC.Load("test.xml"); string sss = DOC.ToXmlString(); Dictionary <string, int> dic = new Dictionary <string, int>(); dic.Add("测试1", 1); dic.Add("测试2", 2); dic.Add("cs3", 3); string test = dic.ToJsonString(); LogHelper.Instance.DebugFormat("除非{0},shijian:{1},dd:{2}", "我的", "你的", "他的"); LogHelper.Instance.Debug(test); }
/// <summary> /// 将参数转换成json /// </summary> /// <param name="arguments"></param> /// <returns></returns> private string ConvertArgumentsToJson(IDictionary <string, object> arguments) { try { if (arguments.IsNullOrEmpty()) { return("{}"); } var dictionary = new Dictionary <string, object>(); foreach (var argument in arguments) { if (argument.Value == null) { dictionary[argument.Key] = null; } else { dictionary[argument.Key] = argument.Value; } } return(dictionary.ToJsonString()); } catch (Exception ex) { Logger.Warn(ex.ToString(), ex); return("{}"); } }
private string ConvertArgumentsToJson(IInvocation invocation) { try { var parameters = invocation.MethodInvocationTarget.GetParameters(); if (parameters.IsNullOrEmpty()) { return("{}"); } var dictionary = new Dictionary <string, object>(); for (int i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; var argument = invocation.Arguments[i]; dictionary[parameter.Name] = argument; } return(dictionary.ToJsonString(true)); } catch (Exception ex) { Logger.Warn("Could not serialize arguments for method: " + invocation.MethodInvocationTarget.Name); Logger.Warn(ex.ToString(), ex); return("{}"); } }
/// <summary> /// Post /// </summary> /// <param name="url">请求地址</param> /// <param name="data">请求参数</param> /// <returns></returns> public static async Task <string> PostAsync(string url, Dictionary <string, object> data, string contentType) { string strData = string.Empty; strData = data.ToJsonString(); return(await ExecuteAsync(url, strData, HTTP_TYPE.POST, null, contentType)); }
public void TestDictToJson() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict["one"] = 1; dict["two"] = 2; var str = dict.ToJsonString(); Assert.AreEqual("{\"one\":1,\"two\":2}", str); }
public ActionResult Test01() { Dictionary<string,string>dict = new Dictionary<string, string>() { {"abc","fs"}, {"授命","rwef"} }; return Content(dict.ToJsonString()); }
public Task ReplyOKAsync() { var result = new Dictionary <string, object>() { { "results", "ok" } }; Response = result.ToJsonString(); return(ReplyAsync()); }
/// <summary> /// 把Form转换为json字符串 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string ToJson(this System.Collections.Specialized.NameValueCollection form) { Dictionary <string, string> dic = new Dictionary <string, string>(); for (int i = 0; i < form.Keys.Count; i++) { dic[form.Keys[i]] = form[i]; } return(dic.ToJsonString()); }
public void TestDictToJson() { Dictionary <string, int> dict = new Dictionary <string, int>(); dict["one"] = 1; dict["two"] = 2; var str = dict.ToJsonString(); Assert.AreEqual("{\"one\":1,\"two\":2}", str); }
public void ObjectToJson() { var dic = new Dictionary <string, string> { { this.GetRandom(), this.GetRandom() }, { this.GetRandom(), this.GetRandom() } }; this.WriteLine(dic.ToJsonString()); }
public ActionResult Test01() { Dictionary <string, string> dict = new Dictionary <string, string>() { { "abc", "fs" }, { "授命", "rwef" } }; return(Content(dict.ToJsonString())); }
public override string Render() { var containerBuilder = new TagBuilder("div"); var renderingOptions = this.Builder.GetRenderingOptions(); this.Builder.ApplyPreRenderingChanges(); containerBuilder.AddCssClass("form_builder row"); var controlsTab = RenderControlsTab(renderingOptions); var formTab = RenderFormTab(renderingOptions); var propertiesTab = RenderPropertiesTab(renderingOptions); containerBuilder.InnerHtml = controlsTab + formTab + propertiesTab; containerBuilder.MergeAttributes(this.Builder.htmlAttributes); var availableControls = this.Builder.GetAvailableControls().Select(x => new { Type = x.Type, Text = x.Text, Order = x.Order, Glyphicon = x.Glyphicon.GetDescription(), TabId = x.TabId, ControlName = x.ControlName, Actions = x.Actions != null ? x.Actions.Select(y => y.GetDisplayAttribute().Name).ToList() : new List <string>(), CustomActions = x.CustomActions.Select(y => new { Name = y.Name, Glyphicon = y.Glyphicon.GetDescription(), Title = y.Title }) }); var controlsData = new Dictionary <string, object> { { "controls", availableControls } }; var defaultActionsData = new Dictionary <string, object> { { "actions", this.Builder.GetDefaultActions().Select(x => x.GetDisplayAttribute().Name) } }; var customActionsData = new Dictionary <string, object> { { "actions", this.Builder.GetCustomActions().Select(x => new { Name = x.Name, Title = x.Title, Glyphicon = x.Glyphicon.GetDescription() }) } }; containerBuilder.MergeAttribute("data-controls", controlsData.ToJsonString()); containerBuilder.MergeAttribute("data-defaultactions", defaultActionsData.ToJsonString()); containerBuilder.MergeAttribute("data-customactions", customActionsData.ToJsonString()); return(containerBuilder.ToString()); }
/// <summary> /// 修改次数 /// </summary> /// <param name="fields">需要修改的字段</param> /// <param name="addNums">次数 负数表示减少 正数表示增加</param> /// <param name="whereKey">字典条件</param> /// <param name="opertionUser">操作者信息</param> /// <returns></returns> public static Result UpdateNums(string fields, int addNums, Dictionary <string, object> whereKey, OpertionUser opertionUser) { var ret = BloginfoRepository.Instance.UpdateNums <Bloginfo>(fields, addNums, whereKey); DbLog.WriteDbLog(nameof(Bloginfo), "修改记录", whereKey.ToJsonString(), whereKey, OperLogType.编辑, opertionUser); return(new Result() { IsSucceed = ret > 0, Message = ret.ToString() }); }
/// <summary> /// Edits the specified dicwhere. /// </summary> /// <param name="valuedata">修改的值</param> /// <param name="dicwhere">修改条件</param> /// <param name="opertionUser">操作者信息</param> /// <returns>Result.</returns> public static Result UpdateByWhere(Dictionary <string, object> valuedata, Dictionary <string, object> dicwhere, OpertionUser opertionUser) { var ret = BloginfoRepository.Instance.Update <Bloginfo>(valuedata, dicwhere); DbLog.WriteDbLog(nameof(Bloginfo), "批量修改记录", valuedata.ToJsonString(), valuedata, OperLogType.编辑, opertionUser); return(new Result() { IsSucceed = ret > 0 }); }
/// <summary> /// Adds the specified model. /// </summary> /// <param name="model">The model.</param> /// <param name="opertionUser">操作者信息</param> /// <returns>Result.</returns> public static Result Add(Dictionary <string, object> dicwhere, OpertionUser opertionUser) { var ret = SysmenuRepository.Instance.Add <Sysmenu>(dicwhere); DbLog.WriteDbLog(nameof(Sysmenu), "添加记录", ret, dicwhere.ToJsonString(), opertionUser, OperLogType.添加); return(new Result() { IsSucceed = ret > 0, Message = ret.ToString() }); }
protected override void BuildScriptDescriptor(ScriptComponentDescriptor descriptor) { this.DataBind(); Dictionary <string, object> dictionary = new Dictionary <string, object>(); foreach (ValuePair valuePair in this.Values) { dictionary.Add(valuePair.Name, valuePair.Value); } descriptor.AddScriptProperty("Values", dictionary.ToJsonString(null)); descriptor.AddProperty("Name", this.Name); }
/// <summary> /// 保存到数据库 /// </summary> /// <param name="closeOnSuccess">成功后是否关闭窗口</param> internal void saveToServer(bool closeOnSuccess) { if (_pointModel.Name.IsBlank() || _pointModel.Desc.IsBlank()) { MessageBox.Show(MainWindow.Instance, "请输入点名和描述"); return; } if (_pointModel.Name.StartsWith("/") == false) { MessageBox.Show(MainWindow.Instance, "点名必须以“/”反斜杠为起始字符"); return; } _container.Cursor = Cursors.Hand; try { _pointModel.AddrSetting = _PointJsonDict.ToJsonString(); _pointModel.Address = gatewayClient.GetPointAddress(_PointJsonDict); } catch (Exception ex) { _container.Cursor = null; MessageBox.Show(MainWindow.Instance, ex.Message); return; } Helper.Remote.Invoke <int>("UpdatePoint", (ret, err) => { _container.Cursor = null; if (err != null) { MessageBox.Show(MainWindow.Instance, err); } else { //更新TabItem的文字 this._container.Title = _pointModel.Desc; if (_pointModel.id == null) { //是添加的新点 _pointModel.id = ret; _parentNode.Nodes.Add(new DevicePointNode(_pointModel)); } _pointModel.ChangedProperties.Clear(); OriginalModel.CopyValue(_pointModel); OriginalModel.ChangedProperties.Clear(); if (closeOnSuccess) { //关闭当前document MainWindow.Instance.CloseDocument(_container); } } }, _pointModel); }
public void ReturnsCorrectJsonForDictionary() { IDictionary <string, object> o = new Dictionary <string, object>(); o.Add("a", new Foo { BarInt = 1, BarStr = "bar" }); var result = o.ToJsonString(false, false, false); result.Should().NotBeNullOrWhiteSpace(); result.Should().Be("{ \"a\":{\"BarStr\":\"bar\",\"BarInt\":1} }"); }
/// <summary> /// Deletes the specified kid. /// </summary> /// <param name="dicwhere">删除条件</param> /// <param name="opertionUser">操作者信息</param> /// <returns>Result.</returns> public static Result DeleteByWhere(Dictionary <string, object> dicwhere, OpertionUser opertionUser) { var deldic = new Dictionary <string, object>(); deldic.Add(nameof(Bloginfo.IsDeleted), 1); var ret = BloginfoRepository.Instance.Update <Bloginfo>(deldic, dicwhere); DbLog.WriteDbLog(nameof(Bloginfo), "批量删除记录", dicwhere.ToJsonString(), dicwhere, OperLogType.除, opertionUser); return(new Result() { IsSucceed = ret > 0 }); }
private string getModuleSettingsDiv() { string html = ""; bool themeSupport = getSetting <bool>("ThemeSupport"); bool openAllNodes = getSetting <bool>("OpenAllInitialy"); int AnimationSpeed = getSetting <int>("AnimationSpeed"); Dictionary <string, object> liveSettings = new Dictionary <string, object>(); liveSettings.Add("themeSupport", themeSupport.ToString().ToLower()); liveSettings.Add("openAllNodesInitialy", openAllNodes.ToString().ToLower()); liveSettings.Add("AnimationSpeed", AnimationSpeed); html = "<div class=\"modulesettings\" data-module-settings=\"" + liveSettings.ToJsonString().Replace("\"", "-") + "\"></div>"; return(html); }
public void ReturnsCorrectJsonForDictionaryWithListInternal() { IDictionary <string, object> o = new Dictionary <string, object>(); o.Add("a", new FooWithList { BarInt = 1, BarStr = "bar", BarList = new System.Collections.Generic.List <string> { "x", "y", "z" } }); var result = o.ToJsonString(false, false, false); result.Should().NotBeNullOrWhiteSpace(); result.Should().Be("{ \"a\":{\"BarList\":[\"x\",\"y\",\"z\"],\"BarStr\":\"bar\",\"BarInt\":1} }"); }
private static string GetApiRequestData(HttpRequestMessage request, RequestInfo requestInfo) { string str = ""; Dictionary <string, object> actionArguments = requestInfo.ActionArguments; if (actionArguments != null) { if ((actionArguments.Count == 1) && request.Method.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) { return(actionArguments.First <KeyValuePair <string, object> >().Value.ToJsonString()); } if (actionArguments.Count > 0) { str = actionArguments.ToJsonString(); } return(str); } MediaTypeHeaderValue contentType = request.Content.Headers.ContentType; if (contentType != null) { string str2 = ""; string mediaType = contentType.MediaType; if (string.Equals("application/jsone", mediaType, StringComparison.OrdinalIgnoreCase)) { Stream result = request.Content.ReadAsStreamAsync().Result; int length = (int)result.Length; byte[] buffer = new byte[length]; result.Position = 0L; result.Read(buffer, 0, length); str2 = Convert.ToBase64String(buffer); } else if (string.Equals("application/jsonet", mediaType, StringComparison.OrdinalIgnoreCase)) { Stream stream2 = request.Content.ReadAsStreamAsync().Result; int count = (int)stream2.Length; byte[] buffer2 = new byte[count]; stream2.Position = 0L; stream2.Read(buffer2, 0, count); str2 = Encoding.UTF8.GetString(buffer2); } if (!string.IsNullOrEmpty(str2)) { str = string.Format("{{\"RsaData\":\"{0}\"}}", str2); } } return(str); }
/// <summary> /// Renders the property editor UI elements. /// </summary> /// <param name="html">The HTML.</param> /// <param name="customProperties">The custom properties.</param> /// <returns></returns> public static IHtmlString RenderPropertyEditorUIElements(this HtmlHelper html, IEnumerable <ContentProperty> customProperties) { var defs = new Dictionary <string, IEnumerable <UIElement> >(); foreach (var p in customProperties.Where(x => x.PropertyEditorModel != null && x.PropertyEditorModel is IHasUIElements)) { var uiElements = ((IHasUIElements)p.PropertyEditorModel).UIElements; var filteredUiElements = html.FilterUIElements(uiElements); if (filteredUiElements.Any()) { defs.Add(p.Id.GetHtmlId(), uiElements); } } return(new MvcHtmlString(defs.ToJsonString())); }
public string GetOpenIdByCode(string code) { Dictionary <string, object> dicRst = new Dictionary <string, object>(); try { API api = new API(); //dicRst.Add("openId", api.GetOpenIdByCode(code)); dicRst.Add("openId", code); } catch (Exception ex) { WeChatFramework.ErrorLog.WriteLog(ex); dicRst.Add("errmsg", "出现错误,请联系管理员"); } return(dicRst.ToJsonString()); }
public override Task <string> RPCAsync(SlarkServer server, params object[] rpcParamters) { var lobbyRouterResponse = new Dictionary <string, object>() { { "server", "ws://localhost:5000/lobby" }, { "secondary", "ws://localhost:5000/lobby" }, { "ttl", 1440 } }; if (server is PlayLobbyServer lobby) { lobbyRouterResponse["server"] = lobby.ClientConnectionUrl; lobbyRouterResponse["secondary"] = lobby.ClientConnectionUrl; } return(Task.FromResult(lobbyRouterResponse.ToJsonString())); }
/// <summary> /// 从实体类型初始化实体信息 /// </summary> /// <param name="entityType"></param> public virtual void FromType(Type entityType) { Check.NotNull(entityType, nameof(entityType)); TypeName = entityType.FullName; Name = entityType.GetDescription(); AuditEnabled = true; IDictionary <string, string> propertyDict = new Dictionary <string, string>(); PropertyInfo[] propertyInfos = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo propertyInfo in propertyInfos) { propertyDict.Add(propertyInfo.Name, propertyInfo.GetDescription()); } PropertyNamesJson = propertyDict.ToJsonString(); }
private string ConvertArgumentsToJson(IInvocation invocation) { try { var parameters = invocation.MethodInvocationTarget.GetParameters(); if (parameters.IsNullOrEmpty()) { return "{}"; } var dictionary = new Dictionary<string, object>(); for (int i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; var argument = invocation.Arguments[i]; dictionary[parameter.Name] = argument; } return dictionary.ToJsonString(true); } catch (Exception ex) { Logger.Warn("Could not serialize arguments for method: " + invocation.MethodInvocationTarget.Name); Logger.Warn(ex.ToString(), ex); return "{}"; } }