public void JsonBuilder_OpenArray_Can_Be_Nested_In_OpenProperty() { JsonBuilder target = new JsonBuilder(); Assert.IsTrue(target.OpenObject()); Assert.IsTrue(target.OpenProperty("first")); Assert.IsTrue(target.OpenArray()); Assert.IsTrue(target.WriteValue(1)); target.CloseToken(); target.CloseToken(); Assert.IsTrue(target.OpenProperty("second")); Assert.IsTrue(target.OpenArray()); Assert.IsTrue(target.WriteValue(2)); Assert.AreEqual("{\"first\":[1],\"second\":[2]}", target.Finish()); }
public void SetToCollectionThenUpdatedByAppending_ExpectedJsonPatternReturned() { string document = JsonBuilder .CreateObject() .With("first", SetTo.AnArrayContaining( item => item.With("number", SetTo.Value("one")), item => { })) .And("second", SetTo.Value("test2")) .With("first", Updated.WithAdditionalArrayItems( item => item.With("number", SetTo.Value("three")))) .With("first", Updated.AtIndex(1, item => item.With("aNother", SetTo.Value("NewValue")))); Assert.Equal($@"{{""first"":[{{""number"":""one""}},{{""aNother"":""NewValue""}},{{""number"":""three""}}],""second"":""test2""}}", document); }
public void JsonBuilder_OpenProperty_Rejects_Null_Property_Name() { JsonBuilder target = new JsonBuilder(); Assert.IsTrue(target.OpenObject()); try { target.OpenProperty(null); Assert.Fail(); } catch (ArgumentNullException ex) { Assert.AreEqual(typeof(ArgumentNullException), ex.GetType()); } }
public void JsonBuilder_OpenObject_Can_Be_Nested_In_OpenArray() { JsonBuilder target = new JsonBuilder(); Assert.IsTrue(target.OpenArray()); Assert.IsTrue(target.OpenObject()); Assert.IsTrue(target.OpenProperty("value")); Assert.IsTrue(target.WriteValue(1)); target.CloseToken(); target.CloseToken(); Assert.IsTrue(target.OpenObject()); Assert.IsTrue(target.OpenProperty("value")); Assert.IsTrue(target.WriteValue(2)); Assert.AreEqual("[{\"value\":1},{\"value\":2}]", target.Finish()); }
/// <summary> /// Update index replica number /// </summary> /// <param name="index"></param> /// <param name="numOfReplica"></param> /// <returns></returns> public BaseResponse UpdateIndex(string index, int numOfReplica) { string indexUrl = RESTfulESUrlBuilder.Init().UpdateSetting().Host(clusterName).Url(); string jsonData = JsonBuilder.Init() .StartObject() .BuildPropertyName("index") .StartObject() .BuildPropertyName("number_of_replicas") .BuildValue(numOfReplica) .EndObject() .EndObject() .GetJson(); return(restServiceClient.Put <string, BaseResponse>(indexUrl, jsonData)); }
public string ImportStaging(int clientId) { var client = _clientService.Get(clientId); if (client == null) { return("Client not found"); } var fileConfig = _fileService.GetConfiguration(clientId); if (fileConfig == null) { return($"File configuration not found for client {clientId}"); } if (string.IsNullOrEmpty(fileConfig.OutputPath)) { return($"No output file configuration found for Client: {clientId}"); } var list = GetImported(clientId); var writeFunc = new Dictionary <FileType, Func <List <string> > > { { FileType.CSV, () => CSVBuilder.ReadFromCsvFile(fileConfig.InputPath) }, { FileType.JSON, () => JsonBuilder.ReadFromJsonFile(fileConfig.InputPath) } }; var data = writeFunc[fileConfig.FileType].Invoke(); if (data == null) { return("Import Failed"); } var dto = Mapper.Map <List <string>, List <ImportedContact> >(data); dto.ForEach(item => { item.Phone = ValidatePhoneNumber(item.Phone); var contact = Mapper.Map <ImportedContact, Contact>(item); contact.IsValid = true; contact.ClientId = clientId; _contactRepo.Add(contact); }); return($"Imported {dto.Count} contacts"); }
public void AddProperties() { // Arrange JsonBuilder obj = new JsonBuilder(); string jsonResult; obj.Format = JsonFormat.Minify; // Act obj.AppendProperty("name", "Jon"); obj.AppendProperty("age", 22); jsonResult = obj.ToString(); // Assert Assert.AreEqual(jsonResult, "{\"name\":\"Jon\",\"age\":22}"); }
public void NestedObject() { var json = new JsonBuilder() .StartObject() .Property("game", "chess") .PropertyName("player") .StartObject() .Property("name", "jon") .Property("score", 20) .EndObject() .Property("date", "2017-12-14") .EndObject() .ToString(); AssertJson("{'game':'chess','player':{'name':'jon','score':20},'date':'2017-12-14'}", json); }
private void WaitUntilPageReady() { Stopwatch timeOut = new Stopwatch(); timeOut.Start(); while (timeOut.Elapsed.Seconds <= Convert.ToInt32(JsonBuilder.ReturnParameterAppSettings("DEFAULT_TIMEOUT_IN_SECONDS"))) { string documentState = javaScriptExecutor.ExecuteScript("return document.readyState").ToString(); if (documentState.Equals("complete")) { timeOut.Stop(); break; } } }
public string FieldsToJson() { if (Fields == null || Fields.Count == 0) { throw new ArgumentException("fields cant't be null or empty"); } var jsonBuilder = new JsonBuilder(); jsonBuilder.startObject(); foreach (var variable in Fields) { jsonBuilder.add(variable.Key, variable.Value); } jsonBuilder.endObject(); return(jsonBuilder.toJSON()); }
public void BuscaUsuarioDiferenteDoLogado() { #region Parameters string respostaEsperada = "OK"; string nomeUsuario = "administrator"; string token = JsonBuilder.ReturnParameterAppSettings("VISUALIZER_TOKEN"); #endregion #region Actions FindUserRequest ProcuraUsuario = new FindUserRequest(); ProcuraUsuario.UpdateToken(token); IRestResponse <dynamic> Resposta = ProcuraUsuario.ExecuteRequest(); #endregion Assert.AreEqual(respostaEsperada, Resposta.StatusCode.ToString()); Assert.IsTrue(!Resposta.Content.Contains(nomeUsuario)); }
internal static string BuildXsmtpJson(List <Parameter> parameters, List <MailAddress> to) { JObject obj = new JObject(); JsonBuilder.BuildWithToString(obj, to, "to"); var subJson = JObject.Parse("{}"); foreach (var para in parameters) { JsonBuilder.BuildDirectly(subJson, para.ValueList, para.Key, "%"); } obj["sub"] = subJson; return(WebUtility.UrlEncode(obj.ToString())); }
private string SerializeEntity(EntityEntry <IAuditable> entry) { var jsonBuilder = new JsonBuilder(); foreach (PropertyEntry propertyEntry in entry.Properties) { if (TypeHelper.IsByteArray(propertyEntry.Metadata.ClrType)) { continue; } string name = propertyEntry.Metadata.Name; jsonBuilder.AddProperty(name, propertyEntry.Metadata.ClrType, propertyEntry.CurrentValue); } return(jsonBuilder.ToString()); }
public void AddingPropertiesUsingWithAndAnd_PropertiesAppearInJson() { string document = JsonBuilder .CreateObject() .With("first", SetTo.Value("test1")) .And("second", SetTo.Value("test2")) .With("third", SetTo.Null) .And("fourth", SetTo.Null) .With("fifth", SetTo.Null()) .And("sixth", SetTo.Null()) .With("seventh") .And("eighth"); Assert.Equal( @"{""first"":""test1"",""second"":""test2"",""third"":null,""fourth"":null,""fifth"":null,""sixth"":null,""seventh"":null,""eighth"":null}", document); }
public static List <string> ObtemDados(String query, String[,] arrayDeParam = null) { DataSet ds = new DataSet(); List <string> lista = new List <string>(); using (MySqlCommand cmd = new MySqlCommand(query, GetDBConnection())) { cmd.CommandTimeout = Int32.Parse(JsonBuilder.ReturnParameterAppSettings("DB_CONNECTION_TIMEOUT")); cmd.Connection.Open(); if (arrayDeParam != null) { int i = 0; while (i < arrayDeParam.GetLength(0)) { cmd.Parameters.AddWithValue(arrayDeParam[i, 0], arrayDeParam[i, 1]); i++; } } DataTable table = new DataTable(); table.Load(cmd.ExecuteReader()); ds.Tables.Add(table); cmd.Connection.Close(); } if (ds.Tables[0].Columns.Count == 0) { return(null); } try { for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { lista.Add(ds.Tables[0].Rows[0][i].ToString()); } } catch (Exception) { return(null); } return(lista); }
public void NestedNamedObjects() { var json = new JsonBuilder() .WriteObject(root => root .WriteObject("object1", m => m .WriteProperty("property1", 1) .WriteObject("object1-1", n => n .WriteProperty("property2", 2) ) ) ) .ToString(); Assert.AreEqual( "{object1:{property1:1,object1-1:{property2:2}}}", json ); }
public T Delete <T>(String url, WebHeaderCollection headers, BaseRequest request) { HttpClient httpClient = new HttpClient(); foreach (String key in headers.Keys) { httpClient.DefaultRequestHeaders.Add(key, headers.Get(key)); } HttpRequestMessage requestMessage = new HttpRequestMessage { Content = JsonBuilder.ToJsonString(request), Method = HttpMethod.Delete, RequestUri = new Uri(url) }; HttpResponseMessage httpResponseMessage = httpClient.SendAsync(requestMessage).Result; return(JsonConvert.DeserializeObject <T>(httpResponseMessage.Content.ReadAsStringAsync().Result)); }
public void DeletarTarefaTokenVisualizador() { #region Parameters string idTarefa = "1"; string resultadoEsperado = "Forbidden"; string token = JsonBuilder.ReturnParameterAppSettings("VISUALIZER_TOKEN"); string descricaoErro = "Access denied to delete"; #endregion #region Actions DeleteIssueRequest Delete = new DeleteIssueRequest(idTarefa); Delete.UpdateToken(token); IRestResponse <dynamic> Resposta = Delete.ExecuteRequest(); #endregion Assert.AreEqual(resultadoEsperado, Resposta.StatusCode.ToString()); Assert.IsTrue(Resposta.StatusDescription.Contains(descricaoErro)); }
public void JsonBuilder_WriteValue_Writes_String() { JsonBuilder target = new JsonBuilder(70000, 1); Assert.IsTrue(target.WriteValue(null)); Assert.AreEqual("null", target.Finish()); target.Clear(); Assert.IsTrue(target.WriteValue(string.Empty)); Assert.AreEqual("\"\"", target.Finish()); target.Clear(); Assert.IsTrue(target.WriteValue(Constants.UnicodeRainbowDecoded)); string encoded = target.Finish(); for (int i = 0; i < Constants.UnicodeRainbowEncoded.Length; i++) { Assert.AreEqual(Constants.UnicodeRainbowEncoded[i], encoded[i], "index:{0}", i); } }
public void JsonBuilder_TryResize_Increases_Capacity_And_Preserves_Current_State() { JsonBuilder target = new JsonBuilder(50, 2); Assert.IsTrue(target.OpenArray()); for (int i = 0; i < 10; i++) { Assert.IsTrue(target.WriteValue(i), "index:{0}", i); } Assert.IsTrue(target.TryResize(100)); for (int i = 10; i < 20; i++) { Assert.IsTrue(target.WriteValue(i), "index:{0}", i); } Assert.AreEqual("[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]", target.Finish()); }
public void DeletarUsuarioTokenVisualizador() { #region Parameter string idUsuario = "2"; string respostaEsperada = "Forbidden"; string descricaoErro = "Access denied to delete users"; string token = JsonBuilder.ReturnParameterAppSettings("VISUALIZER_TOKEN"); #endregion #region Actions DeleteUserRequest DeletarUsuario = new DeleteUserRequest(idUsuario); DeletarUsuario.UpdateToken(token); IRestResponse <dynamic> Resposta = DeletarUsuario.ExecuteRequest(); #endregion Assert.AreEqual(respostaEsperada, Resposta.StatusCode.ToString()); Assert.AreEqual(descricaoErro, Resposta.StatusDescription); }
private void Shield() { bool isShield = _Request.Get <bool>("isShield", Method.Post, false) ? false : true; MessageDisplay msgDisplay = CreateMessageDisplay(); bool success = false; using (ErrorScope es = new ErrorScope()) { try { if (isShield) { success = FeedBO.Instance.FiltrateFeed(MyUserID, m_FriendUserID); } else { success = FeedBO.Instance.UnFiltrateFeed(m_FriendUserID); } } catch (Exception ex) { msgDisplay.AddException(ex); } if (success == false) { es.CatchError <ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("targetUserID", m_FriendUserID); json.Set("isShield", isShield); Return(json); //msgDisplay.ShowInfo(this); } }
private void EditCategory() { string categoryName = _Request.Get("name", Method.Post); bool success = false; using (ErrorScope es = new ErrorScope()) { MessageDisplay msgDisplay = CreateMessageDisplay(); if (categoryID == null) { msgDisplay.AddError(new InvalidParamError("categoryID").Message); return; } try { success = BlogBO.Instance.UpdateBlogCategory(MyUserID, categoryID.Value, categoryName); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success == false) { es.CatchError <ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("id", categoryID); json.Set("name", categoryName); Return(json); } }
override public string Convert(object o) { var t = o as Transform; if (t == null) { return("null"); } var json = new JsonBuilder(); json.BeginObject(); json.Name("name"); json.StringValue(t.name); json.Name("position"); json.Value(JsonReflector.Reflect(t.position)); json.Name("rotation"); json.Value(JsonReflector.Reflect(t.rotation)); json.Name("scale"); json.Value(JsonReflector.Reflect(t.localScale)); json.Name("children"); json.BeginArray(); foreach (Transform c in t) { if (c != null) { json.StringValue(c.name); } } json.EndArray(); json.EndObject(); return(json.GetString()); }
public void MultipleNamedComplexObjects() { var json = new JsonBuilder() .WriteObject(root => root .WriteObject("object1", obj1 => obj1 .WriteProperty("prop1", 1) .WriteProperty("prop2", 2) ) .WriteObject("object2", obj2 => obj2 .WriteProperty("prop1", 1) .WriteProperty("prop2", 2) ) ).ToString(); Assert.AreEqual( "{object1:{prop1:1,prop2:2},object2:{prop1:1,prop2:2}}", json ); }
/// <summary> /// 注意,请避免将Return写在try...catch块中,以免发生异常 /// </summary> /// <param name="jsonBuilder"></param> /// <param name="closeDialog"></param> protected void Return(JsonBuilder jsonBuilder, bool closeDialog) { if (IsDialog) { if (closeDialog) { OutputReturnHtml(jsonBuilder.ToString()); } else { DialogReturn = "true"; ResultJson = jsonBuilder.ToString(); } } else { //TODO : 跳转到刚才的页面 } }
public void ToJson(JsonBuilder json) { json.WriteObject( json2 => { if (_lineOptions != null) _lineOptions.ToJson(json); if (_barOptions != null) _barOptions.ToJson(json); if (_pointOptions != null) _pointOptions.ToJson(json); if (_xaxisOptions != null) _xaxisOptions.ToJson(json); if (_legendOptions != null) _legendOptions.ToJson(json); }); }
private void ApplyCommandLineValueOverride([NotNull] JObject configuration, [NotNull] Match match) { var path = match.Groups["path"]?.Value ?? string.Empty; if (string.IsNullOrWhiteSpace(path)) { return; } var group = match.Groups["value"]; JetBrainsHelpers.assume(group != null); var stringValue = group.Success ? group.Value : "true"; JToken value = JsonBuilder.ValueFromString(stringValue); var valueConfiguration = JsonBuilder.Construct(path.Split('/'), value); JsonBuilder.Apply(valueConfiguration, configuration); }
public void AJson_BuilderBasicTests_UseBuilder_Works() { JsonBuilder testBuilder = JsonHelper.MakeRootBuilder(); testBuilder .StartDocument() .StartProperty("name") .StartDocument() .AddProperty("first", "AJ") .AddProperty("last", "Badarni") .AddProperty("age", 26) .End() .StartProperty("children") .StartArray() .StartDocument() .AddProperty("name", "Berlynne") .End() .StartDocument() .AddProperty("name", "Teagan") .End() .StartDocument() .AddProperty("name", "Berlynne") .End() .StartDocument() .AddProperty("name", "Berlynne") .End() .End(); Json output = testBuilder.Finalize(); Assert.IsNotNull(output); Assert.IsFalse(output.HasErrors); output.AssertSourceIsValid(); Json reparsedBeans = JsonHelper.ParseText(output.Data.ToString()); Assert.IsNotNull(reparsedBeans); Assert.IsFalse(reparsedBeans.HasErrors, reparsedBeans.BuildJsonErrorReport()); reparsedBeans.AssertSourceIsValid(); }
protected void Click(By locator) { Stopwatch timeOut = new Stopwatch(); timeOut.Start(); while (timeOut.Elapsed.Seconds <= Convert.ToInt32(JsonBuilder.ReturnParameterAppSettings("DEFAULT_TIMEOUT_IN_SECONDS"))) { try { WaitForElement(locator).Click(); timeOut.Stop(); return; } catch (System.Reflection.TargetInvocationException) { } catch (StaleElementReferenceException) { } catch (System.InvalidOperationException) { } catch (WebDriverException e) { if (e.Message.Contains("Other element would receive the click")) { continue; } if (e.Message.Contains("Element is not clickable at point")) { continue; } throw e; } } throw new Exception("Given element isn't visible"); }
public void JsonBuilder_Writing_Truncates_Object_When_Capacity_Is_Exceeded() { JsonBuilder target = new JsonBuilder(50, 4); Assert.IsTrue(target.OpenObject()); bool succeeded = true; for (int i = 0; succeeded; i++) { if (target.OpenProperty(i.ToString(CultureInfo.InvariantCulture))) { succeeded = target.WriteValue(i); target.CloseToken(); continue; } break; } Assert.AreEqual("{\"0\":0,\"1\":1,\"2\":2,\"3\":3,\"(truncated)\":true}", target.Finish()); }
private void AddCategory() { MessageDisplay msgDisplay = CreateMessageDisplay(); string categoryName = _Request.Get("name", Method.Post); int newCategoryId = 0; bool success = false; using (ErrorScope es = new ErrorScope()) { try { success = MissionBO.Instance.CreateMissionCategory(MyUserID, categoryName, out newCategoryId); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success == false) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("id", newCategoryId); json.Set("name", categoryName); Return(json); } }
private void Add() { MessageDisplay msgDisplay = CreateMessageDisplay(); string groupName = _Request.Get("groupName", Method.Post);//"!"号作为特殊标记 //bool success = false; int newGroupID = 0; using (ErrorScope es = new ErrorScope()) { try { newGroupID = FriendBO.Instance.AddFriendGroup(MyUserID, groupName); } catch (Exception ex) { msgDisplay.AddException(ex); } if (newGroupID == 0) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } if (newGroupID > 0) { JsonBuilder json = new JsonBuilder(); json.Set("groupID", newGroupID); json.Set("groupName", groupName); Return(json); } }
private void Shield() { MessageDisplay msgDisplay = CreateMessageDisplay(); bool isShield = _Request.Get<bool>("isShield", Method.Post, false) ? false : true; bool success = false; using (ErrorScope es = new ErrorScope()) { try { success = FriendBO.Instance.ShieldFriendGroup(MyUserID, m_GroupID, isShield); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success == false) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("groupID", m_GroupID); json.Set("isShield", isShield); Return(json); } }
/// <summary> /// 注意,请避免将Return写在try...catch块中,以免发生异常 /// </summary> /// <param name="jsonBuilder"></param> /// <param name="closeDialog"></param> protected void Return(JsonBuilder jsonBuilder, bool closeDialog) { if (IsDialog) { if (closeDialog) OutputReturnHtml(jsonBuilder.ToString()); else { DialogReturn = "true"; ResultJson = jsonBuilder.ToString(); } } else { //TODO : 跳转到刚才的页面 } }
/// <summary> /// 弹出成功提示 /// </summary> protected void AlertSuccess(string message) { if (IsAjaxRequest) { JsonBuilder json = new JsonBuilder(); json.Set("issuccess", true); json.Set("message", message); AjaxPanelContext.SetAjaxResult(json); } else { //TODO: } }
private void ShieldFeed() { MessageDisplay msgDisplay = CreateMessageDisplay(); int userID = UserBO.Instance.GetCurrentUserID(); int? friendUserID = _Request.Get<int>("frienduserid", Method.Get); if (friendUserID == null) { msgDisplay.AddError(new InvalidParamError("frienduserid").Message); return; } Guid appID = Guid.Empty; try { appID = new Guid(_Request.Get("appID", Method.Get)); } catch { msgDisplay.AddError(new InvalidParamError("appID").Message); return; } int? actionType = _Request.Get<int>("actionType", Method.Get); if (actionType == null) { msgDisplay.AddError(new InvalidParamError("actionType").Message); return; } string type = _Request.Get("shieldType", Method.Post); bool success = false; using (ErrorScope es = new ErrorScope()) { if (type == null || type.Trim() != "1") { try { success = FeedBO.Instance.FiltrateFeed(friendUserID.Value, appID, actionType.Value); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("friendUserID", friendUserID.Value); json.Set("appID", appID); json.Set("actionType", actionType.Value); Return(json); } } else { try { success = FeedBO.Instance.FiltrateFeed(appID, actionType.Value); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("appID", appID); json.Set("actionType", actionType.Value); Return(json); } } if (success == false) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } }
private void EditCategory() { using (new ErrorScope()) { MessageDisplay msgDisplay = CreateMessageDisplay(); string categoryName = _Request.Get("name", Method.Post); if (categoryID == null) { msgDisplay.AddError(new InvalidParamError("categoryID").Message); return; } try { if (MissionBO.Instance.UpdateMissionCategory(MyUserID, categoryID.Value, categoryName)) { JsonBuilder json = new JsonBuilder(); json.Set("id", categoryID); json.Set("name", categoryName); Return(json); } else { CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } catch (Exception ex) { msgDisplay.AddError(ex.Message); } } }
public string ToJson() { var json = new JsonBuilder(); ToJson(json); return json.ToString(); }
private void Shield() { bool isShield = _Request.Get<bool>("isShield", Method.Post, false) ? false : true; MessageDisplay msgDisplay = CreateMessageDisplay(); bool success = false; using (ErrorScope es = new ErrorScope()) { try { if (isShield) success = FeedBO.Instance.FiltrateFeed(MyUserID, m_FriendUserID); else success = FeedBO.Instance.UnFiltrateFeed(m_FriendUserID); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success == false) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("targetUserID", m_FriendUserID); json.Set("isShield", isShield); Return(json); //msgDisplay.ShowInfo(this); } }
/// <summary> /// 注意,请避免将Return写在try...catch块中,以免发生异常 /// </summary> /// <param name="key"></param> /// <param name="value"></param> protected void Return(string key, object value) { JsonBuilder json = new JsonBuilder(); json.Set(key, value, null); Return(json, true); }
/// <summary> /// 注意,请避免将Return写在try...catch块中,以免发生异常 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="closeDialog"></param> protected void Return(string key, object value, bool closeDialog) { JsonBuilder json = new JsonBuilder(); json.Set(key, value, null); Return(json, closeDialog); }
private void Move() { MessageDisplay msgDisplay = CreateMessageDisplay(); int friendGroupID = _Request.Get<int>("groupid", Method.Post, 0); //int[] ids = StringUtil.Split<int>(friendUserIDs, ','); if (CreateGroup) { string groupName = _Request.Get("newgroup", Method.Post); friendGroupID = FriendBO.Instance.AddFriendGroup(MyUserID, groupName); if (HasUnCatchedError) { CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); return; } } bool success = false; using (ErrorScope es = new ErrorScope()) { try { success = FriendBO.Instance.MoveFriends(MyUserID, m_FriendUserIds, friendGroupID); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success == false) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } //成功就返回 if (success) { JsonBuilder json = new JsonBuilder(); json.Set("newGroupID", friendGroupID); json.Set("userIds", m_FriendUserIds); Return(json); //msgDisplay.ShowInfo(this); } }
private void Edit() { string content = _Request.Get("Content", Method.Post, string.Empty, false); CommentType type = _Request.Get<CommentType>("type", Method.Get, CommentType.All); string newContent = null; MessageDisplay msgDisplay = CreateMessageDisplay(); bool success = false; string warningMessage = null; try { using (ErrorScope es = new ErrorScope()) { success = CommentBO.Instance.ModifyComment(MyUserID, commentID.Value, content, type, out newContent); if (success == false) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { if (error is UnapprovedError) { warningMessage = error.Message; //AlertWarning(error.Message); //ShowWarning(error.Message); } else msgDisplay.AddError(error); }); } } } catch (Exception ex) { msgDisplay.AddException(ex); } if (success) Return("content", newContent); else if (warningMessage != null) { JsonBuilder jb = new JsonBuilder(); jb.Set("iswarning", true); jb.Set("message", warningMessage); Return(jb); } }
private void EditCategory() { string categoryName = _Request.Get("name", Method.Post); bool success = false; using (ErrorScope es = new ErrorScope()) { MessageDisplay msgDisplay = CreateMessageDisplay(); if (categoryID == null) { msgDisplay.AddError(new InvalidParamError("categoryID").Message); return; } try { success = BlogBO.Instance.UpdateBlogCategory(MyUserID, categoryID.Value, categoryName); } catch (Exception ex) { msgDisplay.AddException(ex); } if (success == false) { es.CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } } if (success) { JsonBuilder json = new JsonBuilder(); json.Set("id", categoryID); json.Set("name", categoryName); Return(json); } }
/// <summary> /// 注意,请避免将Return写在try...catch块中,以免发生异常 /// </summary> /// <param name="jsonBuilder"></param> protected void Return(JsonBuilder jsonBuilder) { Return(jsonBuilder, true); }